diff --git a/.github/workflows/contract-build.yml b/.github/workflows/contract-build.yml new file mode 100644 index 0000000..b168171 --- /dev/null +++ b/.github/workflows/contract-build.yml @@ -0,0 +1,219 @@ +concurrency: + group: contract-build-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +name: contract-build + +on: + pull_request: + paths: + - "CMakeLists.txt" + - "cmake/**" + - "proto/**" + - "include/**" + - "src/**" + - "tests/**" + - "tools/**" + - "build-lock.json" + - ".github/workflows/contract-build.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + contract: + name: C++20 protobuf/gRPC contract build + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - name: Check out source + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + + - name: Install pinned CMake and Ninja + uses: lukka/get-cmake@56d043d188c3612951d8755da8f4b709ec951ad6 + with: + cmakeVersion: 3.31.6 + ninjaVersion: 1.11.1 + + - name: Install distribution-matched Protobuf and gRPC tools + run: | + sudo apt-get update + python3 - <<'PY' + import json, subprocess + lock = json.load(open("build-lock.json")) + packages = [name + "=" + version for name, version in lock["dependencies"]["package_versions"].items()] + subprocess.run(["sudo", "apt-get", "install", "--yes", "python3", *packages], check=True) + PY + dpkg-query -W nlohmann-json3-dev + dpkg-query -W libgrpc++-dev libgrpc-dev libprotobuf-dev protobuf-compiler protobuf-compiler-grpc libssl-dev zlib1g-dev + + - name: Check build-lock verifier rejection cases + run: python3 -m unittest discover -s tools/tests -v + + - name: Configure C++20 build and protobuf/gRPC generation + run: >- + cmake -S . -B build -G Ninja + -DCMAKE_BUILD_TYPE=RelWithDebInfo + -DRATEGUARD_FETCH_GRPC=OFF + -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON + + - name: Build code-generation smoke and available product contracts + run: cmake --build build --parallel 2 + + - name: Run contract tests + run: ctest --test-dir build --output-on-failure + + - name: Reproduce contracts from a second clean build directory + run: | + cmake -S . -B build-clean -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON + cmake --build build-clean --parallel 2 + ctest --test-dir build-clean --output-on-failure + python3 - <<'PY' + import hashlib, pathlib + def generated(root): + base = pathlib.Path(root) / "generated" + return {str(p.relative_to(base)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in base.rglob("*") if p.is_file()} + first, second = generated("build"), generated("build-clean") + if not first or first != second: + raise SystemExit("Clean code-generation reproduction mismatch") + print(f"Clean reproduction: {len(first)} generated files match") + PY + + - name: Check bounded Docker Unix HTTP transport under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-docker-transport-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_DOCKER_TRANSPORT=ON + cmake --build build-docker-transport-sanitized --parallel 2 --target rateguard_http1_parser_tests rateguard_http1_parser_independent_tests rateguard_http1_parser_allocation_independent_tests rateguard_unix_http_transport_linux_tests rateguard_unix_http_transport_independent_tests rateguard_unix_http_fault_independent_tests + ctest --test-dir build-docker-transport-sanitized --output-on-failure -R '^rateguard[.](http1_parser(_(allocation_)?independent)?|unix_http_transport_(linux|independent)|unix_http_fault_independent)$' + + - name: Check bootstrap inventory and persistence under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-bootstrap-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_BOOTSTRAP=ON -DRATEGUARD_SANITIZE_RUNTIME=ON -DRATEGUARD_SANITIZE_MANIFEST=ON + cmake --build build-bootstrap-sanitized --parallel 2 --target rateguard_bootstrap_inventory_tests rateguard_bootstrap_inventory_independent_tests rateguard_bootstrap_store_tests rateguard_bootstrap_store_independent_tests rateguard_bootstrap_recovery_reader_tests rateguard_bootstrap_recovery_reader_independent_tests rateguard_epoch_artifact_layout_tests rateguard_epoch_artifact_integration_independent_tests + ctest --test-dir build-bootstrap-sanitized --output-on-failure -R '^rateguard[.](bootstrap_(inventory|store|recovery_reader)(_independent)?|epoch_artifact_(layout|integration_independent))$' + + - name: Check durable manifest components under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-manifest-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_MANIFEST=ON + cmake --build build-manifest-sanitized --parallel 2 --target rateguard_manifest_codec_tests rateguard_manifest_store_tests rateguard_manifest_store_independent_tests + ctest --test-dir build-manifest-sanitized --output-on-failure -R '^rateguard[.]manifest_(codec|store|store_independent)$' + + - name: Check configured runtime ownership under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-runtime-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_RUNTIME=ON + cmake --build build-runtime-sanitized --parallel 2 --target rateguard_runtime_owner_tests rateguard_runtime_owner_independent_tests + ctest --test-dir build-runtime-sanitized --output-on-failure -R '^rateguard[.]runtime_owner(_independent)?$' + + - name: Check local supervisor lifecycle under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-supervisor-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_SUPERVISOR=ON + cmake --build build-supervisor-sanitized --parallel 2 --target rateguard_epoch_gate_tests rateguard_epoch_gate_independent_tests + ctest --test-dir build-supervisor-sanitized --output-on-failure -R '^rateguard[.]epoch_gate(_independent)?$' + + - name: Check clock and test fixtures under address/undefined sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-clock-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_CLOCK=ON + cmake --build build-clock-sanitized --parallel 2 --target rateguard_clock_tests rateguard_clock_independent_tests rateguard_clock_linux_smoke + ctest --test-dir build-clock-sanitized --output-on-failure -R '^rateguard[.]clock($|_independent$|_linux$)' + + - name: Check history components under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-history-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_HISTORY=ON + cmake --build build-history-sanitized --parallel 2 --target rateguard_history_inspect rateguard_event_recorder_tests rateguard_history_export_tests rateguard_history_validator_tests rateguard_history_reader_tests rateguard_aggregate_metrics_tests rateguard_history_file_publisher_tests rateguard_strict_reconciliation_tests + ctest --test-dir build-history-sanitized --output-on-failure -R '^rateguard[.](event_recorder|history_export|history_validator|history_reader|aggregate_metrics|history_file_publisher|strict_reconciliation|history_inspector)$' + + - name: Check security fixtures and trusted UTC under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-security-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_SECURITY=ON + cmake --build build-security-sanitized --parallel 2 --target rateguard_tls_compatibility_tests rateguard_trusted_wall_clock_tests rateguard_trusted_wall_clock_independent_tests rateguard_certificate_registry_tests rateguard_certificate_registry_profile_tests rateguard_certificate_registry_independent_tests rateguard_peer_authenticator_tests rateguard_authorization_tests rateguard_peer_authorization_rpc_tests rateguard_client_call_guard_tests rateguard_pinned_client_contract_tests rateguard_pinned_client_rpc_tests + ctest --test-dir build-security-sanitized --output-on-failure -R '^rateguard[.](mtls_compatibility|trusted_wall_clock|trusted_wall_clock_independent|certificate_registry|certificate_registry_profile|certificate_registry_independent|peer_authenticator|authorization|peer_authorization_rpc|client_call_guard|pinned_client_contract|pinned_client_rpc)$' + + - name: Observe pinned SDK TLS session qualification (production cache disabled) + run: | + python3 tools/tests/pinned_client_test_runner.py \ + --binary "$(realpath build/rateguard_pinned_client_rpc_tests)" \ + --fixture tests/fixtures/policy_v1.json \ + --qualify --output build/b3-session-qualification.json + + - name: Observe native trusted UTC source (not deployment acceptance) + run: | + python3 - <<'PY' + import json, pathlib, subprocess + result = subprocess.run(["build/trusted_wall_clock_probe"], text=True, capture_output=True, timeout=10) + data = json.loads(result.stdout) + if result.returncode not in (0, 2) or data.get("trusted") is not (result.returncode == 0): + raise SystemExit("native UTC probe returned an inconsistent result") + record = {"scope": "GitHub hosted Linux only; Docker/target deployment gate remains separate", + "exit_code": result.returncode, "observation": data} + pathlib.Path("build/native-trusted-time.json").write_text(json.dumps(record, indent=2) + "\n") + print(json.dumps(record)) + print("NATIVE_UTC_READY_OBSERVATION" if result.returncode == 0 else "NATIVE_UTC_NOT_READY_DEPLOYMENT_BLOCKED") + PY + + - name: Observe constrained Docker time capabilities (not service deployment) + run: | + python3 tools/probes/docker_time_preflight.py \ + --wall-probe "$(realpath build/trusted_wall_clock_probe)" \ + --clock-probe "$(realpath build/rateguard_clock_linux_smoke)" \ + --image ubuntu:24.04 > build/docker-time-preflight.json + cat build/docker-time-preflight.json | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Capture observed build manifest + run: | + python3 tools/capture_build_manifest.py \ + --source-root . \ + --build-dir build \ + --codegen-tools build/codegen-tools.json \ + --output build/build-manifest.json \ + --build-result passed + cat build/build-manifest.json | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Verify exact observed toolchain against the frozen lock + run: python3 tools/verify_build_manifest.py --lock build-lock.json --manifest build/build-manifest.json + + - name: Preserve the observed build manifest + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: rg001-build-manifest-${{ github.run_id }}-${{ github.run_attempt }} + path: | + build/build-manifest.json + build/native-trusted-time.json + build/docker-time-preflight.json + build/b3-session-qualification.json + build/Testing/Temporary/LastTest.log + build-clean/Testing/Temporary/LastTest.log + build-docker-transport-sanitized/Testing/Temporary/LastTest.log + build-bootstrap-sanitized/Testing/Temporary/LastTest.log + build-manifest-sanitized/Testing/Temporary/LastTest.log + build-runtime-sanitized/Testing/Temporary/LastTest.log + build-supervisor-sanitized/Testing/Temporary/LastTest.log + build-history-sanitized/Testing/Temporary/LastTest.log + build-clock-sanitized/Testing/Temporary/LastTest.log + build-security-sanitized/Testing/Temporary/LastTest.log + if-no-files-found: error + retention-days: 30 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f0e150f --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/build/ +/build-*/ +/CMakeUserPresets.json +.DS_Store +__pycache__/ +*.pyc diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..fcb3a63 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,735 @@ +cmake_minimum_required(VERSION 3.31.6) +project(DistributedRateGuard VERSION 0.1.0 LANGUAGES CXX) + +include(CTest) +include(FetchContent) +find_package(Python3 3.8 REQUIRED COMPONENTS Interpreter) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +option(RATEGUARD_FETCH_GRPC "Fetch the pinned gRPC source and its pinned submodules" OFF) +option(RATEGUARD_REQUIRE_PRODUCT_CONTRACTS "Fail unless product protos and contract tests are present" OFF) + +if(RATEGUARD_FETCH_GRPC) + # This build consumes source-tree targets and does not install dependencies. + set(protobuf_INSTALL OFF CACHE BOOL "" FORCE) + set(utf8_range_ENABLE_INSTALL OFF CACHE BOOL "" FORCE) + set(gRPC_BUILD_TESTS OFF CACHE BOOL "" FORCE) + set(gRPC_INSTALL OFF CACHE BOOL "" FORCE) + set(gRPC_BUILD_CODEGEN ON CACHE BOOL "" FORCE) + set(gRPC_BUILD_GRPC_CPP_PLUGIN ON CACHE BOOL "" FORCE) + set(gRPC_ABSL_PROVIDER module CACHE STRING "" FORCE) + set(gRPC_CARES_PROVIDER module CACHE STRING "" FORCE) + set(gRPC_PROTOBUF_PROVIDER module CACHE STRING "" FORCE) + set(gRPC_RE2_PROVIDER module CACHE STRING "" FORCE) + set(gRPC_SSL_PROVIDER package CACHE STRING "" FORCE) + set(gRPC_ZLIB_PROVIDER package CACHE STRING "" FORCE) + set(protobuf_BUILD_TESTS OFF CACHE BOOL "" FORCE) + set(protobuf_BUILD_PROTOC_BINARIES ON CACHE BOOL "" FORCE) + FetchContent_Declare( + grpc + GIT_REPOSITORY https://github.com/grpc/grpc.git + GIT_TAG v1.85.0 + GIT_SHALLOW FALSE + GIT_SUBMODULES_RECURSE TRUE + ) + FetchContent_MakeAvailable(grpc) + if(TARGET grpc++ AND NOT TARGET gRPC::grpc++) + add_library(gRPC::grpc++ ALIAS grpc++) + endif() + set(RG_GRPC_SOURCE_DIR "${grpc_SOURCE_DIR}") +else() + find_package(Protobuf REQUIRED MODULE) + find_package(gRPC CONFIG REQUIRED) + set(RG_GRPC_SOURCE_DIR "") +endif() + +# Package exports use a namespace; the generation helper uses one stable name. +if(NOT TARGET grpc_cpp_plugin) + if(TARGET gRPC::grpc_cpp_plugin) + add_executable(grpc_cpp_plugin ALIAS gRPC::grpc_cpp_plugin) + else() + find_program(RATEGUARD_GRPC_CPP_PLUGIN NAMES grpc_cpp_plugin REQUIRED) + add_executable(grpc_cpp_plugin IMPORTED GLOBAL) + set_property(TARGET grpc_cpp_plugin PROPERTY IMPORTED_LOCATION "${RATEGUARD_GRPC_CPP_PLUGIN}") + endif() +endif() + +include(cmake/GenerateProto.cmake) +file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/codegen-tools.json" + CONTENT "{\"protoc\":\"$\",\"grpc_cpp_plugin\":\"$\"}\n") + +# Always compile one isolated code-generation fixture so this infrastructure PR +# remains verifiable before the junior-owned product schemas arrive. +rateguard_generate_proto_library( + rateguard_codegen_smoke + PROTO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/cmake/fixtures" + PROTO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/cmake/fixtures/build_smoke.proto" +) +add_executable(rateguard_codegen_smoke_test cmake/fixtures/codegen_smoke.cpp) +target_link_libraries(rateguard_codegen_smoke_test PRIVATE rateguard_codegen_smoke) +add_test(NAME rateguard.codegen_smoke COMMAND rateguard_codegen_smoke_test) + +file(GLOB_RECURSE RATEGUARD_PRODUCT_PROTO_FILES CONFIGURE_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/proto/rateguard/v1/*.proto") +if(RATEGUARD_PRODUCT_PROTO_FILES) + rateguard_generate_proto_library( + rateguard_proto + PROTO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}" + PROTO_FILES ${RATEGUARD_PRODUCT_PROTO_FILES} + ) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/contract_test.cpp") + add_executable(rateguard_contract_tests tests/contract_test.cpp) + target_include_directories(rateguard_contract_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include") + target_link_libraries(rateguard_contract_tests PRIVATE rateguard_proto) + add_test(NAME rateguard.contracts + COMMAND rateguard_contract_tests "${CMAKE_CURRENT_SOURCE_DIR}") + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/contracts/transport_error_test.cpp") + add_executable(rateguard_transport_error_tests + tests/contracts/transport_error_test.cpp) + target_include_directories(rateguard_transport_error_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include") + add_test(NAME rateguard.transport_errors + COMMAND rateguard_transport_error_tests) + elseif(RATEGUARD_REQUIRE_PRODUCT_CONTRACTS) + message(FATAL_ERROR "tests/contracts/transport_error_test.cpp is required") + endif() + elseif(RATEGUARD_REQUIRE_PRODUCT_CONTRACTS) + message(FATAL_ERROR "Product proto files exist but tests/contract_test.cpp is missing") + endif() + add_executable(rateguard_channel_policy_tests tests/channel_policy_test.cpp) + target_include_directories(rateguard_channel_policy_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include") + target_link_libraries(rateguard_channel_policy_tests PRIVATE gRPC::grpc++) + add_test(NAME rateguard.channel_policy COMMAND rateguard_channel_policy_tests) + add_executable(rateguard_retry_behavior_tests tests/retry_behavior_test.cpp) + target_include_directories(rateguard_retry_behavior_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include") + target_link_libraries(rateguard_retry_behavior_tests PRIVATE rateguard_proto) + add_test(NAME rateguard.retry_behavior COMMAND rateguard_retry_behavior_tests) + set_tests_properties(rateguard.retry_behavior PROPERTIES TIMEOUT 20) +elseif(RATEGUARD_REQUIRE_PRODUCT_CONTRACTS) + message(FATAL_ERROR "Product proto files are required but none were found under proto/rateguard/v1") +endif() + +if(BUILD_TESTING) + add_custom_target(capture-build-manifest + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/capture_build_manifest.py" + --source-root "${CMAKE_CURRENT_SOURCE_DIR}" + --build-dir "${CMAKE_BINARY_DIR}" + --grpc-source "${RG_GRPC_SOURCE_DIR}" + --protoc "$" + --grpc-plugin "$" + --output "${CMAKE_BINARY_DIR}/build-manifest.json" + --build-result not-yet-run + BYPRODUCTS "${CMAKE_BINARY_DIR}/build-manifest.json" + VERBATIM + COMMENT "Capturing observed toolchain and source revisions (not a lock validation)" + ) +endif() + +# RG-002 pure arithmetic: no clock/RPC/state ownership in this component. +add_executable(rateguard_bucket_math_tests tests/bucket_math_test.cpp) +target_include_directories(rateguard_bucket_math_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/include") +add_test(NAME rateguard.bucket_math COMMAND rateguard_bucket_math_tests) +add_test(NAME rateguard.bucket_math_oracle + COMMAND "${CMAKE_COMMAND}" -E env "CXX=${CMAKE_CXX_COMPILER}" + "RATEGUARD_REPO_ROOT=${CMAKE_CURRENT_SOURCE_DIR}" + "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/bucket_math_oracle.py") +set_tests_properties(rateguard.bucket_math_oracle PROPERTIES TIMEOUT 60) + +# RG-002 immutable policy, canonical identity, and independent serialization oracle. +find_package(nlohmann_json 3.11.3 EXACT CONFIG REQUIRED) +find_package(OpenSSL 3.0 REQUIRED COMPONENTS Crypto) +add_library(rateguard_policy + src/policy/policy_loader.cpp + src/policy/canonical_codec.cpp) +target_include_directories(rateguard_policy PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}") +target_link_libraries(rateguard_policy PUBLIC nlohmann_json::nlohmann_json OpenSSL::Crypto) +target_compile_options(rateguard_policy PRIVATE -Wall -Wextra -Werror -pedantic) + +add_executable(rateguard_policy_tests tests/policy_test.cpp) +target_link_libraries(rateguard_policy_tests PRIVATE rateguard_policy) +add_test(NAME rateguard.policy + COMMAND rateguard_policy_tests "${CMAKE_CURRENT_SOURCE_DIR}") +add_executable(policy_driver tests/policy_driver.cpp) +target_link_libraries(policy_driver PRIVATE rateguard_policy) +add_test(NAME rateguard.policy_oracle + COMMAND "${CMAKE_COMMAND}" -E env + "RATEGUARD_POLICY_DRIVER=$" + "RATEGUARD_REPO_ROOT=${CMAKE_CURRENT_SOURCE_DIR}" + "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/policy_loader_integration.py") +set_tests_properties(rateguard.policy rateguard.policy_oracle PROPERTIES TIMEOUT 60) + +option(RATEGUARD_SANITIZE_CLOCK "Instrument clock library/tests with address and undefined-behavior sanitizers" OFF) + +# RG-003 verified Linux clock provenance and serialized sticky-fail sampling. +find_package(Threads REQUIRED) +add_library(rateguard_clock src/platform/clock_linux.cpp) +target_include_directories(rateguard_clock PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_clock PUBLIC Threads::Threads) +target_compile_options(rateguard_clock PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_CLOCK) + if(NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + message(FATAL_ERROR "Clock sanitizer checks require a supported GCC/Clang compiler") + endif() + target_compile_options(rateguard_clock PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_clock INTERFACE -fsanitize=address,undefined) +endif() +add_executable(rateguard_clock_tests tests/clock_test.cpp) +target_link_libraries(rateguard_clock_tests PRIVATE rateguard_clock) +add_test(NAME rateguard.clock COMMAND rateguard_clock_tests) +add_executable(rateguard_clock_independent_tests tools/tests/clock_independent_test.cpp) +target_link_libraries(rateguard_clock_independent_tests PRIVATE rateguard_clock) +add_test(NAME rateguard.clock_independent COMMAND rateguard_clock_independent_tests) +add_test(NAME rateguard.clock_clamp_mutation + COMMAND "${CMAKE_COMMAND}" -E env "CXX=${CMAKE_CXX_COMPILER}" + "RG003_SOURCE_ROOT=${CMAKE_CURRENT_SOURCE_DIR}/src" + "RG003_INCLUDE_ROOT=${CMAKE_CURRENT_SOURCE_DIR}/include" + "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/clock_mutation_test.py") +set_tests_properties(rateguard.clock_clamp_mutation PROPERTIES TIMEOUT 120) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_executable(rateguard_clock_linux_smoke tests/clock_linux_smoke_test.cpp) + target_link_libraries(rateguard_clock_linux_smoke PRIVATE rateguard_clock) + add_test(NAME rateguard.clock_linux COMMAND rateguard_clock_linux_smoke) + # Unsupported provenance on the supported Linux lane must FAIL, never skip. + set_tests_properties(rateguard.clock_linux PROPERTIES TIMEOUT 20) +endif() + +# RG-004 compatibility inputs; these are not quota-service integration. +option(RATEGUARD_SANITIZE_SECURITY "Instrument security components/tests with ASan and UBSan" OFF) +add_library(rateguard_security src/security/tls_certificate_verifier.cpp) +target_include_directories(rateguard_security PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_security PUBLIC gRPC::grpc++ OpenSSL::Crypto) +target_compile_options(rateguard_security PRIVATE -Wall -Wextra -Werror -pedantic) +add_library(rateguard_trusted_wall_clock src/security/trusted_wall_clock.cpp) +target_include_directories(rateguard_trusted_wall_clock PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_trusted_wall_clock PUBLIC Threads::Threads) +target_compile_options(rateguard_trusted_wall_clock PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_SECURITY) + if(NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + message(FATAL_ERROR "Security sanitizer checks require GCC or Clang") + endif() + foreach(rg_security_target IN ITEMS rateguard_security rateguard_trusted_wall_clock) + target_compile_options(${rg_security_target} PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(${rg_security_target} INTERFACE -fsanitize=address,undefined) + endforeach() +endif() +add_executable(rateguard_tls_compatibility_tests + tests/security/ephemeral_pki.cpp tests/security/mtls_probe_test.cpp) +target_include_directories(rateguard_tls_compatibility_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_tls_compatibility_tests PRIVATE + rateguard_security rateguard_proto OpenSSL::Crypto Threads::Threads) +add_test(NAME rateguard.mtls_compatibility + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/mtls_probe_output_test.py" + "$") +set_tests_properties(rateguard.mtls_compatibility PROPERTIES TIMEOUT 110) +add_executable(rateguard_trusted_wall_clock_tests tests/security/trusted_wall_clock_test.cpp) +target_link_libraries(rateguard_trusted_wall_clock_tests PRIVATE rateguard_trusted_wall_clock) +add_test(NAME rateguard.trusted_wall_clock COMMAND rateguard_trusted_wall_clock_tests) +add_executable(rateguard_trusted_wall_clock_independent_tests tools/tests/trusted_wall_clock_independent_test.cpp) +target_link_libraries(rateguard_trusted_wall_clock_independent_tests PRIVATE rateguard_trusted_wall_clock) +add_test(NAME rateguard.trusted_wall_clock_independent COMMAND rateguard_trusted_wall_clock_independent_tests) +add_executable(trusted_wall_clock_probe tools/probes/trusted_wall_clock_probe.cpp) +target_link_libraries(trusted_wall_clock_probe PRIVATE rateguard_trusted_wall_clock) + +# Test-only verifier bypass: never linked into the real security library. +set(RG004_MUTANT_SOURCE "${CMAKE_CURRENT_BINARY_DIR}/test-mutants/tls_certificate_verifier_bypass.cpp") +add_custom_command(OUTPUT "${RG004_MUTANT_SOURCE}" + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/generate_mtls_verifier_bypass_mutant.py" + --source "${CMAKE_CURRENT_SOURCE_DIR}/src/security/tls_certificate_verifier.cpp" + --output "${RG004_MUTANT_SOURCE}" + DEPENDS src/security/tls_certificate_verifier.cpp tools/tests/generate_mtls_verifier_bypass_mutant.py + VERBATIM) +add_library(rateguard_security_verifier_mutant STATIC "${RG004_MUTANT_SOURCE}") +target_include_directories(rateguard_security_verifier_mutant PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_security_verifier_mutant PUBLIC gRPC::grpc++ OpenSSL::Crypto) +target_compile_options(rateguard_security_verifier_mutant PRIVATE -Wall -Wextra -Werror -pedantic -Wno-unused-function) +add_executable(rateguard_tls_bypass_mutant tests/security/ephemeral_pki.cpp tests/security/mtls_probe_test.cpp) +target_include_directories(rateguard_tls_bypass_mutant PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_tls_bypass_mutant PRIVATE + rateguard_security_verifier_mutant rateguard_proto OpenSSL::Crypto Threads::Threads) +add_test(NAME rateguard.mtls_verifier_bypass + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/mtls_verifier_bypass_mutation_test.py" + "$") +set_tests_properties(rateguard.mtls_verifier_bypass PROPERTIES TIMEOUT 110) + +# RG-004-B1 typed certificate input; no manifest or request authorization. +add_library(rateguard_certificate_registry src/security/certificate_registry.cpp) +target_include_directories(rateguard_certificate_registry PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_certificate_registry PUBLIC + rateguard_security rateguard_trusted_wall_clock rateguard_policy OpenSSL::Crypto) +target_compile_options(rateguard_certificate_registry PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_SECURITY) + target_compile_options(rateguard_certificate_registry PUBLIC + -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_certificate_registry INTERFACE -fsanitize=address,undefined) +endif() +add_executable(rateguard_certificate_registry_tests + tests/security/certificate_registry_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_certificate_registry_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_certificate_registry_tests PRIVATE rateguard_certificate_registry) +target_compile_options(rateguard_certificate_registry_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.certificate_registry COMMAND rateguard_certificate_registry_tests + "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +add_executable(rateguard_certificate_registry_profile_tests + tests/security/certificate_registry_profile_test.cpp) +target_link_libraries(rateguard_certificate_registry_profile_tests PRIVATE rateguard_certificate_registry) +target_compile_options(rateguard_certificate_registry_profile_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.certificate_registry_profile COMMAND rateguard_certificate_registry_profile_tests + "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +add_executable(rateguard_certificate_registry_independent_tests + tools/tests/certificate_registry_independent_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_certificate_registry_independent_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_certificate_registry_independent_tests PRIVATE rateguard_certificate_registry) +target_compile_options(rateguard_certificate_registry_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.certificate_registry_independent COMMAND rateguard_certificate_registry_independent_tests + "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +set_tests_properties(rateguard.certificate_registry rateguard.certificate_registry_profile + rateguard.certificate_registry_independent PROPERTIES TIMEOUT 120) + +# This separate target deliberately violates one invariant for QA only. +set(RG004_ROOT_PIN_MUTANT "${CMAKE_CURRENT_BINARY_DIR}/test-mutants/certificate_registry_root_pin.cpp") +add_custom_command(OUTPUT "${RG004_ROOT_PIN_MUTANT}" + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/generate_wrong_root_pin_mutant.py" + --source "${CMAKE_CURRENT_SOURCE_DIR}/src/security/certificate_registry.cpp" + --output "${RG004_ROOT_PIN_MUTANT}" + DEPENDS src/security/certificate_registry.cpp tools/tests/generate_wrong_root_pin_mutant.py + VERBATIM) +add_library(rateguard_certificate_registry_mutant STATIC "${RG004_ROOT_PIN_MUTANT}") +target_include_directories(rateguard_certificate_registry_mutant PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_certificate_registry_mutant PUBLIC + rateguard_security rateguard_trusted_wall_clock rateguard_policy OpenSSL::Crypto) +target_compile_options(rateguard_certificate_registry_mutant PRIVATE -Wall -Wextra -Werror -pedantic) +add_executable(rateguard_certificate_registry_root_pin_mutant + tools/tests/certificate_registry_independent_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_certificate_registry_root_pin_mutant PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_certificate_registry_root_pin_mutant PRIVATE rateguard_certificate_registry_mutant) +add_test(NAME rateguard.certificate_registry_root_pin_mutation + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/root_pin_mutation_test.py" + --normal "$" + --mutant "$" + --fixture "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +set_tests_properties(rateguard.certificate_registry_root_pin_mutation PROPERTIES TIMEOUT 250) + +# RG-004-B2 identity/permission inputs; no quota-state implementation. +add_library(rateguard_peer_authenticator src/security/peer_authenticator.cpp) +target_include_directories(rateguard_peer_authenticator PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_peer_authenticator PUBLIC rateguard_certificate_registry gRPC::grpc++) +target_compile_options(rateguard_peer_authenticator PRIVATE -Wall -Wextra -Werror -pedantic) +add_library(rateguard_authorization src/security/authorization_resolver.cpp) +target_include_directories(rateguard_authorization PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_authorization PUBLIC rateguard_peer_authenticator rateguard_proto) +target_compile_options(rateguard_authorization PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_SECURITY) + foreach(rg_auth_target IN ITEMS rateguard_peer_authenticator rateguard_authorization) + target_compile_options(${rg_auth_target} PUBLIC + -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(${rg_auth_target} INTERFACE -fsanitize=address,undefined) + endforeach() +endif() +add_executable(rateguard_peer_authenticator_tests + tests/security/peer_authenticator_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_peer_authenticator_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_peer_authenticator_tests PRIVATE rateguard_peer_authenticator) +target_compile_options(rateguard_peer_authenticator_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.peer_authenticator COMMAND rateguard_peer_authenticator_tests + "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +add_executable(rateguard_authorization_tests + tests/security/authorization_resolver_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_authorization_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_authorization_tests PRIVATE rateguard_authorization) +target_compile_options(rateguard_authorization_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.authorization COMMAND rateguard_authorization_tests + "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +set_tests_properties(rateguard.peer_authenticator rateguard.authorization PROPERTIES TIMEOUT 90) + +# Independent real TLS fixture and isolated test-only unsafe variants. +add_executable(rateguard_peer_authorization_rpc_tests + tools/tests/peer_authorization_rpc_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_peer_authorization_rpc_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_peer_authorization_rpc_tests PRIVATE rateguard_authorization) +target_compile_options(rateguard_peer_authorization_rpc_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.peer_authorization_rpc + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/b2_mutation_test.py" + --normal-rpc "$" + --fixture "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +set_tests_properties(rateguard.peer_authorization_rpc PROPERTIES TIMEOUT 140) + +set(RG_B2_MUTANT_DIR "${CMAKE_CURRENT_BINARY_DIR}/test-mutants/b2") +set(RG_B2_PAIR_MUTANT "${RG_B2_MUTANT_DIR}/authorization_resolver_pair_mutant.cpp") +set(RG_B2_PIN_MUTANT "${RG_B2_MUTANT_DIR}/peer_authenticator_pin_mutant.cpp") +add_custom_command(OUTPUT "${RG_B2_PAIR_MUTANT}" "${RG_B2_PIN_MUTANT}" + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/generate_b2_mutants.py" + --resolver-src "${CMAKE_CURRENT_SOURCE_DIR}/src/security/authorization_resolver.cpp" + --auth-src "${CMAKE_CURRENT_SOURCE_DIR}/src/security/peer_authenticator.cpp" + --out-dir "${RG_B2_MUTANT_DIR}" + DEPENDS src/security/authorization_resolver.cpp src/security/peer_authenticator.cpp + tools/tests/generate_b2_mutants.py + VERBATIM) +add_library(rateguard_authorization_pair_mutant STATIC "${RG_B2_PAIR_MUTANT}") +target_include_directories(rateguard_authorization_pair_mutant PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_authorization_pair_mutant PUBLIC + rateguard_peer_authenticator rateguard_proto) +target_compile_options(rateguard_authorization_pair_mutant PRIVATE -Wall -Wextra -Werror -pedantic) +add_executable(rateguard_peer_authorization_pair_mutant + tools/tests/peer_authorization_rpc_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_peer_authorization_pair_mutant PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_peer_authorization_pair_mutant PRIVATE rateguard_authorization_pair_mutant) +add_library(rateguard_peer_auth_pin_mutant STATIC "${RG_B2_PIN_MUTANT}") +target_include_directories(rateguard_peer_auth_pin_mutant PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_peer_auth_pin_mutant PUBLIC rateguard_certificate_registry gRPC::grpc++) +target_compile_options(rateguard_peer_auth_pin_mutant PRIVATE -Wall -Wextra -Werror -pedantic) +add_executable(rateguard_peer_authenticator_pin_mutant + tests/security/peer_authenticator_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_peer_authenticator_pin_mutant PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_peer_authenticator_pin_mutant PRIVATE rateguard_peer_auth_pin_mutant) +add_test(NAME rateguard.peer_authorization_mutation + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/b2_mutation_test.py" + --normal-rpc "$" + --pair-mutant-rpc "$" + --normal-auth "$" + --pin-mutant-auth "$" + --fixture "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +set_tests_properties(rateguard.peer_authorization_mutation PROPERTIES TIMEOUT 500) + +# RG-004-B3 client trust inputs, not quota/forwarding implementations. +add_library(rateguard_client_call_guard src/security/client_call_guard.cpp) +target_include_directories(rateguard_client_call_guard PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_client_call_guard PUBLIC rateguard_certificate_registry) +target_compile_options(rateguard_client_call_guard PRIVATE -Wall -Wextra -Werror -pedantic) +add_library(rateguard_pinned_peer_rpc_client src/security/pinned_peer_rpc_client.cpp) +target_include_directories(rateguard_pinned_peer_rpc_client PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_pinned_peer_rpc_client PUBLIC + rateguard_client_call_guard rateguard_proto gRPC::grpc++ OpenSSL::Crypto) +target_compile_options(rateguard_pinned_peer_rpc_client PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_SECURITY) + foreach(rg_b3_target IN ITEMS rateguard_client_call_guard rateguard_pinned_peer_rpc_client) + target_compile_options(${rg_b3_target} PUBLIC + -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(${rg_b3_target} INTERFACE -fsanitize=address,undefined) + endforeach() +endif() +add_executable(rateguard_client_call_guard_tests + tests/security/client_call_guard_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_client_call_guard_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_client_call_guard_tests PRIVATE rateguard_client_call_guard) +target_compile_options(rateguard_client_call_guard_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.client_call_guard COMMAND rateguard_client_call_guard_tests + "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +add_executable(rateguard_pinned_client_contract_tests + tests/security/pinned_peer_rpc_client_contract_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_pinned_client_contract_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_pinned_client_contract_tests PRIVATE rateguard_pinned_peer_rpc_client) +target_compile_options(rateguard_pinned_client_contract_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.pinned_client_contract COMMAND rateguard_pinned_client_contract_tests + "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +set_tests_properties(rateguard.client_call_guard rateguard.pinned_client_contract PROPERTIES TIMEOUT 90) + +# Independent sealed-client TLS checks and isolated preflight defect. +add_executable(rateguard_pinned_client_rpc_tests + tools/tests/pinned_peer_rpc_client_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_pinned_client_rpc_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_pinned_client_rpc_tests PRIVATE rateguard_pinned_peer_rpc_client) +target_compile_options(rateguard_pinned_client_rpc_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.pinned_client_rpc + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/pinned_client_test_runner.py" + --binary "$" + --fixture "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +set_tests_properties(rateguard.pinned_client_rpc PROPERTIES TIMEOUT 140) +set(RG_B3_MUTANT "${CMAKE_CURRENT_BINARY_DIR}/test-mutants/client_preflight_bypass.cpp") +add_custom_command(OUTPUT "${RG_B3_MUTANT}" + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/generate_client_preflight_mutant.py" + --source "${CMAKE_CURRENT_SOURCE_DIR}/src/security/client_call_guard.cpp" + --output "${RG_B3_MUTANT}" + DEPENDS src/security/client_call_guard.cpp tools/tests/generate_client_preflight_mutant.py + VERBATIM) +add_library(rateguard_pinned_client_preflight_mutant STATIC + "${RG_B3_MUTANT}" src/security/pinned_peer_rpc_client.cpp) +target_include_directories(rateguard_pinned_client_preflight_mutant PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(rateguard_pinned_client_preflight_mutant PUBLIC + rateguard_certificate_registry rateguard_proto gRPC::grpc++ OpenSSL::Crypto) +target_compile_options(rateguard_pinned_client_preflight_mutant PRIVATE -Wall -Wextra -Werror -pedantic) +add_executable(rateguard_pinned_client_preflight_mutant_tests + tools/tests/pinned_peer_rpc_client_test.cpp tests/security/ephemeral_pki.cpp) +target_include_directories(rateguard_pinned_client_preflight_mutant_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/tests/security") +target_link_libraries(rateguard_pinned_client_preflight_mutant_tests PRIVATE + rateguard_pinned_client_preflight_mutant) +add_test(NAME rateguard.pinned_client_preflight_mutation + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/pinned_client_test_runner.py" + --binary "$" + --mutant "$" + --fixture "${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/policy_v1.json") +set_tests_properties(rateguard.pinned_client_preflight_mutation PROPERTIES TIMEOUT 270) + +# RG-006 per-epoch local lifecycle logic. Real process/manifest integration is pending. +option(RATEGUARD_SANITIZE_SUPERVISOR "Instrument lifecycle tests with ASan and UBSan" OFF) +add_library(rateguard_epoch_gate INTERFACE) +target_include_directories(rateguard_epoch_gate INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_epoch_gate INTERFACE Threads::Threads) +if(RATEGUARD_SANITIZE_SUPERVISOR) + target_compile_options(rateguard_epoch_gate INTERFACE -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_epoch_gate INTERFACE -fsanitize=address,undefined) +endif() +add_executable(rateguard_epoch_gate_tests tests/supervisor/epoch_gate_test.cpp) +target_link_libraries(rateguard_epoch_gate_tests PRIVATE rateguard_epoch_gate) +target_compile_options(rateguard_epoch_gate_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.epoch_gate COMMAND rateguard_epoch_gate_tests) +set_tests_properties(rateguard.epoch_gate PROPERTIES TIMEOUT 30) + +add_executable(rateguard_epoch_gate_independent_tests tests/supervisor/epoch_gate_independent_test.cpp) +target_link_libraries(rateguard_epoch_gate_independent_tests PRIVATE rateguard_epoch_gate) +target_compile_options(rateguard_epoch_gate_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.epoch_gate_independent COMMAND rateguard_epoch_gate_independent_tests) +set_tests_properties(rateguard.epoch_gate_independent PROPERTIES TIMEOUT 30) + +# RG-006 bounded canonical persistence codec. +option(RATEGUARD_SANITIZE_MANIFEST "Instrument manifest components with ASan and UBSan" OFF) +add_library(rateguard_manifest_codec src/supervisor/manifest_codec.cpp) +target_include_directories(rateguard_manifest_codec PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_manifest_codec PRIVATE nlohmann_json::nlohmann_json OpenSSL::Crypto) +target_link_libraries(rateguard_manifest_codec PUBLIC Threads::Threads) +target_compile_options(rateguard_manifest_codec PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_MANIFEST) + target_compile_options(rateguard_manifest_codec PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_manifest_codec PUBLIC -fsanitize=address,undefined) +endif() + +add_library(rateguard_manifest_store src/supervisor/manifest_store.cpp) +target_link_libraries(rateguard_manifest_store PUBLIC rateguard_manifest_codec) +target_compile_options(rateguard_manifest_store PRIVATE -Wall -Wextra -Werror -pedantic) + +add_executable(rateguard_manifest_codec_tests tests/supervisor/manifest_codec_test.cpp) +target_link_libraries(rateguard_manifest_codec_tests PRIVATE rateguard_manifest_codec) +target_compile_options(rateguard_manifest_codec_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.manifest_codec COMMAND rateguard_manifest_codec_tests) +set_tests_properties(rateguard.manifest_codec PROPERTIES TIMEOUT 60) + +add_executable(rateguard_manifest_store_tests tests/supervisor/manifest_store_test.cpp) +target_link_libraries(rateguard_manifest_store_tests PRIVATE rateguard_manifest_store) +target_compile_options(rateguard_manifest_store_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.manifest_store COMMAND rateguard_manifest_store_tests) +add_executable(rateguard_manifest_store_independent_tests tests/supervisor/manifest_store_independent_test.cpp) +target_link_libraries(rateguard_manifest_store_independent_tests PRIVATE rateguard_manifest_store) +target_compile_options(rateguard_manifest_store_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.manifest_store_independent COMMAND rateguard_manifest_store_independent_tests) +set_tests_properties(rateguard.manifest_store rateguard.manifest_store_independent PROPERTIES TIMEOUT 90) + +# RG-006 supervisor ownership across epoch directories under the configured root. +option(RATEGUARD_SANITIZE_RUNTIME "Instrument runtime ownership with ASan and UBSan" OFF) +add_library(rateguard_runtime_owner src/supervisor/runtime_owner.cpp) +target_include_directories(rateguard_runtime_owner PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_runtime_owner PRIVATE nlohmann_json::nlohmann_json OpenSSL::Crypto) +target_link_libraries(rateguard_runtime_owner PUBLIC Threads::Threads) +target_compile_options(rateguard_runtime_owner PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_RUNTIME) + target_compile_options(rateguard_runtime_owner PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_runtime_owner PUBLIC -fsanitize=address,undefined) +endif() + +add_executable(rateguard_runtime_owner_tests tests/supervisor/runtime_owner_test.cpp) +target_link_libraries(rateguard_runtime_owner_tests PRIVATE rateguard_runtime_owner) +target_compile_options(rateguard_runtime_owner_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.runtime_owner COMMAND rateguard_runtime_owner_tests) +add_executable(rateguard_runtime_owner_independent_tests tests/supervisor/runtime_owner_independent_test.cpp) +target_link_libraries(rateguard_runtime_owner_independent_tests PRIVATE rateguard_runtime_owner) +target_compile_options(rateguard_runtime_owner_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.runtime_owner_independent COMMAND rateguard_runtime_owner_independent_tests) +set_tests_properties(rateguard.runtime_owner rateguard.runtime_owner_independent PROPERTIES TIMEOUT 90) + +# RG-005 component checks. Use std::thread for the last-slot contention case. +option(RATEGUARD_SANITIZE_HISTORY "Instrument history component tests with ASan and UBSan" OFF) +function(add_history_test target source name) + add_executable(${target} ${source}) + target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") + target_link_libraries(${target} PRIVATE Threads::Threads) + target_compile_options(${target} PRIVATE -Wall -Wextra -Werror -pedantic) + if(RATEGUARD_SANITIZE_HISTORY) + target_compile_options(${target} PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(${target} PRIVATE -fsanitize=address,undefined) + endif() + add_test(NAME rateguard.${name} COMMAND ${target}) +endfunction() +add_history_test(rateguard_event_recorder_tests tests/event_recorder_test.cpp event_recorder) +add_history_test(rateguard_history_export_tests tests/history_export_test.cpp history_export) +add_history_test(rateguard_history_validator_tests tests/history_validator_test.cpp history_validator) +add_history_test(rateguard_history_reader_tests tests/history_reader_test.cpp history_reader) +add_history_test(rateguard_aggregate_metrics_tests tests/aggregate_metrics_test.cpp aggregate_metrics) +add_history_test(rateguard_history_file_publisher_tests tests/history_file_publisher_test.cpp history_file_publisher) +add_history_test(rateguard_strict_reconciliation_tests tests/strict_reconciliation_test.cpp strict_reconciliation) + +# RG-005 offline structural inspection with an independently supplied plan. +add_executable(rateguard_history_inspect tools/history/inspect_main.cpp) +target_include_directories(rateguard_history_inspect PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") +target_link_libraries(rateguard_history_inspect PRIVATE nlohmann_json::nlohmann_json) +target_compile_options(rateguard_history_inspect PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_HISTORY) + target_compile_options(rateguard_history_inspect PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_history_inspect PRIVATE -fsanitize=address,undefined) +endif() + +add_test(NAME rateguard.history_inspector + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/history_inspector_integration.py" + "$") +set_tests_properties(rateguard.history_inspector PROPERTIES TIMEOUT 60) + +# RG-006 staged bootstrap inventory. Serving and process control remain separate. +option(RATEGUARD_SANITIZE_BOOTSTRAP "Instrument bootstrap components with ASan and UBSan" OFF) +add_library(rateguard_bootstrap_inventory src/supervisor/bootstrap_inventory.cpp) +target_include_directories(rateguard_bootstrap_inventory PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_bootstrap_inventory PRIVATE nlohmann_json::nlohmann_json OpenSSL::Crypto) +target_link_libraries(rateguard_bootstrap_inventory PUBLIC Threads::Threads) +target_compile_options(rateguard_bootstrap_inventory PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_BOOTSTRAP) + target_compile_options(rateguard_bootstrap_inventory PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_bootstrap_inventory PUBLIC -fsanitize=address,undefined) +endif() + +add_executable(rateguard_bootstrap_inventory_tests tests/supervisor/bootstrap_inventory_test.cpp) +target_link_libraries(rateguard_bootstrap_inventory_tests PRIVATE rateguard_bootstrap_inventory) +target_compile_options(rateguard_bootstrap_inventory_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.bootstrap_inventory COMMAND rateguard_bootstrap_inventory_tests) +add_executable(rateguard_bootstrap_inventory_independent_tests tests/supervisor/bootstrap_inventory_independent_test.cpp) +target_link_libraries(rateguard_bootstrap_inventory_independent_tests PRIVATE + rateguard_bootstrap_inventory nlohmann_json::nlohmann_json) +target_compile_options(rateguard_bootstrap_inventory_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.bootstrap_inventory_independent COMMAND rateguard_bootstrap_inventory_independent_tests) +set_tests_properties(rateguard.bootstrap_inventory rateguard.bootstrap_inventory_independent PROPERTIES TIMEOUT 60) + +add_library(rateguard_bootstrap_store src/supervisor/bootstrap_store.cpp) +target_link_libraries(rateguard_bootstrap_store PUBLIC rateguard_bootstrap_inventory rateguard_runtime_owner) +target_compile_options(rateguard_bootstrap_store PRIVATE -Wall -Wextra -Werror -pedantic) + +add_executable(rateguard_bootstrap_store_tests tests/supervisor/bootstrap_store_test.cpp) +target_link_libraries(rateguard_bootstrap_store_tests PRIVATE rateguard_bootstrap_store) +target_compile_options(rateguard_bootstrap_store_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.bootstrap_store COMMAND rateguard_bootstrap_store_tests) +add_executable(rateguard_bootstrap_store_independent_tests tests/supervisor/bootstrap_store_independent_test.cpp) +target_link_libraries(rateguard_bootstrap_store_independent_tests PRIVATE + rateguard_bootstrap_store nlohmann_json::nlohmann_json) +target_compile_options(rateguard_bootstrap_store_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.bootstrap_store_independent COMMAND rateguard_bootstrap_store_independent_tests) +set_tests_properties(rateguard.bootstrap_store rateguard.bootstrap_store_independent PROPERTIES TIMEOUT 90) + + +# RG-006 diagnostic read of existing bootstrap intents; never a fencing token. +add_library(rateguard_bootstrap_recovery_reader src/supervisor/bootstrap_recovery_reader.cpp) +target_link_libraries(rateguard_bootstrap_recovery_reader PUBLIC + rateguard_bootstrap_inventory rateguard_runtime_owner) +target_compile_options(rateguard_bootstrap_recovery_reader PRIVATE -Wall -Wextra -Werror -pedantic) + +add_executable(rateguard_bootstrap_recovery_reader_tests + tests/supervisor/bootstrap_recovery_reader_test.cpp) +target_link_libraries(rateguard_bootstrap_recovery_reader_tests PRIVATE + rateguard_bootstrap_recovery_reader rateguard_bootstrap_store) +target_compile_options(rateguard_bootstrap_recovery_reader_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.bootstrap_recovery_reader COMMAND rateguard_bootstrap_recovery_reader_tests) + +add_executable(rateguard_bootstrap_recovery_reader_independent_tests + tests/supervisor/bootstrap_recovery_reader_independent_test.cpp) +target_link_libraries(rateguard_bootstrap_recovery_reader_independent_tests PRIVATE + rateguard_bootstrap_recovery_reader rateguard_bootstrap_store nlohmann_json::nlohmann_json) +target_compile_options(rateguard_bootstrap_recovery_reader_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.bootstrap_recovery_reader_independent + COMMAND rateguard_bootstrap_recovery_reader_independent_tests) +set_tests_properties(rateguard.bootstrap_recovery_reader rateguard.bootstrap_recovery_reader_independent + PROPERTIES TIMEOUT 120) + + +# RG-006 layout grammar and optional manifest-store recovery diagnostics. +target_link_libraries(rateguard_bootstrap_recovery_reader PUBLIC rateguard_manifest_codec) + +add_executable(rateguard_epoch_artifact_layout_tests + tests/supervisor/epoch_artifact_layout_test.cpp) +target_link_libraries(rateguard_epoch_artifact_layout_tests PRIVATE rateguard_epoch_gate) +target_compile_options(rateguard_epoch_artifact_layout_tests PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_BOOTSTRAP) + target_compile_options(rateguard_epoch_artifact_layout_tests PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_epoch_artifact_layout_tests PRIVATE -fsanitize=address,undefined) +endif() +add_test(NAME rateguard.epoch_artifact_layout COMMAND rateguard_epoch_artifact_layout_tests) +set_tests_properties(rateguard.epoch_artifact_layout PROPERTIES TIMEOUT 30) + +add_executable(rateguard_epoch_artifact_integration_independent_tests + tests/supervisor/epoch_artifact_integration_independent_test.cpp) +target_link_libraries(rateguard_epoch_artifact_integration_independent_tests PRIVATE + rateguard_bootstrap_recovery_reader rateguard_bootstrap_store rateguard_manifest_store + nlohmann_json::nlohmann_json) +target_compile_options(rateguard_epoch_artifact_integration_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.epoch_artifact_integration_independent + COMMAND rateguard_epoch_artifact_integration_independent_tests) +set_tests_properties(rateguard.epoch_artifact_integration_independent PROPERTIES TIMEOUT 120) + +target_link_libraries(rateguard_bootstrap_recovery_reader_tests PRIVATE rateguard_manifest_store) + + +# RG-006 bounded Docker Unix HTTP exchange; process interpretation is separate. +option(RATEGUARD_SANITIZE_DOCKER_TRANSPORT "Instrument Docker transport with ASan and UBSan" OFF) +add_library(rateguard_unix_http_transport STATIC + src/supervisor/http1_parser.cpp + src/supervisor/unix_http_transport.cpp) +target_include_directories(rateguard_unix_http_transport PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(rateguard_unix_http_transport PUBLIC Threads::Threads) +target_compile_options(rateguard_unix_http_transport PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_DOCKER_TRANSPORT) + target_compile_options(rateguard_unix_http_transport PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_unix_http_transport PUBLIC -fsanitize=address,undefined) +endif() +function(add_docker_transport_test target source name) + add_executable(${target} ${source}) + target_link_libraries(${target} PRIVATE rateguard_unix_http_transport) + target_compile_options(${target} PRIVATE -Wall -Wextra -Werror -pedantic) + add_test(NAME rateguard.${name} COMMAND ${target}) + set_tests_properties(rateguard.${name} PROPERTIES TIMEOUT 60) +endfunction() +add_docker_transport_test(rateguard_http1_parser_tests + tests/supervisor/http1_parser_test.cpp http1_parser) +add_docker_transport_test(rateguard_http1_parser_independent_tests + tests/supervisor/http1_parser_independent_test.cpp http1_parser_independent) +add_docker_transport_test(rateguard_http1_parser_allocation_independent_tests + tests/supervisor/http1_parser_allocation_independent_test.cpp http1_parser_allocation_independent) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_docker_transport_test(rateguard_unix_http_transport_linux_tests + tests/supervisor/unix_http_transport_linux_test.cpp unix_http_transport_linux) + add_docker_transport_test(rateguard_unix_http_transport_independent_tests + tests/supervisor/unix_http_transport_independent_test.cpp unix_http_transport_independent) +endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_docker_transport_test(rateguard_unix_http_fault_independent_tests + tests/supervisor/unix_http_fault_independent_test.cpp unix_http_fault_independent) + target_link_options(rateguard_unix_http_fault_independent_tests PRIVATE + "-Wl,--wrap=send" "-Wl,--wrap=poll" "-Wl,--wrap=connect" "-Wl,--wrap=__poll_chk") +endif() diff --git a/README.md b/README.md index 4b227cb..54f6aca 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # DistributedRateGuard -A proposed C++20/gRPC service for per-tenant API admission across replicas. It compares strict per-request authority checks with fixed-Q credits spent locally, measuring coordination cost against a bounded additional burst. +## About + +DistributedRateGuard explores how replicated services can enforce per-tenant API quotas with less coordination. It compares strict authority checks with fixed-Q credits held by replicas, measuring the trade-off between authority traffic and bounded burst allowance. The project includes specifications for deterministic replay and correctness evaluation; quota enforcement and release-level guarantees are still in development. ## Current specification bundle @@ -8,8 +10,8 @@ Read in this order: 1. [PRD revision 8](docs/PRD.md) — product goals and release gates. 2. [SRD revision 5](docs/SRD.md) — normative behavior and test obligations. -3. [HLD revision 4](docs/HLD.md) — proposed process and deployment architecture. -4. [LLD revision 5](docs/LLD.md) — proposed interfaces, state transitions, classes, and implementation order. +3. [HLD revision 5](docs/HLD.md) — proposed process and deployment architecture. +4. [LLD revision 10](docs/LLD.md) — proposed interfaces, state transitions, classes, and implementation order. 5. [Implementation stories](docs/STORIES.md) and [JSON context blocks](docs/context-blocks.json) — planned work and acceptance evidence. 6. [Agile sprint plan](docs/SPRINT-PLAN.md) — minute-based effort estimates, sequence, roles, and acceptance gates. @@ -23,9 +25,9 @@ Live policy changes (PRD-013) and long-operation permits (PRD-014) are deferred. ## Status and implementation notes -The repository currently contains proposed specifications and handoff material; no implementation, tests, benchmarks, or model-checking results are claimed. All product thresholds are goals, not achieved results. +Component implementations are integrated on `feature/distributed-rateguard`: wire/build contracts, immutable policy and fixed-point arithmetic, clock provenance, security/client guards, bounded history and inspection, local lifecycle, durable manifests/intents, runtime ownership and recovery-artifact diagnostics and bounded local Unix HTTP transport. Read the [per-agent scrum log](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/SCRUM-WORK-LOG.md), [build instructions](docs/build.md) and [component evidence](docs/evidence/RG-006-G.md). The [final PR to main](https://github.com/kshiteesh28/DistributedRateGuard/pull/13) remains unmerged. Live quota/forwarding services, real process control and witness integration, release benchmarks and model checking remain pending. All product thresholds remain goals. -The source of truth is the current `main` branch. The local path hint in the context file currently contains documentation only and is not a verified Git checkout. Clone or sync `main` before implementation. Start at **RG-001**. Capture toolchain versions on the actual build host before compiling instead of guessing or claiming an untested lock. Keep enforcement services fail-closed until shared-clock provenance, witness durability, process fencing, and identity fixtures pass. +PRD 8 and SRD 5 on `main` remain the product/behavior contracts; current HLD/LLD and implementation evidence are on `feature/distributed-rateguard` until final promotion. The local path hint in the context file currently contains documentation only and is not a verified Git checkout. Use the relevant review branch for implementation; dependent PRs may stack on a verified feature branch. The primary Ubuntu package lock is based on observed CI. Actual Docker target/image-digest evidence remains open; hosted component tests do not satisfy that deployment gate. Keep enforcement services fail-closed until shared-clock provenance, witness durability, process fencing, and identity fixtures pass. ## Research foundation diff --git a/build-lock.json b/build-lock.json new file mode 100644 index 0000000..66cf3be --- /dev/null +++ b/build-lock.json @@ -0,0 +1,53 @@ +{ + "schema_version": 1, + "lock_status": "validated", + "target": { + "runner_label": "ubuntu-24.04", + "os_id": "ubuntu", + "os_version_id": "24.04", + "architecture": "x86_64", + "language_standard": "C++20", + "dependency_mode": "ubuntu-packages" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "ninja": "1.11.1", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "protoc": "libprotoc 3.21.12" + }, + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "libssl-dev": "3.0.13-0ubuntu3.16", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3", + "nlohmann-json3-dev": "3.11.3-1" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02" + }, + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "validation": { + "validated": true, + "scope": "Primary Ubuntu x86_64 foundation toolchain/package snapshot; generated C++20 contracts, policy/crypto and arithmetic component checks, two clean builds and code-generation repeat verified", + "observed_run": 43353832066, + "observed_commit": "7640975031aee2af2ee7ae855ce88b76115f1569", + "tested_merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "clean_rebuild_and_codegen_match": true + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ] +} diff --git a/cmake/GenerateProto.cmake b/cmake/GenerateProto.cmake new file mode 100644 index 0000000..1f09fc0 --- /dev/null +++ b/cmake/GenerateProto.cmake @@ -0,0 +1,41 @@ +include(CMakeParseArguments) + +function(rateguard_generate_proto_library target) + cmake_parse_arguments(RG "" "PROTO_ROOT" "PROTO_FILES" ${ARGN}) + if(NOT RG_PROTO_ROOT OR NOT RG_PROTO_FILES) + message(FATAL_ERROR "${target}: PROTO_ROOT and at least one PROTO_FILES entry are required") + endif() + + set(generated_sources) + foreach(proto IN LISTS RG_PROTO_FILES) + file(RELATIVE_PATH relative_proto "${RG_PROTO_ROOT}" "${proto}") + get_filename_component(relative_dir "${relative_proto}" DIRECTORY) + get_filename_component(proto_stem "${relative_proto}" NAME_WE) + set(output_dir "${CMAKE_CURRENT_BINARY_DIR}/generated/${target}/${relative_dir}") + set(pb_cc "${output_dir}/${proto_stem}.pb.cc") + set(pb_h "${output_dir}/${proto_stem}.pb.h") + set(grpc_cc "${output_dir}/${proto_stem}.grpc.pb.cc") + set(grpc_h "${output_dir}/${proto_stem}.grpc.pb.h") + + add_custom_command( + OUTPUT "${pb_cc}" "${pb_h}" "${grpc_cc}" "${grpc_h}" + COMMAND "${CMAKE_COMMAND}" -E make_directory "${output_dir}" + COMMAND "$" + "--proto_path=${RG_PROTO_ROOT}" + "--cpp_out=${CMAKE_CURRENT_BINARY_DIR}/generated/${target}" + "--grpc_out=${CMAKE_CURRENT_BINARY_DIR}/generated/${target}" + "--plugin=protoc-gen-grpc=$" + "${proto}" + DEPENDS ${RG_PROTO_FILES} protobuf::protoc grpc_cpp_plugin + COMMENT "Generating C++ protobuf and gRPC sources for ${relative_proto}" + VERBATIM + ) + list(APPEND generated_sources "${pb_cc}" "${grpc_cc}") + endforeach() + + add_library(${target} STATIC ${generated_sources}) + target_include_directories(${target} PUBLIC + "${CMAKE_CURRENT_BINARY_DIR}/generated/${target}") + target_link_libraries(${target} PUBLIC protobuf::libprotobuf gRPC::grpc++) + target_compile_features(${target} PUBLIC cxx_std_20) +endfunction() diff --git a/cmake/fixtures/build_smoke.proto b/cmake/fixtures/build_smoke.proto new file mode 100644 index 0000000..b5800d1 --- /dev/null +++ b/cmake/fixtures/build_smoke.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; + +package rateguard.ci; + +message EchoRequest { + string request_id = 1; +} + +message EchoReply { + string request_id = 1; + bool accepted = 2; +} + +service BuildSmoke { + rpc Echo(EchoRequest) returns (EchoReply); +} diff --git a/cmake/fixtures/codegen_smoke.cpp b/cmake/fixtures/codegen_smoke.cpp new file mode 100644 index 0000000..a7f623b --- /dev/null +++ b/cmake/fixtures/codegen_smoke.cpp @@ -0,0 +1,29 @@ +#include "build_smoke.grpc.pb.h" + +#include +#include + +int main() { + static_assert(std::is_base_of_v); + + rateguard::ci::EchoRequest request; + request.set_request_id("rg001-codegen-smoke"); + + std::string wire; + if (!request.SerializeToString(&wire)) { + return 1; + } + + rateguard::ci::EchoRequest decoded; + if (!decoded.ParseFromString(wire)) { + return 2; + } + + if (decoded.request_id() != "rg001-codegen-smoke") { + return 3; + } + + rateguard::ci::BuildSmoke::Service service; + (void)service; + return 0; +} diff --git a/docs/HLD.md b/docs/HLD.md index 0da9afe..4843379 100644 --- a/docs/HLD.md +++ b/docs/HLD.md @@ -1,6 +1,6 @@ # DistributedRateGuard — High-Level Design -**Revision:** 4 · **Date:** 2026-11-12 · **Status:** Proposed; not implemented or verified +**Revision:** 5 · **Date:** 2026-11-23 · **Status:** Proposed architecture; component implementation/evidence tracked separately **Sources:** [PRD revision 8](PRD.md) and [SRD revision 5](SRD.md), read from main. ## 1. Purpose, scope, and decision status @@ -127,7 +127,7 @@ On authority crash, state-integrity failure or identity change, the epoch enters A strict replica restart may rejoin only if SRD restart conditions and intact authority state are verified; a credit replica cannot reuse its old slot in the epoch. Adapter restart must not introduce a second forward for an attempt; exact idempotence evidence is an LLD decision. Clock mismatch blocks readiness. Transparent promotion or restoration of an old epoch is unsupported. -**A-03 — lifecycle recovery:** One supervisor holds an exclusive local runtime lock and durably records exact container IDs, boot identity and PID start identities before launching each participant. No participant is unregistered or automatically restarted. Confirm stop with runtime inspect plus OS exit evidence for the recorded identity; a reused PID or an absent response is not proof. Supervisor death does not permit a new supervisor to resume service: recovery loads the last inventory, fences/stops every recorded participant including the old authority and witness, confirms exit, then creates a new epoch. On host reboot, verified changed kernel boot identity proves old kernel processes cannot survive, but the supervisor still inventories/stops any newly auto-started containers before activation. Unreadable or untrusted inventory blocks reset until a controlled complete VM shutdown provides positive fencing evidence. A stop command is monotonic and idempotent by operation ID; activation is never inferred from a partially written manifest. +**A-03 — lifecycle recovery:** One supervisor holds the exclusive lock for the deployment's single trusted runtime root across epoch creation, serving and recovery. Before starting a participant, durably record its exact created/stopped container ID, role, slot/incarnation, epoch and policy binding in a launch-intent artifact. OS creation enters a non-serving bootstrap phase. After start, obtain and verify the exact host PID, PID-start identity, boot/time-namespace provenance and container identity while admission remains disabled. Persist those observations before acknowledging activation. Complete inventory, policy, clock, trust and witness readiness are required before the epoch becomes ACTIVE; adapters activate last. No participant is unregistered or automatically restarted. Recovery from supervisor loss reads every recorded intent, including containers whose process identity was never completed, stops each exact container/process and verifies exit before any successor epoch. Existing ownership or manifest acquisition never adopts serving state. Host reboot requires verified changed boot identity plus inventory and cessation of any auto-started containers. Missing or untrusted intent/inventory blocks reset until controlled complete-VM shutdown supplies positive fencing evidence. Stop operations remain monotonic and idempotent by operation ID; partial writes never authorize activation. ## 7. Security and trust @@ -237,3 +237,36 @@ Implementation planning: [LLD class design](LLD.md#17-class-design-and-construct The capacity gate uses the all-delivered-attempt latency population defined in PRD 8 / SRD 5: adapter receipt to terminal response, with errors included and the caller-deadline duration used when no response arrives. The separate timely ALLOW/LIMITED and generator-delivery gates remain mandatory. The authority/witness path remains a single availability failure domain. Its journal flush cost must be measured on the actual Docker Linux VM; no performance claim or shortcut around integrity is permitted. The design documents specify the mechanisms, while shared-clock provenance, durable journal failure behavior, positive process-exit evidence, certificate handling, and the build/dependency lock remain implementation evidence gates. Pin versions from the actual build environment in RG-001; this document does not invent tested versions. This revision does not claim implementation, benchmark results, or release readiness. + +## Startup ordering clarification — 2026-11-23 + +Revision 5 of the HLD and revision 6 of the LLD clarify A-03 without changing PRD 8 or SRD 5. A PID-start identity becomes available after OS process creation. The previous pre-launch wording could not be implemented literally. The selected sequence preserves durable registration before execution and complete verified identity before serving. + +1. Hold ownership of the one configured runtime root. Fresh initialization requires a new root; existing acquisition enters recovery. +2. Create stopped containers and persist the complete fixed launch plan before any container start. +3. Start registered containers with admission disabled. Record exact runtime-observed identity and common clock provenance. +4. Persist every identity. A failed or uncertain write keeps startup unavailable and requires recovery. +5. Construct the complete epoch manifest and validate policy/trust/witness/clock readiness. Activate the epoch and acknowledge participants, with adapters last. +6. After failure, fence every recorded container, including pending-identity entries. An omitted/missing record cannot be replaced by an empty inventory. + +```mermaid +sequenceDiagram + participant S as Supervisor + participant D as Durable artifacts + participant R as Container runtime + participant P as Bootstrap participant + S->>R: Create stopped registered containers + R-->>S: Exact container IDs + S->>D: Persist fixed launch intents + D-->>S: Durable result + S->>R: Start non-serving bootstrap + R->>P: Create process + S->>R: Inspect exact process and clock identity + R-->>S: Verified identity observations + S->>D: Persist identity-complete inventory + D-->>S: Durable result + S->>S: Validate all epoch readiness gates + S->>P: Activate matching epoch and policy +``` + +Runtime ownership is global across epoch directories within the deployment's one trusted configured root. Different configured roots require deployment-level reconciliation before serving; changing that root while an old epoch may act cannot bypass fencing. A fresh ownership claim alone supplies no launch or durability proof. Bootstrap models supply no actual OS observation, authenticated control-channel or persistence guarantee. Those guarantees require the corresponding controller, durable store and participant integration tests. diff --git a/docs/LLD.md b/docs/LLD.md index a623662..2e85df2 100644 --- a/docs/LLD.md +++ b/docs/LLD.md @@ -1,20 +1,22 @@ # DistributedRateGuard — Low-Level Design -**Revision:** 5 · **Date:** 2026-11-12 · **Status:** Proposed design; implementation/evidence pending -**Current source branch:** `main` (the review design has been merged) -**Binding sources:** [PRD revision 8](PRD.md), [SRD revision 5](SRD.md) -**Architecture input:** [proposed HLD revision 4](HLD.md), delivered with this LLD. +**Revision:** 10 · **Date:** 2026-11-25 UTC · **Status:** Proposed design; artifact-layout, manifest-reader and Unix HTTP transport component code present; full recovery orchestration/controller pending, verification tracked separately +**Current source branch:** `feature/distributed-rateguard`; layout contract on `feature/RG-006-epoch-artifact-layout` +**Binding sources:** [PRD revision 8](PRD.md), [SRD revision 5](SRD.md) +**Architecture input:** [proposed HLD revision 5](HLD.md), delivered with this LLD. +**Revision input:** LLD revision 9 from `feature/distributed-rateguard` (integration commit `e2d6aeaef0b9ac4e595eb6c50e26afda3e6ee314`). +**Selected contract input:** `docs/contracts/epoch-artifact-layout-v1.md` from `feature/RG-006-epoch-artifact-layout` (blob `9e262317fd7ea029b48723805bf7b063d1bb78c5`). **Input blob identities before principal review (historical):** PRD `04456d95ed2474700198361db2314c50a73cb300`; SRD `dd82770809e1a56900336070404360c33b3b08a2`; HLD `fb835c70b4d53f1f4bf980dde1f0cd3065212cf3`. ## 1. Scope and implementation status This LLD serves implementers and reviewers of a tenant admission service. A delivers strict quota decisions, B delivers deterministic replay and evaluation, and C delivers fixed-Q credits and independent model/history validation. PRD-013 live policy changes and PRD-014 long-operation permits remain deferred. Multi-host operation, transparent failover, automatic credit reclamation, and continuous cross-epoch quota guarantees are excluded. -The repository root inspected on main contains README and docs; all implementation paths below are proposed. There is no established build layout to preserve. PRD/SRD are binding; SRD §8 explicitly supersedes historical open decisions. The HLD's in-memory authority is a proposal conditional on integrity/fencing decisions. This LLD proposes interfaces and synchronization; §15 lists implementation gates rather than silently resolving product behavior. No code, tests, model checks, benchmarks, or deployment are claimed. +The implementation feature contains component code for RuntimeOwner, InitialEpochClaim, BootstrapInventory, BootstrapStore, BootstrapRecoveryReader, and the pure epoch-artifact layout helper; their boundaries are listed in §17.1 and §21. The Docker process controller, participant activation, complete supervisor lifecycle, and successor-epoch recovery remain integration work. PRD/SRD are binding; SRD §8 explicitly supersedes historical open decisions. The HLD's in-memory authority is a proposal conditional on integrity/fencing decisions. This LLD distinguishes component code from integration and does not claim CI acceptance, release acceptance, benchmark results, production deployment, or complete fencing. ## 2. Modules and dependency graph -All paths in this table are **proposed**. Public means a process boundary; internal means a C++ library boundary. +Public means a process boundary; internal means a C++ library boundary. Rows labeled implemented identify component code present on the integration feature; the remaining rows are proposed or partially implemented and do not imply end-to-end acceptance. | Module/path | Boundary; dependencies | State owned; source | | --- | --- | --- | @@ -25,7 +27,15 @@ All paths in this table are **proposed**. Public means a process boundary; inter | `src/admission/` | Public CheckAdmission; policy, authority client, credits | Bounded in-flight calls; FR-005/006/010 | | `src/authority/` | Internal strict/grant engine plus internal gRPC | Buckets, grant journal, tenant transition order; FR-002/015 | | `src/credits/` | Internal; authority client, clock | Fixed-slot confirmed credit and pending sequence; FR-014–018 | -| `src/supervisor/` and `src/supervisor/witness.*` | Local CLI/control and authenticated witness protocol; process controller, manifest, journal | Independent expected image, journal, inventory and epoch lifecycle; FR-001/007/008 | +| `src/supervisor/` and `src/supervisor/witness.*` | Local CLI/control and authenticated witness protocol; process controller, manifest, journal | Independent expected image, journal, inventory and epoch lifecycle; FR-001/007/008; integration proposed | +| `src/supervisor/runtime_owner.h/.cpp` | Internal; POSIX filesystem and lock ownership | One configured runtime-root owner, anchor/lock identity, fresh/recovery mode, one-use initial claim; implemented component | +| `src/supervisor/unix_http_transport.h/.cpp`, `http1_parser.h/.cpp` | Internal bounded local Docker HTTP transport and pure parser | Immutable socket binding, per-call descriptors and atomic in-flight cap; component code present, verification tracked separately | +| `src/supervisor/bootstrap_inventory.h/.cpp` | Internal immutable value model and canonical codec | Fixed planned roster, observed process identities, monotonic revision and recovery latch; implemented component | +| `src/supervisor/bootstrap_store.h/.cpp` | Internal; RuntimeOwner claim, BootstrapInventory, POSIX durable file operations | Initial epoch intent creation, revision/digest CAS, last durable snapshot and candidate data handoff; implemented component | +| `src/supervisor/epoch_artifact_layout.h` | Pure internal path/name utility; no filesystem access or state | Shared epoch artifact names and checked epoch-directory parse/format; no ownership or fencing capability | +| `src/supervisor/bootstrap_recovery_reader.h/.cpp` | Internal read-only diagnostic scan; recovery-mode RuntimeOwner, BootstrapInventory and ManifestCodec | Bounded scan contract covers recorded intents and optional manifest-store artifacts, including pending identities; bootstrap/optional-manifest reader component code is present; full orchestration pending | +| `src/supervisor/epoch_gate.h` | Internal lifecycle gate and `IProcessController` interface | Fixed single-epoch candidate, commit leases, stop/inspect boundary and local phase; component-verified, not durable successor authorization | +| `src/supervisor/manifest_store.h/.cpp` | Internal POSIX manifest store | Prepared/Active/Draining/Closed manifest snapshots and recovery-only existing open; component-verified, not launch or exit proof | | `adapter/` | Public sample API; admission client | Forwarding attempt state; FR-006 | | `src/events/` | Internal; bounded recorder/export | Event buffers and bounded aggregate metrics; FR-009 | | `tools/loadgen/`, `tools/report/` | Offline CLI; traces and manifest | Schedule, paired samples, gate calculations; FR-013/019 | @@ -238,7 +248,7 @@ The witness appends an ordered hash-chained journal, with flush before acknowled The witness detects declared single-record deletion, version rollback and inconsistent grant results before subsequent authority use. It is not a claim to detect coordinated corruption of both independent images or malicious rollback of the whole host; such evidence is UNKNOWN. Witness/supervisor loss terminates the authority incarnation and blocks reset until all old processes are confirmed stopped. Crash-window, acknowledgment-loss, journal corruption and record-rollback checks are mandatory evidence before this mechanism can satisfy FR-008/AT-09. Added coordination and flush cost may miss performance gates; thresholds must not be reduced to conceal it. -**A-03 — lifecycle recovery:** One supervisor holds an exclusive local runtime lock and durably records exact container IDs, boot identity and PID start identities before launching each participant. No participant is unregistered or automatically restarted. Confirm stop with runtime inspect plus OS exit evidence for the recorded identity; a reused PID or an absent response is not proof. Supervisor death does not permit a new supervisor to resume service: recovery loads the last inventory, fences/stops every recorded participant including the old authority and witness, confirms exit, then creates a new epoch. On host reboot, verified changed kernel boot identity proves old kernel processes cannot survive, but the supervisor still inventories/stops any newly auto-started containers before activation. Unreadable or untrusted inventory blocks reset until a controlled complete VM shutdown provides positive fencing evidence. A stop command is monotonic and idempotent by operation ID; activation is never inferred from a partially written manifest. +**A-03 — lifecycle recovery:** One supervisor holds the exclusive lock for the deployment's single trusted runtime root across epoch creation, serving and recovery. Before starting a participant, durably record its exact created/stopped container ID, role, slot/incarnation, epoch and policy binding in a launch-intent artifact. OS creation enters a non-serving bootstrap phase. After start, obtain and verify the exact host PID, PID-start identity, boot/time-namespace provenance and container identity while admission remains disabled. Persist those observations before acknowledging activation. Complete inventory, policy, clock, trust and witness readiness are required before the epoch becomes ACTIVE; adapters activate last. No participant is unregistered or automatically restarted. Recovery from supervisor loss reads every recorded intent, including containers whose process identity was never completed, stops each exact container/process and verifies exit before any successor epoch. Existing ownership or manifest acquisition never adopts serving state. Host reboot requires verified changed boot identity plus inventory and cessation of any auto-started containers. Missing or untrusted intent/inventory blocks reset until controlled complete-VM shutdown supplies positive fencing evidence. Stop operations remain monotonic and idempotent by operation ID; partial writes never authorize activation. ## 9. mTLS and authorization @@ -447,7 +457,7 @@ The recorded semantic findings are resolved in this revision. Conformance tests, ## 17. Class design and construction contracts -All classes/files below are **planned**. C++20 is the implementation language baseline; use std::variant as Result, not an undeclared exception convention or C++23-only std::expected. Error has category, stable code, retry disposition, commitment (NotCommitted/Possible/Committed) and optional bounded diagnostics; no credential values. Constructors return validated factories when validation can fail. Runtime dependencies outlive services and are injected by reference; no hidden global mutable state. +Unless marked implemented, classes/files below are **planned**. C++20 is the implementation language baseline; use std::variant as Result, not an undeclared exception convention or C++23-only std::expected. Error has category, stable code, retry disposition, commitment (NotCommitted/Possible/Committed) and optional bounded diagnostics; no credential values. Constructors return validated factories when validation can fail. Runtime dependencies outlive services and are injected by reference; no hidden global mutable state. ### 17.1 Class ownership and interfaces @@ -462,14 +472,20 @@ Signatures are contract sketches; strong domain types and cancellation/deadline | LinuxMonotonicClock / src/platform/clock_linux.h | Verified boot/namespace/clock identity | Implements IClock; syscall/provenance/backwards failures return typed integrity error | | PeerAuthenticator / src/security/peer_authenticator.h | Immutable trust registry + trusted wall-time provider | Authenticate(TransportPeer)→Result; role/SAN/EKU/expiry checked every RPC | | AuthorizationResolver / src/security/authorization.h | PolicySnapshot reference | Resolve(peer,tenant,operation)→Result; sole constructor of trusted operation/cost | -| EpochGate / src/supervisor/epoch_gate.h | Atomic observed phase + epoch identity | ObserveDrain, PermitCommit(expectedEpoch), Phase; transitions monotonic ACTIVE→DRAINING→CLOSED | +| EpochGate / src/supervisor/epoch_gate.h (component-verified) | Mutex-protected shared fixed-epoch candidate, lifecycle phase, in-flight commit count; injected `IProcessController` | Create, Activate, TryAcquireCommitPermit, BeginDrain, FenceAndClose, phase; PreActivation→Active→Draining→Closed. This gate is local to one candidate and cannot authorize a successor epoch | +| IProcessController / src/supervisor/epoch_gate.h (implemented interface only) | Abstract boundary injected into EpochGate; no concrete Docker implementation | RequestStop(exact participant, operation ID), Inspect(exact participant); errors/unknown states do not count as positive exit | +| RuntimeOwner / src/supervisor/runtime_owner.h + runtime_owner.cpp (implemented component) | Exclusive lock and immutable anchor for one configured runtime root; process identity and owner validation | CreateNew, OpenExisting, ValidateOwnership, ClaimInitialEpoch; existing roots are recovery-only and cannot mint a fresh claim | +| InitialEpochClaim / src/supervisor/runtime_owner.h (implemented component) | Move-only one-use capability retaining the RuntimeOwner lock state | Supplies validated domain/epoch ownership and a duplicated root descriptor; proves neither process launch nor fencing | +| BootstrapInventory / src/supervisor/bootstrap_inventory.h + bootstrap_inventory.cpp (implemented component) | Immutable planned roster, observations, canonical digest inputs, revision and recovery state | Create, RecordIdentity, RequireRecovery, ReadyCandidate; exact replay is idempotent, identity mismatch irreversibly requires recovery | +| BootstrapStore / src/supervisor/bootstrap_store.h + bootstrap_store.cpp (implemented component) | InitialEpochClaim plus durable per-epoch intent file and last committed snapshot | CreateNew, RecordIdentity(revision,digest CAS), ReadyCandidate; distinguishes NotVisible, Durable and VisibleDurabilityUnknown; uncertainty blocks further writes | +| BootstrapRecoveryReader / src/supervisor/bootstrap_recovery_reader.h + bootstrap_recovery_reader.cpp (component code present) | Read-only bounded scan; recovery-mode RuntimeOwner, bootstrap decoder, and manifest codec | `Read(owner,test_io) → variant, RecoveryReaderFatal>`; returns diagnostic inventories/manifests/issues, including pending process identities; no claim, candidate, store, stop proof or fencing capability | | TenantLedger / src/authority/tenant_ledger.h | Mutex, immutable identity, bucket, fixed grant-result array, version, reservation state | BeginReservation→Result; ReadSnapshot; no public balance setter | | TenantReservation / src/authority/tenant_reservation.h | Move-only reservation token, original version/snapshot, phase | ValidateSnapshot, CommitCandidate, CompleteAck, Fail; only this token can change the reserved tenant | | BucketMath / src/authority/bucket_math.h | Stateless production arithmetic | Refill, Decide, RetryDelay; checked 128-bit D3 arithmetic, never accesses clock or global state | | IStateWitness / src/authority/witness_port.h | Abstract authority boundary | Validate, Commit, QueryAck; exact identity/fingerprint/version per §16.1 | | LocalStateWitnessClient / src/authority/local_witness_client.h | Unix-socket client bound to supervisor identity; implements IStateWitness | Validate, Commit, QueryAck; authenticates expected server and keeps exact transaction fingerprint | | WitnessServer / src/supervisor/witness_server.h | Supervisor-owned local socket; refs peer identity, WitnessStateMachine and JournalWriter | Dispatch validated authority requests; reject unrelated process identity before touching witness state | -| DockerProcessController / src/supervisor/docker_process_controller.h | Implements IProcessController using local runtime API and recorded identities | Start, InspectIdentity, Stop, ConfirmExited; never infer exit from missing network reply | +| DockerProcessController / proposed `src/supervisor/docker_process_controller.h` | Future adapter over the local container runtime and durable bootstrap inventory | Create stopped containers, StartNonServing, InspectIdentity, Stop, ConfirmExited; not implemented. Never infer exit from missing runtime response | | WitnessStateMachine / src/supervisor/witness_state.h | Independent expected tenant images and last acknowledgments; own arithmetic validator | ValidateSnapshot, ValidateTransition, PublishAck; cannot import BucketMath as its validator | | JournalWriter / src/supervisor/journal_writer.h | Single joined worker, append fd, chain/index, fixed queue and 2 GiB budget | AppendAndFlush→Result; ack only after flush; no active-epoch recovery | | AuthorityEngine / src/authority/authority_engine.h | Preloaded TenantLedger objects; refs clock, witness, policy, gate, recorder | StrictCheck, AllocateCredit, ReplayGrant; private shared ExecuteTransition follows reservation/ack protocol | @@ -481,8 +497,7 @@ Signatures are contract sketches; strong domain types and cancellation/deadline | AuthorityService / src/authority/authority_service.h | Internal gRPC facade; refs auth and AuthorityEngine | StrictCheck and AcquireCredit RPCs; only registered replica identity can call | | ForwardAttempt / adapter/forward_attempt.h | Attempt ID, deadline, atomic Pending/ForwardStarted/Expired/Failed | TryForwardTransition; exactly one CAS winner; does not retry backend automatically | | SampleAdapter / adapter/sample_adapter.h | Trusted fixture mapping and bounded active ForwardAttempt objects | Handle; derive authorized context, call admission, enforce receipt/epoch/deadline, never replay after crash | -| ManifestStore / src/supervisor/manifest_store.h | Supervisor-owned directory/lock fd; immutable validated manifest snapshots | Load, AtomicReplace; fsync/rename/dir-fsync failures prevent activation; no anti-rollback claim from rename | -| IProcessController / src/supervisor/process_controller.h | Abstract local runtime boundary | Start, InspectIdentity, Stop, ConfirmExited; identity includes boot/container/PID-start values | +| ManifestStore / src/supervisor/manifest_store.h/.cpp (component-verified) | Caller-supplied directory/lock fd; immutable validated manifest snapshots | CreateNew, OpenExisting, snapshot, digest, Transition; existing opens are recovery-only; caller must compose the exact `/epoch-/manifest-store` path under validated global ownership; layout strings do not grant path authority; fsync/rename/directory-fsync uncertainty blocks writes; no anti-rollback claim from rename | | EpochSupervisor / src/supervisor/epoch_supervisor.h | Exclusive control thread, inventory/operation state, WitnessStateMachine, JournalWriter | StartEpoch, Drain, FenceAndClose, RecoverAfterCrash; never adopts old ACTIVE epoch | | EventRecorder / src/events/event_recorder.h | Fixed run-wide budget, producer sequences and reserved slots | Reserve→Result, Publish, SealIncomplete; no identifiers as metric labels | | HistoryExporter / src/events/history_exporter.h | Bounded streaming file writer | Export with count/hash/complete markers; cleanup follows D7; missing producer seal yields incomplete | @@ -492,6 +507,60 @@ Signatures are contract sketches; strong domain types and cancellation/deadline | HistoryChecker / tools/history_checker/checker.h | Independent parser/model/config | Check, ExplainCounterexample; prefix interval check plus serial/provenance validation; UNKNOWN on missing evidence/resource limit | | ModelHarness / model/runner | Pinned external model-check tool/config | EnumerateDeclaredBounds, Mutate, ExportCounterexample; tool output cannot self-certify production code | +The recovery-reader dependency boundary is read-only: + +```mermaid +classDiagram + class RuntimeOwner { + +OpenExisting(root, domain) + +mode() + +ValidateOwnership() + +DuplicateRootFd() + } + class BootstrapStore { + +CreateNew(claim, plan) + +RecordIdentity(revision, digest, observed) + +ReadyCandidate() + } + class BootstrapRecoveryReader { + +Read(owner, test_io) + } + class BootstrapRecoverySnapshot { + +domain_id + +scan_complete + +epochs + +issues + +issues_truncated + } + class RecoveryEpochDiagnostic { + +directory_name + +intent_identity + +canonical_digests + +issues + +issues_truncated + } + class BootstrapInventory { + +records() + +recovery_required() + } + class ManifestV1 { + +candidate + +phase + +generation + } + BootstrapRecoveryReader ..> RuntimeOwner : validates mode and duplicates root + BootstrapRecoveryReader ..> BootstrapInventory : bounded intent decode + BootstrapRecoveryReader ..> ManifestV1 : bounded manifest decode + BootstrapRecoveryReader --> BootstrapRecoverySnapshot : diagnostic result + BootstrapRecoverySnapshot o-- RecoveryEpochDiagnostic : per-epoch results + RecoveryEpochDiagnostic o-- BootstrapInventory : optional intent model + RecoveryEpochDiagnostic o-- ManifestV1 : optional manifest model + BootstrapStore *-- InitialEpochClaim : consumes and retains lock capability + BootstrapStore ..> BootstrapInventory : durable initial writes +``` + +The shared `epoch_layout_v1` helper is a pure header utility, not a service or capability. It defines the literal names `epoch-`, `intent.json`, `intent.tmp`, `manifest-store`, `owner.lock`, `manifest.json`, and `manifest.tmp`, plus checked `ParseEpochDirectoryName` / `FormatEpochDirectoryName` functions. Parsing accepts only the exact `epoch-<32 lowercase hexadecimal digits>` form for a nonzero ID; formatting rejects a zero ID and reports allocation failure. BootstrapStore, BootstrapRecoveryReader, and ManifestStore reuse these names. The helper performs no filesystem checks and cannot grant path ownership. + ### 17.2 Construction, lifetime and threading ServiceRuntime owns instances in dependency order: validated policy/trust/clock → gate/recorder → ledger/witness/client → engines/services → servers. Stop reverses admission: reject new RPCs, mark DRAINING, wake CV waiters, cancel bounded transport waits, join workers, seal/export available histories, destroy services, then dependencies. A crash bypassing graceful shutdown triggers incomplete evidence and supervisor fencing. No detached task may retain raw pointers to destroyed services; pending operations hold owned request buffers and validated snapshot shared_ptrs. @@ -500,12 +569,17 @@ TenantReservation is move-only. Destruction before CommitCandidate cancels reser JournalWriter owns its descriptor and joined worker exclusively. Queue capacity is fixed at 1,024 transition records, each bounded to 16 KiB; reservation/queue acquisition occurs before commit so overload cannot silently strand a postcommit append. Per-tenant ordering and durable indices are maintained; batching never changes commit timestamps. Grant result snapshots contain ≤8 fixed-slot records, so encoding must be size-validated at startup; configuration whose transition record cannot fit is rejected before traffic. Existing in-flight records finish or become uncertain when the 2 GiB cap/IO failure occurs. Supervisor continues to account old credit holders until CLOSED. -AuthorityService exposes both the strict internal check and credit grant port. AdmissionService never exposes the witness socket or a balance-reset endpoint. Only Supervisor constructs a new epoch and authority identity; local mutexes cannot authorize a second authority instance. IProcessController positively verifies identity/exit; container names alone cannot prove fencing. +AuthorityService exposes both the strict internal check and credit grant port. AdmissionService never exposes the witness socket or a balance-reset endpoint. Only Supervisor constructs a new epoch and authority identity; local mutexes cannot authorize a second authority instance. The `IProcessController` contract requires identity-bound stop/inspection evidence; the interface alone and container names alone do not prove that an OS process exited. ### 17.3 Class collaboration ```mermaid classDiagram + RuntimeOwner --> InitialEpochClaim : issues once for fresh root + BootstrapStore *-- InitialEpochClaim : consumes and retains + BootstrapStore --> BootstrapInventory : durable CAS snapshots + BootstrapInventory --> EpochCandidate : complete roster data only + EpochGate --> EpochCandidate : validates fixed candidate AdmissionService --> AuthorizationResolver AdmissionService --> IAuthorityClient AdmissionService --> CreditManager @@ -530,11 +604,13 @@ classDiagram CreditManager --> EventRecorder ``` -Class-level seam acceptance: substitute IClock, IAuthorityClient, IStateWitness and IProcessController through constructors only. Test duplicate RPC callbacks against ReplicaTenantCredits; injected mutation during reservation against TenantLedger/WitnessStateMachine; fsync/ack loss against JournalWriter/AuthorityEngine; forwarding races against ForwardAttempt; all stop/fencing outcomes against EpochSupervisor. Independent ReplayModel/HistoryChecker use only versioned artifacts and policy input, not production decision functions. Every proposed class maps to a story in [implementation stories](STORIES.md) and the machine-readable [context blocks](context-blocks.json). +The `InitialEpochClaim` edge is a move-only capability that retains root-lock ownership; `BootstrapStore` consumes and owns it. `BootstrapInventory` can produce only complete candidate data. The diagram does not imply that `ReadyCandidate` activates the gate or authorizes a later epoch. + +Class-level seam acceptance: substitute IClock, IAuthorityClient, IStateWitness and IProcessController through constructors only. Test duplicate RPC callbacks against ReplicaTenantCredits; injected mutation during reservation against TenantLedger/WitnessStateMachine; fsync/ack loss against JournalWriter/AuthorityEngine; forwarding races against ForwardAttempt; lifecycle gate outcomes against EpochGate. Concrete Docker stop/exit evidence and full recovery remain integration requirements. Independent ReplayModel/HistoryChecker use only versioned artifacts and policy input, not production decision functions. Every proposed class maps to a story in [implementation stories](STORIES.md) and the machine-readable [context blocks](context-blocks.json). ### 17.4 Per-process composition -SupervisorRuntime owns ManifestStore, DockerProcessController, EpochSupervisor, WitnessServer, WitnessStateMachine and JournalWriter. AuthorityRuntime owns TenantLedgers, AuthorityEngine/AuthorityService and LocalStateWitnessClient; it never shares a pointer to supervisor witness memory. ReplicaRuntime owns AdmissionService, CreditManager and GrpcAuthorityClient. AdapterRuntime owns SampleAdapter and its gRPC admission client. Evaluation tools own independent ReplayModel/HistoryChecker. ServiceRuntime refers to this per-process construction pattern; it is not one address space for all components. All cross-process transitions use the explicit authenticated ports. +The intended SupervisorRuntime composition is RuntimeOwner, BootstrapStore, BootstrapRecoveryReader, ManifestStore, EpochGate, DockerProcessController, EpochSupervisor, WitnessServer, WitnessStateMachine and JournalWriter. RuntimeOwner, InitialEpochClaim, BootstrapInventory, BootstrapStore and BootstrapRecoveryReader are the RG-006 components described in §21; EpochGate and ManifestStore are previously component-verified. `IProcessController` is currently an interface declared in `epoch_gate.h` with stop-request and inspection operations; no concrete Docker controller or durable process-launch/exit acknowledgment path is implemented. The bootstrap and optional-manifest reader components are implemented; full recovery orchestration/controller, participant activation and successor-epoch recovery remain pending. AuthorityRuntime owns TenantLedgers, AuthorityEngine/AuthorityService and LocalStateWitnessClient; it never shares a pointer to supervisor witness memory. ReplicaRuntime owns AdmissionService, CreditManager and GrpcAuthorityClient. AdapterRuntime owns SampleAdapter and its gRPC admission client. Evaluation tools own independent ReplayModel/HistoryChecker. ServiceRuntime is a per-process construction pattern, not one address space for all components. All cross-process transitions use the explicit authenticated ports. Witness Validate pre-reserves a bounded journal queue slot and maximum record byte budget before returning permission to prepare a transition; no automatic eviction/lease expiry can remove it while the authority may commit. It is released only on explicit precommit abort, committed acknowledgment, or fenced epoch shutdown. This prevents postcommit capacity rejection from becoming an unrecorded ordinary overload. Duplicate Validate with identical transaction identity returns its existing reservation. Only crashes/I/O/integrity failures can invalidate a postcommit reservation, and those follow DRAINING/uncertainty rules. @@ -543,4 +619,132 @@ Witness Validate pre-reserves a bounded journal queue slot and maximum record by PRD 8 / SRD 5 define the p99 population as all delivered attempts, including error responses; a missing response contributes the caller-deadline duration. The latency measurement begins at adapter receipt and ends at the first terminal application response or deadline. This prevents completion-only sampling from hiding timed-out calls. -The implementation toolchain is intentionally not pre-pinned in this document: the current local path has documentation only and no verified Git checkout or Linux build environment. RG-001 must capture compiler, CMake, gRPC, Protocol Buffers, crypto, and model-tool versions from the actual supported build host and produce a successful reproducible build before the lock is treated as validated. This is a sequencing decision, not a guessed compatibility matrix. Clock, witness, fencing, and certificate tests remain required before activating enforcement services or claiming acceptance. No implementation or evidence is claimed here. +The implementation toolchain and component evidence are tracked with the integration feature and RG-001 build records. A successful component build does not establish Docker runtime identity, participant activation, recovery fencing, performance gates, or release acceptance. Clock, witness, fencing, certificate, and end-to-end integration evidence remain required before activating enforcement services or claiming acceptance. + + +## 19. RG-002 representation addendum — version 1 + +[Canonical policy v1 revision 1](contracts/policy-v1.md) fixes the aggregate byte/JSON layout and finite startup parsing caps before codec implementation. It preserves D3 quotas, fixed membership, full-B initialization in §5, identity roles in §9, and release/deferred scope. The loader normalizes input order and rejects duplicates; a digest cannot depend on JSON iteration order. The public trust fingerprint belongs in canonical bytes; live CA/X.509 validation remains RG-004, so offline policy replay does not need exported certificates. + +The implementation uses immutable sorted vectors with binary-search lookups and no insertion for unknown IDs. This is a recorded implementation choice replacing the proposed hash-table estimate in §14: lookup is O(log T), with bounded T≤10,000; canonical bytes remain independent of this storage choice. Performance gates remain measurements, not assertions. The representation record is a versioned implementation decision; it does not claim the policy code or its acceptance evidence exists yet. + + +## 20. RG-003 clock implementation addendum — version 1 + +[Linux clock v1](contracts/clock-v1.md) fixes the internal provenance grammar, Linux namespace source checks, mandatory manifest matching and initial successful clock sample, and serialized sticky failure behavior before component acceptance. Namespace offsets describe the children namespace, so current/children device and inode must agree across all four startup snapshots. A process-leader startup probe precedes worker creation; runtime namespace changes are prohibited. + +Sampling uses the shared CLOCK_MONOTONIC source; lock direction is tenant transition → process clock. Factory success is clock-component readiness, not authority/replica activation: RG-006 must verify every participant and trusted manifest. Actual commit/deadline mapping remains RG-007/008 and strict UNKNOWN history semantics the RG-011A/005 Release A evidence gate, extended by RG-013 for C. Inadequate clock/history provenance cannot produce a safety PASS in A; this obligation is not deferred to the formal checker. A local or fork/exec smoke test alone cannot claim the Docker shared-clock premise or a quota bound. This addendum records implementation decisions, not completed tests or measured latency. + +## Startup ordering clarification — 2026-11-23 + +Revision 5 of the HLD and revision 7 of the LLD clarify A-03 without changing PRD 8 or SRD 5. A PID-start identity becomes available after OS process creation. The previous pre-launch wording could not be implemented literally. The selected sequence preserves durable registration before process start and complete verified identity before serving. + +1. Hold ownership of the one configured runtime root. Fresh initialization requires a new root; existing acquisition enters recovery. +2. Create stopped containers and persist the complete fixed launch plan before any container start. +3. Start registered containers with admission disabled. Record exact runtime-observed identity and common clock provenance. +4. Persist every identity. A failed or uncertain write keeps startup unavailable and requires recovery. +5. Construct the complete epoch manifest and validate policy/trust/witness/clock readiness. Activate the epoch and acknowledge participants, with adapters last. +6. After failure, fence every recorded container, including pending-identity entries. An omitted/missing record cannot be replaced by an empty inventory. + +```mermaid +sequenceDiagram + participant S as Supervisor + participant D as Durable artifacts + participant R as Container runtime + participant P as Bootstrap participant + S->>R: Create stopped registered containers + R-->>S: Exact container IDs + S->>D: Persist fixed launch intents + D-->>S: Durable result + S->>R: Start non-serving bootstrap + R->>P: Create process + S->>R: Inspect exact process and clock identity + R-->>S: Verified identity observations + S->>D: Persist identity-complete inventory + D-->>S: Durable result + S->>S: Validate all epoch readiness gates + S->>P: Activate matching epoch and policy +``` + +Runtime ownership is global across epoch directories within the deployment's one trusted configured root. Different configured roots require deployment-level reconciliation before serving; changing that root while an old epoch may act cannot bypass fencing. A fresh ownership claim alone supplies no launch or durability proof. Bootstrap models supply no actual OS observation, authenticated control-channel or persistence guarantee. Those guarantees require the corresponding controller, durable store and participant integration tests. + + +## 21. RG-006 implementation boundary — revision 9 + +These components support PRD-007, PRD-024 and PRD-025 / FR-001, FR-007, FR-008 and FR-022. Component fixtures exercise ownership, intent and identity persistence; the end-to-end restart, state-integrity and fencing evidence in AT-08, AT-09 and AT-28 remains pending. + +The integration feature contains five bounded supervisor-side components: + +- **RuntimeOwner** (`src/supervisor/runtime_owner.h`, `src/supervisor/runtime_owner.cpp`) acquires exclusive ownership of one configured runtime root, validates its owner lock and immutable anchor, and distinguishes a newly created root from recovery-only opening. `ClaimInitialEpoch` can issue one move-only `InitialEpochClaim` from a fresh root. The claim retains owner state and provides the root descriptor only while ownership validates. It is not a successor-epoch or process-fencing token. +- **BootstrapInventory** (`src/supervisor/bootstrap_inventory.h`, `src/supervisor/bootstrap_inventory.cpp`) is an immutable planned roster plus observed identity records. It binds domain, epoch, authority incarnation, policy digest, and expected clock identity. Revisions start at one, advance without wrapping on new observations/recovery latches, and remain unchanged for an exact duplicate observation unless recovery is already latched. A new observation at revision exhaustion cannot wrap and enters recovery-required state. Unknown or mismatched observations latch recovery-required state. +- **BootstrapStore** (`src/supervisor/bootstrap_store.h`, `src/supervisor/bootstrap_store.cpp`) consumes the initial claim to create one epoch intent directory and its canonical inventory file. Updates use expected revision and digest as a compare-and-swap precondition. The returned visibility is `NotVisible`, `Durable`, or `VisibleDurabilityUnknown`; only a durable write advances the acknowledged in-memory snapshot. `store_error` reports persistence/ownership outcomes independently from `transition_status`: for example, a detected identity mismatch can be durably recorded as recovery-required while the transition reports the mismatch. An uncertain publication makes the store unavailable for further writes. `ReadyCandidate` checks ownership, canonical persisted bytes, domain/epoch binding, and complete observed inventory before returning candidate data. +- **BootstrapRecoveryReader** (`src/supervisor/bootstrap_recovery_reader.h`, `src/supervisor/bootstrap_recovery_reader.cpp`) is the component reader for recovery diagnostics. `Read(const RuntimeOwner&, IRecoveryReaderIo*)` accepts only a valid `RecoveryRequired` owner, validates ownership, duplicates the root descriptor, scans bounded root/epoch entries, and validates ownership again. Fatal results are limited to wrong owner mode, invalid owner, unavailable root descriptor, and allocation failure. Other scan uncertainty is returned in an immutable `BootstrapRecoverySnapshot` with typed issues and truncation flags where allocation permits. The reader retains safely decoded inventories and their planned container IDs even when a record has no PID/start identity; it preserves historical clock/boot provenance and does not compare it with the current boot. It does not open a BootstrapStore, return an `EpochCandidate`, adopt an epoch, issue stop commands, prove exit, or authorize reset/activation. +- **InitialEpochClaim** is a one-use ownership capability, not proof that a participant has started or stopped. `RuntimeOwner::OpenExisting` is recovery-only; the current code has no API to reopen an existing bootstrap intent for serving or to authorize a successor epoch. Any diagnostic read of an existing intent is not authority to serve or reset. + +The intended startup handoff is: after the controller confirms the fixed containers exist in a stopped state, persist their exact IDs and bindings before process start; start each container in a non-serving mode; inspect its exact host PID, PID-start identity, container identity and shared clock provenance; persist each observation; then obtain candidate data and continue through the remaining readiness gates. These ownership/bootstrap components implement durable roster/observation storage, candidate-data validation, and the diagnostic recovery reader only. They do not implement a Docker process controller, participant activation acknowledgment, authority/witness readiness, `ACTIVE` transition, stopping, positive exit confirmation, supervisor-crash recovery orchestration, or a fenced-successor authorization. + +A create operation that succeeds in the container runtime while persisting its returned container ID fails or becomes uncertain cannot be treated as an empty roster. Recovery remains blocked until the container is reconciled or the HLD/LLD-required controlled complete-VM shutdown supplies positive fencing evidence. No token or API currently proves that all prior participants are stopped and authorizes a successor epoch. + +### 21.1 BootstrapRecoveryReader v1 component contract + +The [bootstrap-only base contract](contracts/bootstrap-recovery-v1.md) is extended by [Epoch artifact layout v1](contracts/epoch-artifact-layout-v1.md) for optional manifest-store validation. Sources are PRD 8, SRD 5 and HLD 5 A-03. The bootstrap and optional-manifest reader components are implemented; full recovery orchestration/controller remains pending. Verification evidence is tracked separately, and this document makes no end-to-end recovery or fencing claim. + +**API and result semantics.** `BootstrapRecoveryReader::Read(const RuntimeOwner&, IRecoveryReaderIo*) noexcept` returns either `shared_ptr` or `RecoveryReaderFatal`. The owner must be in `RecoveryRequired` mode and pass initial validation; otherwise the call returns a fatal outcome. The reader duplicates its root descriptor and revalidates ownership after scanning; later failure returns incomplete diagnostic evidence. The snapshot carries the domain, `scan_complete`, per-epoch diagnostics, global issues, and `issues_truncated`. An epoch diagnostic may include its canonical directory name and identity, intent identity, a safely decoded immutable `BootstrapInventory`, an optional safely decoded immutable `ManifestV1`, canonical digests, epoch-local issues, and an `issues_truncated` flag. File identities record device, inode, owner UID, link count, mode, size, mtime, and ctime. Arbitrary raw filesystem names and file contents are excluded. + +`scan_complete=true` means only that the bounded structural scan was stable and all examined artifacts were valid. It does not mean all planned participants have recorded process identities, that a previous write was durably synced, that an epoch was active, that any process exited, that rollback did not occur, or that reset/serve is safe. A structurally valid inventory may contain pending identities. Empty roots, missing or invalid intents, unknown entries, collisions, detected mutation, and every resource-limit/truncation condition make the scan incomplete. The result is diagnostic data only: it is not a `BootstrapStore`, `EpochCandidate`, `InitialEpochClaim`, stop/exit acknowledgment, fencing token, or successor authorization. + +**Scan order and validation.** The reader validates recovery-mode ownership and duplicates the root descriptor; it enumerates all root entries rather than choosing a newest epoch. It recognizes only canonical nonzero `epoch-<32 lowercase hex>` directories with owner-only `0700` permissions. An epoch directory contains `intent.json` and may contain `manifest-store`; absence of that directory is valid for a bootstrap-only structural scan and proves no activation state. The epoch child-entry cap includes both names. `intent.json` must be an owner-only `0600` regular single-link file within the existing 4 MiB inventory codec cap. If `manifest-store` exists, it must be owner-only `0700` and have no more than 16 entries; its only accepted entries are an empty, owner-owned regular single-link `0600` `owner.lock` and an owner-owned regular single-link `0600` `manifest.json`. The manifest has its own 4 MiB codec cap. It opens entries with no-follow and nonblocking flags. It records symlinks, special files, hard links, malformed names, unknown or temporary entries (`intent.tmp`, `manifest.tmp`), missing required files, invalid checksums/schema, domain or directory-epoch mismatch, and identity collisions across epochs as issues. Safely decoded sibling artifacts remain in the result when another artifact is invalid. A readable manifest remains in its epoch diagnostic even if the intent is missing, corrupt, or inconsistent, when remaining caps permit. It revalidates file/directory identities and entry listings around reads, repeats root enumeration, and validates ownership again. These checks detect observed changes; they are not an atomic filesystem snapshot or protection against a hostile same-UID writer. The scan never writes, repairs, removes, fsyncs, starts, stops, or adopts filesystem/process state. + +Every safely decoded inventory contributes each planned container ID as a diagnostic target, whether or not `identity_recorded` is true. PID and PID-start identity are included only when recorded. This preserves exact container targets for pending identities. If an intent is unreadable, malformed, missing, or absent, unknown targets may exist; the reader reports uncertainty and retains known targets from other valid artifacts rather than presenting a complete empty set. Historical boot/clock identity remains diagnostic evidence; decoding does not require it to match the current boot. + +If both artifacts decode, candidate comparison occurs only when `BootstrapInventory::ReadyCandidate` succeeds. Compare exact epoch ID, authority incarnation, policy digest, shared clock identity, and every participant identity, using canonical ordering by role, participant ID, and slot. Incomplete comparison data or any mismatch makes the scan incomplete; do not select the newer artifact or repair one from the other. Same-epoch duplicate representations that match are expected and are not cross-epoch collisions. `Prepared`, `Active`, `Draining`, and `Closed` are recorded metadata only; no phase, including `Closed`, proves process cessation. Manifest and intent checksums detect corruption only; they do not authenticate a writer, prove rollback freshness, or prove that a prior directory fsync completed. + +**Finite reader limits.** The component uses these fixed caps. Exceeding a cap retains collected evidence where possible, reports a limit/truncation condition, and forces `scan_complete=false`. + +| Resource | Limit | Overflow behavior | +| --- | ---: | --- | +| Epoch directories | 1,024 | Stop enumerating more epoch directories and report a limit issue | +| Root entries (excluding `.` and `..`) | 4,096 | Truncate the root listing and report a limit issue | +| Entries per epoch directory | 16 | Truncate that child listing and report an epoch issue | +| Entries in `manifest-store` | 16 | Truncate nested listing and report an epoch issue | +| Aggregate attempted intent and manifest bytes | 64 MiB | Shared budget before read/decode; failed attempts still consume budget | +| Retained bootstrap and manifest participant records | 16,384 | Shared record budget; count both matching representations, preserve prior records, report a limit issue | +| Global issues | 256 | Stop retaining issues and set `issues_truncated` | +| Issues per epoch | 16 | Stop retaining local issues and set epoch `issues_truncated` | + +Each intent and manifest also obey its 4 MiB codec cap. These reader bounds do not amend product quota limits. Issue truncation, any resource cap, and allocation failure cannot become a clean scan. Matching bootstrap/manifest records in the same epoch do not collide; duplicate container or process identities across epoch directories remain conflicts. + +**Recovery handoff and remaining gates.** `EpochSupervisor` may use decoded container IDs as inputs to a future stop/reconcile operation, but it must independently inspect and positively confirm exit for each exact process/container. The reader cannot report “all stopped.” Unknown targets, missing/untrusted artifacts, or incomplete evidence block successor activation until reconciliation or the contracts' controlled complete-VM shutdown evidence. Full recovery orchestration, the Docker process controller, stop/exit evidence, participant activation, and successor-epoch authorization remain pending. Independent tests and pinned Linux/sanitizer CI evidence for the reader are required before component acceptance; no end-to-end recovery or fencing result is claimed. + +### 21.2 Epoch artifact layout v1 + +The selected names and structure are specified in [Epoch artifact layout v1](contracts/epoch-artifact-layout-v1.md). The pure `epoch_layout_v1` utility is shared by BootstrapStore, BootstrapRecoveryReader, and ManifestStore: one canonical parser/formatter for nonzero epoch IDs and one source for all artifact name constants. Format/parse helpers produce or validate strings only. They do not validate filesystem ownership, authorize file access, prove an epoch is active, or issue any capability. + +The per-epoch layout is `epoch-/intent.json`, optionally followed by `epoch-/manifest-store/{owner.lock,manifest.json}`. BootstrapStore persists the launch intent before process start. ManifestStore may create a new private manifest-store directory only after the complete observed candidate exists; it cannot initialize an existing directory or adopt an ACTIVE epoch. These are separate durable transitions, not one transaction. `manifest.tmp` is uncertain evidence. Until witness/journal and recovery-operation path validators are defined and integrated, their names/directories are not recognized or accepted; an unknown entry remains a scan issue. + +The generic ManifestStore factory receives a caller-supplied directory and does not itself bind that path to the validated runtime root and epoch directory. Supervisor integration must construct exactly `/epoch-/manifest-store` while holding and validating global RuntimeOwner ownership. Shared path constants are not path capabilities. This complete supervisor-to-manifest-store binding and the recovery controller remain unimplemented; layout conformance alone does not authorize serving, stopping, or successor creation. + + + +### 21.3 Docker Engine Unix HTTP transport — revision 10 + +[Transport v1](contracts/docker-engine-unix-http-v1.md) selects an internal local HTTP exchange for the future inspect/stop controller (RG-006; PRD-007/024/025, FR-007/008/022). It does not implement container identity/state interpretation, process control, EpochSupervisor activation, orphan reconciliation or successor authorization. HLD 5 architecture and PRD 8/SRD 5 product semantics remain unchanged. The transport is outside admission/quota latency measurements. + +| Element | Ownership, lifetime and synchronization | +| --- | --- | +| `IUnixHttpTransport` | Internal interface; caller owns the transport and must finish calls before destruction | +| Private `NativeUnixHttpTransport` | Owns canonical pathname and pinned socket device/inode/owner; immutable after factory construction; owns atomic active-call count | +| `detail::ParseHttpResponse` | Pure complete-response parser; owns no cross-call state; input remains caller-owned; returned body is independently owned | +| `IClock&` | Borrowed; must outlive transport and all calls; clock exceptions become `ClockFailure` rather than escaping a noexcept boundary | +| Cancellation flag | Borrowed atomic; caller retains it until return; no detached worker or callback retains it | +| Socket descriptor and wire buffer | Per-call RAII state, never shared; four calls maximum, no queue; no mutex held across I/O | + +**Exchange.** A caller supplies GET/POST, bounded origin-form target, future absolute monotonic deadline and cancellation flag. The transport generates fixed headers and an empty body. Each Linux call uses a fresh nonblocking close-on-exec AF_UNIX descriptor, revalidates pinned pathname metadata and checks peer credentials before writing. Production controller composition must fix socket owner/peer UID to 0; configurable UID fields are an internal native-test seam. There is no TCP/proxy/Docker-context lookup, CLI subprocess, redirect or automatic retry. A failed Unix connect with EAGAIN fails safely; only EINPROGRESS enters completion polling. Non-Linux factory use returns UnsupportedPlatform. + +**Bounds.** Target/request caps are 2,048/4,096 bytes. Header bytes/fields are 8,192/64; complete wire/decoded body caps are 512/256 KiB; chunk count/size-line caps are 4,096/128 bytes. At most 4 active exchanges are allowed; the fifth returns Overloaded before connecting or writing. Factory pins the configured canonical socket; missing/replaced socket or wrong owner/peer prevents dispatch. These are internal component bounds, not amendments to product tenant/queue limits. + +**Framing and outcomes.** The parser requires strict CRLF HTTP/1.0 or 1.1 and rejects informational responses, duplicate/ambiguous lengths/codings, folded headers, truncation, invalid chunks, extensions, nonempty trailers and trailing framed bytes. Exactly one Content-Length, chunked encoding, or EOF-delimited body is supported. This narrow Docker profile accepts 204/304 only with no transfer coding, absent/zero Content-Length and zero body. Every response requires EOF within the same deadline. Valid HTTP error/redirect statuses are returned as data and never followed; the future controller must interpret only its allowed statuses. Parser allocation failure maps distinctly to transport AllocationFailure. + +**Deadline and uncertainty.** Initial deadline must be future and at most 30 seconds away. Reads/writes and readiness waits use that absolute deadline, never restarted after interruption. Cancellation/clock/deadline are checked at I/O boundaries and again after parsing before allocation-free move of a successful response. Failures are known-unsent only until the first positive write; every later failure preserves request_possibly_sent=true. A possible stop dispatch requires higher-layer inspection/reconciliation; transport completion alone proves no stop, cessation or fence. No late result authorizes serving or forwarding. + +**Choice and evidence.** Direct local HTTP avoids CLI executable/environment selection and subprocess-tree cleanup; the cost is a deliberately limited, independently tested HTTP parser. Socket UID checks do not authenticate a particular daemon binary; trusted local rootful-daemon placement and actual API compatibility remain deployment qualification obligations. The transport never chooses an API version. Fake peers and synthetic version strings are not real Docker qualification. Independent parser/bounds/allocation and Linux socket/UID/replacement/cancel/deadline/concurrency/throwing-clock fixtures are separate from production functions. [RG-006-G evidence](evidence/RG-006-G.md) records actual run status and exclusions; no forced short-write or exact post-EOF scheduling-race result is implied by source review. diff --git a/docs/SCRUM-WORK-LOG.md b/docs/SCRUM-WORK-LOG.md new file mode 100644 index 0000000..92adf7c --- /dev/null +++ b/docs/SCRUM-WORK-LOG.md @@ -0,0 +1,568 @@ +# Scrum Work Log + +**Live log:** This file follows the implementation on `feature/distributed-rateguard`. Story branches append entries for integration. Earlier entries record the branch state at their observation time. + +**Owner:** Master agent (`/root`) · **Started:** 2026-11-13 02:33 UTC +**Repository:** DistributedRateGuard · **Source contracts:** PRD 8 / SRD 5 / HLD 4 / LLD 5. +**Review branches:** [RG-001 / #5](https://github.com/kshiteesh28/DistributedRateGuard/pull/5), [RG-002 / #6](https://github.com/kshiteesh28/DistributedRateGuard/pull/6), [RG-003-A / #8](https://github.com/kshiteesh28/DistributedRateGuard/pull/8), [RG-004-A / #9](https://github.com/kshiteesh28/DistributedRateGuard/pull/9), [RG-004-B1 / #10](https://github.com/kshiteesh28/DistributedRateGuard/pull/10), [RG-004-B2 / #11](https://github.com/kshiteesh28/DistributedRateGuard/pull/11), [RG-004-B3 / #12](https://github.com/kshiteesh28/DistributedRateGuard/pull/12). No implementation has been merged to main. + +## Reading and logging rules + +The Master records agent assignments, handoffs, review findings, rework, actual checks, and unresolved gates here. Entries identify who authored, reviewed, integrated, and verified work; these are different responsibilities. Git history preserves earlier versions. Later corrections reference the entry they correct. Subagent reports are attributed reports until linked execution evidence confirms them. + +Historical entries below are reconstructed from retained handoffs and GitHub evidence. Exact active minutes and earlier start/finish times were not recorded and are **unknown**; sprint estimates are not actual effort. LOG-007–016 header times are approximate report markers; GitHub commit/action timestamps are authoritative. Later UTC observation stamps are sampled from the clock tool; none represents inferred active work duration. No private reasoning, credentials, or hidden execution transcript is included. + +## Board snapshot + +| Story | Owner/contributors | State | Remaining gate | +| --- | --- | --- | --- | +| RG-001 contracts/build | Junior Dev: wire/helpers; Senior Dev: build; Tester: independent checks; Master: integration; earlier Scrum Master: acceptance review | Component verified; PR #5 ready, unmerged | Product Owner review; Sprint 0 Docker target/image-digest gate remains open (Master/Senior Dev); runtime integration has separate story gates | +| RG-002 policy/arithmetic | Junior Dev: arithmetic; Senior Dev: policy/codec; Tester: independent oracles; Master: representation decisions/integration | Component verified; PR #6 ready, unmerged | Product Owner review; runtime integration in later stories | +| RG-003 clock provenance | Junior Dev: clock implementation; Senior Dev: design/code review; Tester: independent checks; Master: decisions/integration | RG-003-A component verified; PR #8 ready, unmerged | RG-003-B/C/D topology, service and checker integrations remain pending | +| RG-004 authentication | Senior Dev: TLS verifier/fixtures; Junior Dev: trusted UTC/Docker observer; Tester: independent checks; Master: integration | RG-004-A/B1/B2/B3 inputs verified; PR #9/#10/#11/#12 ready, unmerged; full story in progress | Real commit/forward, manifest/fencing and service/export integration remain open; native SDK resumption fixture qualified, production caching disabled | +| RG-005 | Senior Dev / Junior Dev / Tester | In progress; components verified, runtime pending | [Evidence](evidence/RG-005.md) | +| RG-006 | Senior Dev / Tester | In progress; local gate verified, durable runtime pending | [Evidence](evidence/RG-006-A.md) | +| RG-007–014 | Assigned by dependency readiness | Planned | Dependencies and acceptance in [stories](STORIES.md) | + +## Work entries + +### LOG-001 — Historical: bootstrap assignments and build experiment + +- **Agents:** Master coordinated; Junior Dev authored versioned protobuf schemas, validation/error contracts; Senior Dev authored CMake/code generation and manifest tooling; Tester reviewed fixtures and retry semantics. +- **Output:** [PR #5](https://github.com/kshiteesh28/DistributedRateGuard/pull/5), [RG-001 evidence](evidence/RG-001.md). +- **Finding/rework:** Initial gRPC source build exceeded a 45-minute CI budget before product tests. Master selected the recorded Ubuntu package lane, fixed package/source CMake target differences, and retained source mode as explicitly unverified. +- **Limitation:** Local host lacks required Linux/CMake/protobuf dependencies and outbound access. Production compilation is verified by GitHub CI, not claimed from temporary local stubs. + +### LOG-002 — Historical: RG-001 verification and scoped review + +- **Agents:** Master integrated and read CI evidence; independent Tester and earlier Scrum Master reviewed scoped acceptance. +- **Evidence:** [run 43327798021](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43327798021), source head `4c924495a1303054a2c3b26edfae757430ea4d72`; final promotion/docs [run 43328571076](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43328571076). +- **Observed:** Five CTest groups passed twice; 12 Python verifier tests passed; 12 generated files matched across clean build directories. Synthetic retry control observed four calls with retry enabled and one with enforcement arguments. +- **Scope:** Wire/helper/build component accepted; no quota service, runtime mTLS, shared-clock proof, Docker image, benchmark, or release acceptance. +- **Handoff:** PR #5 ready for Product Owner review; no merge performed. + +### LOG-003 — Historical: RG-002 arithmetic and independent defect detection + +- **Junior Dev:** Authored `src/authority/bucket_math.h` and C++ unit tests: fixed-point refill, debit, saturation, LIMITED time advancement, checked intermediates, retry ceiling. +- **Tester:** Authored independent Python arbitrary-precision oracle, test-only C++ driver, 3,000 seeded stateful decisions, and compiled reject-all/double-debit mutants. +- **Master:** Integrated compiler portability fixes, CMake targets, and fail-on-missing-source oracle paths. +- **Observed:** Local C++20 arithmetic/oracle checks passed; Linux [run 43330293300](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43330293300) passed seven CTest groups in two clean directories. +- **Scope:** Pure arithmetic only; no live clock, locks, authority state, or RPC admission. + +### LOG-004 — Historical: policy representation and implementation handoff + +- **Master:** Recorded [policy-v1 revision 1](contracts/policy-v1.md) and LLD §19 before codec implementation: canonical bytes, immutable tables, principal/slot identity binding, finite startup caps, and JSON decimal-string accounting. +- **Senior Dev:** Authored immutable PolicySnapshot, bounded duplicate-aware JSON loader, canonical encoder, real OpenSSL digest, C++ tests, and CLI driver. +- **Tester:** Independently derived Python serialization/hash oracle; golden aggregate is 580 bytes, SHA-256 `0fa75c3373b71fc7c21ce0417258ea6545986d884c69c16f2ee8d6d9fefe00ff`. +- **Review fixes:** Master separated offline structural loading from live certificate validation (RG-004), enforced exact binary-search references and portable fixture paths. Senior Dev added typed encoding allocation errors. +- **Limitation:** Temporary fake-driver/shim checks were harness preparation only. They are not production parser, crypto, or acceptance evidence. + +### LOG-005 — Historical: first combined RG-002 Linux result + +- **Master:** Published policy/tests, added CMake linkage to exact nlohmann-json 3.11.3 and recorded OpenSSL, extended primary package lock and manifest verification. +- **Evidence:** [run 43332249683](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43332249683), head `dd3f775e4435aae2f32a44190017ccaada747d49`; tested merge ref `68a7e27a8f8f0975bbd2dd207ddc74b589a7fd57`. +- **Observed:** Nine CTest groups passed in each clean directory; 16 Python verifier/oracle tests passed; 12 generated files matched; C++20 compiler evidence covered 16 project translation units. Exact eight-package lock comparison passed. +- **Remaining:** New boundary/error-classification and crypto-provider-failure checks were not included in this run. RG-002 remains draft. + +### LOG-006 — Historical: process interruption and recovery + +- **Master:** Ended an earlier response while CI was unfinished. User challenged the stop; Master acknowledged it and resumed. Future CI work is tracked through its result or a concrete external blocker. +- **Senior Dev:** Handed off an OpenSSL 3 failure-path patch, then encountered an account usage-limit error during clock review. The patch was not counted as verified. +- **User control:** User requested status, then explicitly authorized continuation and per-agent work logging. +- **Correction:** A handoff or agent completion message is not equivalent to accepted work. Main remains unchanged. + +### LOG-007 — 2026-11-13 02:33 UTC: current assignments + +- **Master:** Rechecked GitHub state; second combined [run 43332456218](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43332456218) succeeded. Created this log; will publish/verify remaining RG-002 changes and maintain the board. +- **Tester:** Assigned final finite-cap/numeric-boundary checks, typed error expectations, independent acceptance notes, and factual work-log handoff. +- **Senior Dev:** Asked to resume if available, supply factual handoff, and review clock design. Availability and independent review remain unconfirmed. +- **Junior Dev:** Completed RG-003 read-only preparation: flagged global versus per-tenant backward-time detection and exact namespace probing as decisions. No clock code was written. +- **Scrum audit agent:** Assigned an independent board/dependency/log audit. Audit findings are pending. +- **Next gates:** Final RG-002 CI and reviewer acceptance; then RG-003 code on its own review branch. No release metrics or full-system safety are claimed. + +### LOG-008 — 2026-11-13 02:40 UTC: independent Scrum audit + +- **Scrum audit agent:** Independently checked current PR heads and successful CI, then identified stale STORIES/sprint/context/PR status. Confirmed that hosted-package evidence does not complete Sprint 0's Docker target/image gate. +- **Master action:** Updating the board and recording stacked review rules. Docker topology/image-digest evidence remains an open deployment gate owned by Master/Senior Dev; no gate is waived. +- **Process clarification:** PR #6 targets the verified RG-001 feature branch for independent review. Main merge stays under Product Owner control; dependent PRs require rebase/retarget and fresh checks after their base changes. + +### LOG-009 — 2026-11-13 02:40 UTC: RG-002 final extensions and one test defect + +- **Senior Dev:** Resumed, supplied factual work handoff, and authored explicit OpenSSL 3 provider-based hashing/failure test. The injected provider failure is isolated in a child process; parent crypto settings are unchanged. +- **Tester:** Added coherent positive/negative collection caps, integer/identifier bounds, exact/over 64 MiB direct loader tests, and typed diagnostic expectations. Local sanity checked independent encodings only; root CI verifies production behavior. +- **Master:** Published extensions through `6d3e55f42b144e4999aad571cfca039e8f74a086`; required OpenSSL 3 in CMake. +- **Evidence:** [run 43353532557](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43353532557) compiled successfully. Crypto-failure and direct byte-cap C++ checks passed; integration suite reported one failing test. +- **Finding / responsible owner:** Tester's unknown-field mutation supplied malformed JSON because it removed the fixture's trailing newline rather than its closing brace. Production correctly returned invalid_json. Tester replaced this with parsed-object mutation/serialization and audited the remaining raw mutations. +- **Master handoff:** Published fixture correction `7640975031aee2af2ee7ae855ce88b76115f1569`; fresh CI pending. The failed run remains visible; no final acceptance is claimed from it. + +### LOG-010 — 2026-11-13 02:40 UTC: RG-003 preparation and design review + +- **Junior Dev:** Located binding clock requirements and raised comparison/provenance questions before coding. +- **Senior Dev:** Reviewed global mutex sampling, tenant-to-clock lock order, sticky failures, manifest matching and runtime namespace restrictions. This was design review, not code review. +- **Master:** Selected bounded startup provenance and serialized sticky-fail sampling. Upstream Linux review found that timens_offsets reads the namespace for children; design therefore compares current/children namespace device/inode before and after offsets. Production probing is leader-only before workers. +- **Assignment:** Junior Dev implements the isolated clock component/tests in temporary working files; Senior Dev reviews it independently after handoff. No clock implementation or Docker/shared-process result has been published yet. + +### LOG-011 — 2026-11-13 02:45 UTC: RG-002 verification and independent acceptance + +- **Master:** Inspected successful [run 43353832066](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43353832066) at corrected head `7640975031aee2af2ee7ae855ce88b76115f1569` / merge ref `9be7be9861ddc0f0bd04718e6d500781de5b18ca`; archived the original manifest in [RG-002 evidence](evidence/RG-002.md). +- **Tester:** Independently fetched actual job logs and source. Confirmed 14 production policy integration methods, direct exact/over 64 MiB Load checks, real isolated-provider failure, 9 CTest groups in both clean builds, 16 Python unit checks, 12 generated-file matches and 16 actual C++20 translation units. No remaining RG-002 component blocker. +- **Master:** Updated stories/context/sprint/evidence consistently. Promoting the exact eight-package lock from frozen-pending to validated based on this observed result; metadata/lock-promotion CI must still pass before PR #6 becomes ready. +- **Scope:** Pure immutable policy, canonical identity and accounting only. Runtime trust-root validation remains RG-004; quota service, witness, Docker deployment and all release gates remain outstanding. + +### LOG-012 — 2026-11-13 02:47 UTC: Scrum re-audit and summary corrections + +- **Scrum audit agent:** Rechecked stories, context, sprint plan, evidence, work log and PR #6 at `5203f91`. Component acceptance, unmerged status, stacked review rules and open Docker deployment gate were consistent. Found stale RG-003 board text, stale PR verification text and an unlabeled historical build-version note. +- **Master:** Corrected the three summary fields; earlier entries remain historical observations. Lock-promotion [run 43354481661](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43354481661) is pending; no new component blocker was identified. + +### LOG-013 — 2026-11-13 02:52 UTC: RG-002 ready; dedicated live log branch + +- **Master:** [run 43354640416](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43354640416) passed the final RG-002 head `410b9d66e998b094fea6a5deffc69bf0412338fd`. Marked PR #6 ready for review without merging it. Previous run 43354481661 completed checks but was automatically cancelled during artifact upload by a newer documentation commit; it is not counted as a successful run. +- **Process improvement:** Continued log updates now live on `docs/scrum-work-log`, independently reviewed against the verified RG-002 feature branch. This avoids cancelling implementation CI whenever the live scrum log changes. Feature branch copies remain historical snapshots; the live URL above is authoritative. +- **Master:** Created RG-003 review branch from the same verified RG-002 head; code remains under review before publication. +- **Senior Dev:** Code review requested stronger startup source validation and explicit clock availability before readiness. +- **Master decisions:** Production opens/validates/reads the same proc descriptors (PROC_SUPER_MAGIC for boot/offsets, NSFS_MAGIC for namespace descriptors), under an explicit trusted-kernel/operator/proc-mount assumption. Clock factory must also obtain and retain a successful initial sample before exposing an object. +- **Junior Dev / Tester:** Updating implementation and independent startup tests for those decisions. Earlier local passes do not cover the new changes until rerun. + +### LOG-014 — 2026-11-13 02:52 UTC: independent test review findings + +- **Master:** Found two defects in the Tester's RG-003 harness before publication: hardcoded temporary output path, and an embedded-NUL std::string length exceeding the literal's storage. +- **Tester:** Replaced the path with mkstemp/cleanup and constructed the embedded NUL safely. Added a reproducible Python runner that compiles an actual regression-guard mutant and checks specific independent failure labels. +- **Evidence boundary:** Local corrected harness and mutant passed before the new startup-sampling change. Junior's deterministic tests passed locally. Linux OS smoke was explicitly unsupported on macOS; it is not logged as a Linux pass. + +### LOG-015 — 2026-11-13 02:58 UTC: clock publication and final review cleanup + +- **Master:** Published RG-003 isolated code, decision record, CMake targets and [PR #8](https://github.com/kshiteesh28/DistributedRateGuard/pull/8), stacked on verified RG-002. Includes independent tests, real clamp-mutant compilation, and Linux fork/exec smoke. Initial CI queued; not yet accepted. +- **Junior Dev:** Delivered mandatory startup sample, retained regression reference, exact boot/offset parsing, four namespace snapshots, same-descriptor filesystem checks, sticky fail-closed sampling and concurrency tests. Portable C++20 checks passed; Linux smoke explicitly returned unsupported 77 on macOS. +- **Tester:** Updated independent factory-failure and retained-startup-reference cases; corrected mutation runner to inject an actual clamp instead of simply removing the guard. Recompiled independent/unit/mutant checks successfully on macOS. Linux-specific fd validation is not covered by those local passes. +- **Senior Dev:** Accepted final core code for publication/CI, then noted an unused unhardened file-reader helper. +- **Master decision / rework:** Junior and Tester are factoring/tests against the actual production bounded-fd reader; remove unused path helper. CI must validate the final version. Independent test-source fixes are preserved in LOG-014. +- **Next preparation:** Senior Dev assigned read-only RG-004 requirement/API extraction. No authentication implementation is claimed from this preparation. + +### LOG-016 — 2026-11-13 03:03 UTC: sanitizer finding and final clock CI + +- **Master:** Initial [Linux run 43355498930](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43355498930) passed 13 CTest groups twice, including real proc/ns filesystem handling and fork/exec smoke. This is preliminary evidence, not final acceptance after subsequent edits. +- **Master:** Ran local address/undefined sanitizers because an earlier independent test had a literal-length defect. Sanitizer caught a separate global-buffer-overflow in Junior Dev's embedded-NUL parser fixture: explicit length 31 exceeded 28-byte literal storage. The independent harness passed sanitized checks. +- **Junior Dev:** Replaced the fixture with safe string construction plus push_back of NUL, audited related parser fixtures, and reran strict and sanitizer tests successfully. +- **Master:** Independently reran the corrected sanitized developer test successfully. Published the production-used bounded-fd reader, final unit/independent tests and a required targeted sanitizer CI step at `2d55c6e032ae75947f045ac76ffa383b2b1dd9d8`. +- **Tester:** Independently checked exact/over limits, descriptor ownership and negative/closed fd typed errors. Actual clamp mutation is rejected, including the retained startup sample check. +- **Gate:** Final Linux normal/clean/sanitizer CI is pending. Earlier green runs do not waive this new gate, and no full RG-003 integration acceptance is claimed. + +### LOG-017 — 2026-11-13 03:10:06 UTC observation: clock independent acceptance and dependency audit + +- **Master:** Inspected final [run 43355987772](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43355987772), head `2d55c6e032ae75947f045ac76ffa383b2b1dd9d8` / merge `208c8ba13c8bbe7cfc36b5fe44a2e0b1b5490ae8`: 13 CTest groups twice, 3 sanitizer tests, 16 Python checks, 12 generated-file matches and 20 actual C++20 translation units. +- **Tester:** Independently fetched logs/tested source, confirmed actual non-skipped Linux fork/exec smoke, safe NUL fixture, common reader bounds/ownership, startup reference and compiled clamp-mutant rejection. Accepted startup/provenance/sample component scope; explicitly left service/checker obligations pending. +- **Senior Dev:** Accepted final reader/fixture changes by code review; did not claim an independent Linux rerun. No new code blocker. +- **Scrum audit agent:** Detected semantic deadlock if RG-006 must wait for all RG-003 ACs while RG-007/008/013 are needed to complete those ACs. Recommended named component input contracts without waiving any requirement. +- **Master:** Recorded RG-003-A verified component input for RG-006/007/008, and pending RG-003-B topology (RG-006), RG-003-C commit/deadline mapping (RG-007/008), RG-003-D UNKNOWN classification (RG-013). Full RG-003 is not Done. Updated PR/evidence/story/context/sprint/README to match. +- **Master process finding:** One publication orchestration script had a JavaScript syntax error and failed before executing any writes; corrected and reran it. No partial repository mutation resulted. +- **Current gate:** Final documentation-head [run 43356954793](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43356954793) is in progress. Runtime/deployment and product gates remain open. Main has not been merged. + +### LOG-018 — 2026-11-13 03:10:06 UTC observation: RG-004 preparation + +- **Senior Dev:** Read main PRD 8 / SRD 5 / LLD 5 and frozen policy-v1, produced a ten-gap authentication contract extraction: dual-role replica EKUs, trusted wall time, expiry under queueing, SAN ambiguity, status classification, replica permission scope, exact server URI pinning, leaf/root shape, handshake versus RPC failures and reused-channel checks on both sides. +- **Master:** Requested concrete source-compatible defaults and verification against pinned gRPC 1.51.1/OpenSSL 3 APIs before security code is assigned. This is active design preparation, not an implemented authentication feature. +- **Limitation:** No PKI provisioning, mTLS server/channel, certificate fixtures, auth tests or deployment trust-time evidence is claimed from that preparation. + +### LOG-019 — 2026-11-13 03:12:19 UTC observation: review-ready clock handoff + +- **Master:** Final documentation-head [run 43356954793](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43356954793) passed at `ccbeddf6a42b0e9247b658284988ec30b2038a9f`, including normal, clean, sanitizer and manifest steps. Marked [PR #8](https://github.com/kshiteesh28/DistributedRateGuard/pull/8) ready for review. +- **Master verification:** Read back PR #5/#6/#7/#8: all open and unmerged. Main remains `71393cf11a0f8508cfb7e85b85538ccc22067f75`. PR #6 targets RG-001; log PR #7 and clock PR #8 target RG-002. +- **Checks on handoff:** Parsed the live context JSON (14 unique parent story IDs), confirmed named RG-003-A input contracts and pending B/C/D owners, and checked changed Markdown fence balance. +- **Current board:** API/build and policy/arithmetic components are review-ready; clock component is review-ready with full-story integration pending. All applicable deployment, enforcement and release gates remain open. +- **Ongoing preparation:** Senior Dev is checking pinned gRPC API compatibility and security defaults for RG-004. No security implementation is represented as complete. + +### LOG-020 — 2026-11-13 03:18:18 UTC observation: Release A ownership correction + +- **Master:** Found that the earlier RG-003-D assignment solely to RG-013 (C) could postpone Release A's missing-provenance guard. Requested source recheck. +- **Scrum audit agent:** Re-read PRD 8 and SRD 5 §7/D4; confirmed the guard already applies in A and acknowledged the earlier C-only assignment was too broad. This supersedes that portion of LOG-017 and prior dependency tables. +- **Corrected contract:** RG-003-D is delivered in RG-011A, with RG-005 completeness, RG-006 participant provenance and RG-007/008 actual commit inputs. Senior Dev implements; Tester independently verifies valid evidence, known violations and missing/incomparable/incomplete evidence. UNKNOWN blocks strict safety PASS before RG-008 acceptance/Release A completion. RG-013 adds credit/formal checks in C. +- **Master:** Updated story/context/sprint/evidence/LLD addendum and PR body. No clock code or product acceptance criterion changed. Fresh documentation-head CI required. +- **Master publication finding:** A metadata store of undefined stopped the first correction batch after one story-document write. Re-read current blobs, completed the remaining edits, and will check the final document bundle. No implementation or main files were changed by the failed batch. + +### LOG-021 — 2026-11-13 03:27:16 UTC observation: corrected bundle green and security defaults recorded + +- **Master:** Corrected clock documentation head `f656648c884ce9bbe6fcb917566898a2f01b4c0e` passed [run 43358083253](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43358083253). All normal/clean/sanitizer/manifest steps completed successfully. PR #8 remains ready and unmerged; no code change accompanied the Release A owner correction. +- **Senior Dev:** Verified pinned gRPC 1.51.1 custom verifier exposes URI SANs and leaf PEM before peer-check completion. Reviewed the Master proposal for immutable per-leaf hashes and wall-time synchronization gates; reported no product/source conflict. Source-only research, not a compile/TLS result. +- **Master decisions:** Published [security defaults revision 1](decisions/RG-004-security-v1.md): immutable manifest leaf pins alongside unchanged policy CA hash; role-specific EKUs; exact URI; both-boundary permissions; per-call root/leaf expiry; trusted CLOCK_REALTIME with adjtimex status and regression/error fail-closed; no live rotation. Preserve the trusted VM/time-authority assumption and no proof of inaccurate-but-monotonic UTC. +- **Review input retained:** [Senior preparation and source links](reviews/RG-004-senior-preparation.md). Earlier questions are retained as historical input and linked to their selected defaults. +- **Required next evidence:** Compile/handshake verifier APIs on frozen packages; prove reused/reconnected/resumed sessions either preserve exact peer pin verification or fail closed; validate real Docker adjtimex/synchronization preflight without claiming fake-time tests prove deployment. No authentication code, PKI provisioning or TLS acceptance is claimed. +- **Handoff state:** PR #5/#6/#8 are review-ready component work; PR #7 contains this live scrum log and planning handoff. Main remains unchanged. The full service and releases remain incomplete. + +### LOG-022 — 2026-11-16 22:48:48 UTC observation: implementation resumed + +- **Master:** Re-read current main PRD 8 / SRD 5 / LLD 5, live security decisions/context/log, and PR #5/#6/#7/#8. All remain open/unmerged; main is still `71393cf11a0f8508cfb7e85b85538ccc22067f75`. No root AGENTS.md found in the current working directory or on main. +- **Master:** Created `feature/RG-004-security-probes` from verified clock head `f656648c884ce9bbe6fcb917566898a2f01b4c0e`; copied reviewed security defaults before source work. No main write. +- **Scrum Master:** Assigned independent readiness/AC/role planning for the security slice, with agent-minute estimates and component-versus-integration gates. +- **Senior Dev:** Assigned real gRPC 1.51.1/OpenSSL 3 custom URI/DER leaf-pin verifier and ephemeral mTLS RPC compatibility probes. No quota handler or TLS success claimed yet. +- **Tester:** Assigned independent negative/reuse/expiry acceptance matrix and tests. Junior will own trusted wall time after the Scrum readiness review frees the fourth execution slot. +- **Environment:** Local host still has Clang but no CMake/Ninja/protoc/Docker/gh on PATH. Actual gRPC/OpenSSL compilation and Linux evidence must come from GitHub CI, not local stubs. Temporary local files are development staging; GitHub remains the shared review source. + +### LOG-023 — 2026-11-16 22:53:11 UTC observation: resumed slice readiness and role corrections + +- **Scrum Master:** Independently confirmed SEC-01–11 are specific enough for implementation; compatibility/integration evidence is still required. Suggested separate probe, registry, TLS wrapper, authorization, wall-time and deployment slices. Component acceptance cannot stand in for full RG-004 integration. +- **Estimate note:** Scrum proposed 4,980 active agent-minutes for its expanded full-story breakdown, compared with the older RG-004 baseline of 720. Master has not adopted this as an additive baseline: scope overlap and calibration need reconciliation after the first probe. These are estimates, not elapsed-time promises or measured effort. +- **Junior Dev:** Assigned trusted CLOCK_REALTIME/read-only adjtimex component with injected platform seam, sticky fail-closed health and mandatory initial trusted sample. Separate from CLOCK_MONOTONIC quota accounting. +- **Tester process finding:** Returned a redundant RG-003 acceptance report already recorded previously, including an obsolete C-only UNKNOWN ownership statement. Master redirected QA to RG-004 and the corrected live Release A owner contract. No board or code was changed based on that stale report. +- **Current artifacts:** Senior is authoring verifier/ephemeral PKI probe inputs; Tester prepared the independent security acceptance matrix. Production TLS compilation and actual trusted-time evidence remain pending. + +### LOG-024 — 2026-11-16 23:06:11 UTC observation: first security bundle published; workflow defect corrected + +- **Senior Dev:** Delivered a real gRPC custom verifier and in-memory CA/leaf RPC fixtures. Applied review fixes for accepted registry limits (10,000 records / 256-byte URI), trailing PEM data, valid 32-hex incarnation fixture URIs, explicit includes and initialized X509 extension context. +- **Junior Dev:** Delivered trusted wall-clock library, deterministic tests and bounded native JSON probe. Strict and local ASan/UBSan checks passed; macOS probe explicitly returned unsupported/untrusted, not a Linux pass. +- **Tester:** Delivered independent wall-clock checks and 13-scenario mTLS output/count/privacy checker. Prepared a test-only accept-all verifier mutant generator/checker; actual mutant TLS execution remains pending. +- **Master:** Independently reran both wall-clock suites under ASan/UBSan successfully. Published [draft PR #9](https://github.com/kshiteesh28/DistributedRateGuard/pull/9) against verified RG-003. No new dependency versions or quota-service implementation. +- **Master defect:** Initial JavaScript string replacement interpreted the shell regex's dollar/quote sequence as replacement syntax, corrupting the workflow; no Actions run started. Reconstructed from the verified base with callback replacement. Validated 14 unique YAML steps, duplicate keys and all run-block shell syntax locally, then published corrected workflow at `b7311c6931bd05f88909ff69a22db18aa9339971`. A local patch attempt also failed before writing and was retried with an update operation. +- **Gate:** First actual Linux compile/handshake and native synchronization observation are pending. No TLS/UTC deployment acceptance is inferred from source or local fake clocks. + +### LOG-025 — 2026-11-16 23:12:06 UTC observation: Linux compile finding and commitment contract correction + +- **CI evidence:** [run 43976130802](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43976130802) reached the real pinned Linux build but failed in the ephemeral PKI fixture: BIO_free returns int while its generic deleter alias required void. No TLS tests ran. +- **Senior Dev:** Corrected the fixture's BIO ownership type and checked the other OpenSSL deleters. No local SDK compile was available; Master published the fix for a real rerun. +- **Senior review / Master-owned correction:** Master originally assigned a clock failure type with NotCommitted embedded. Review identified that SEC-07 also uses trusted time after receiving ALLOW. A primitive clock failure cannot determine quota commitment. Master accepted a reason-only failure plus mandatory explicit phase-to-ServiceError conversion. +- **Junior Dev:** Implemented explicit ToServiceError(NotCommitted/Possible/Committed), with no default phase; strict and local sanitizer checks passed. +- **Tester:** Independently checked all mappings, including preservation of Committed for a post-ALLOW clock failure. Updated the scope: the clock's sticky failure is instance-local, not proof of global epoch fencing. +- **Master:** Published the corrected clock/fixture and isolated test-only verifier-bypass target at `bfea5499651ccf674afcfb62f258a803e114f1a5`. The real security library remains untouched by the generated bypass. Actual TLS and mutant runtime results are pending. +- **Integration gate:** Service code must mark local readiness false and notify RG-006 for epoch fencing on trust loss. A local clock object cannot positively stop every participant; no instantaneous remote-stop claim is made. + +### LOG-026 — 2026-11-16 23:35:20 UTC observation: real compatibility evidence accepted + +- **Failure retained:** [run 43976883458](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43976883458) compiled successfully but rejected every TLS connection, including the positive and accept-all-mutant controls. This identified an ordinary certificate-chain fixture problem; negative rejection alone was not accepted. +- **Senior Dev:** Gave root/leaf distinct subjects, added SKI/AKI, and added independent OpenSSL client/server-purpose chain preflight. No CA verification was disabled. +- **Tester:** Updated privacy-first diagnostics and exact numeric preflight reporting; the checker never echoes raw failing child output. Fake-output tests only validated that harness behavior, not TLS. +- **Observed result:** [run 43978267486](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43978267486), head `82a09370dac6840f8fe1ad48bd060d6e79862ea6`, merge `6fa243bbadce4e2637c9d04c93dd5e24af5f42d7`, passed 17 CTest groups in both clean builds, 3 clock + 3 security sanitizer checks, 16 Python checks (13 verifier / 3 policy oracle), and 12 matching generated files. C++20 evidence covered 30 project compilation commands. Native hosted-Linux UTC reported state 0 / flags 0 / trusted=true; this is not Docker evidence. +- **Independent acceptance:** Tester fetched logs and tested source; Senior Dev reviewed current code. Both accepted only the RG-004-A compatibility input. Full RG-004 authorization, cache-expiry, reconnect/resumption, epoch registry/fencing and export redaction remain pending. +- **Master:** Retained [component evidence](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-security-probes/docs/evidence/RG-004-A.md) and immutable manifest/native observation snapshots on the review branch. +- **Scrum Master:** Confirmed this slice does not make RG-004 Done. Found the 4,980-minute expanded estimate double-charges RG-005/006/008/009 integration; neither it nor the old 720-minute estimate is measured actual effort. Master will not treat the expansion as a replacement baseline. +- **Junior Dev:** Delivered a bounded Docker observation harness with explicit NOT_RUN / NOT_READY / OBSERVATIONS_MATCHED, immutable observed image digest, constrained container permissions and no automatic permission broadening. Local checks passed; Docker absent locally, so actual evidence is pending CI. + +### LOG-027 — 2026-11-16 23:40 UTC observation: final compatibility PR ready; constrained Docker evidence retained + +- **Master:** [run 43980308204](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43980308204) succeeded at head `f5b3e975225c869e4a9638af57ab9f7c8a06e546`, tested merge `a24c820d98aea8916a23c49d6129a4b88d14504b`. It passed both 17-test builds, clock/security sanitizer lanes (3 each), 16 Python checks (13 manifest verifier and 3 policy oracle), 12 generated-file matches and the exact package lock. [Final manifest](evidence/RG-004-A/manifest-43980308204.json). +- **Junior Dev / actual CI:** Docker 28.0.4 ran the immutable observed Ubuntu digest with all capabilities dropped, read-only mounts/root, no network and no-new-privileges. Host/container trusted UTC returned state 0 / flags 0; boot/time identities matched and monotonic samples were ordered. Result: OBSERVATIONS_MATCHED. [Complete bounded observation](evidence/RG-004-A/docker-time-43980308204.json). +- **Evidence boundary:** A matched capability probe is not the service deployment topology, process fencing, supervisor integration or an actual quota guarantee. Sprint 0's target/service deployment gate stays open; no permission was broadened to obtain this observation. +- **Tester:** Independently fetched the latest logs and confirmed no blocker to the narrow compatibility PR being ready. Full RG-004 AC01–03 remain open. QA's shorthand “16 manifest tests” is corrected here from the actual test names: 13 verifier + 3 policy-oracle methods. +- **Master:** Marked [PR #9](https://github.com/kshiteesh28/DistributedRateGuard/pull/9) ready, updated live context/stories/sprint state and archived final observations on this independent log branch. No implementation merge, PRD/SRD change, benchmark or release acceptance. +- **Senior Dev:** Assigned a read-only contract proposal for RG-004-B immutable certificate registry validation, followed by PeerAuthenticator/AuthorizationResolver. Manifest ownership/fencing stays RG-006; input validation must not silently expand canonical policy-v1 or imply runtime authorization exists. + +### LOG-028 — 2026-11-16 23:45 UTC observation: registry slice starts; dependency cycle corrected + +- **Scrum Master:** Independently confirmed current RG-004-A evidence/board consistency. Found RG-006's full-RG-004 prerequisite would cycle with RG-004-AC02's fenced-rotation evidence. Master changed the scheduling edges to named RG-004-A/B inputs -> RG-006, then RG-006 lifecycle evidence -> final RG-004 integration. No product acceptance gate was removed. +- **Senior Dev:** Proposed and was assigned RG-004-B1 typed public-root/leaf validation against immutable policy/trusted UTC, producing immutable identity/fingerprint/validity metadata. Policy encoding and supervisor manifest serialization are untouched; PeerAuthenticator/AuthorizationResolver are a later B2 slice. +- **Master:** Created `feature/RG-004-certificate-registry` from verified PR #9 head. Selected finite 64 KiB/certificate and 64 MiB aggregate public-PEM bounds under NFR-008; the existing 10,000 principal limit is policy-v1's implementation cap, not D6's 10,000 tenant cap. A snapshot's validation timestamp does not itself prove later service readiness. +- **Tester:** Assigned independent OpenSSL positive/negative fixtures and meaningful defect detection against actual compiled registry code. No fake-only acceptance. +- **Junior Dev:** Assigned independent integer certificate-validity, boundary, cap and lifetime review; does not edit the Senior's implementation. +- **Master:** Updated live dependency tables/context and PR #7 summary. A metadata read initially used the wrong connector parameter name; schema validation rejected it without mutation, then the corrected read succeeded. Main is still `71393cf11a0f8508cfb7e85b85538ccc22067f75`. + +### LOG-029 — 2026-11-17 04:23 UTC observation: registry PR published; interrupted agent handoffs + +- **Senior Dev:** Drafted bounded typed registry loader and developer tests. Implemented direct/self signatures, strict chain purposes, P-256/SHA-256/role EKU, root/policy binding, exact principals, owned metadata and explicit UTC validity. No local OpenSSL compile available. +- **Junior Dev:** Independently reviewed the implementation; raised RFC 5280 tag/year canonicality and unused helper issues. Senior corrected these before publication. Master also identified unused local/header includes and requested validity classification before chain verification; corrections are included. +- **Tester:** Authored independent metadata/hash/identity/chain/time/cap/lifetime tests and a separate root-pin-bypass mutant generator/checker. The normal suite must pass before the mutant is accepted as detected. Local compile failed explicitly because OpenSSL headers are absent; no local acceptance is claimed. +- **External capacity blocker:** Senior Dev and Tester encountered account usage-limit errors after drafting. Master preserved their files and took over integration; final agent sign-off has not occurred. A later retry asks Tester to review the actual CI result if capacity has returned. +- **Master:** Added standalone signed-certificate profile fixtures for algorithms, CA/path length/key usage/EKU, signatures, canonical dates, pre-1970 validity and root expiry. A local patch did not match the current draft; reread and normalized the profile test to 21 unique cases before publication. No failed patch is counted as a check. +- **Master checks:** Python mutation generation and Ruby YAML duplicate-key, 15 unique step-name and all run-block shell-syntax checks passed. These are harness checks, not production crypto evidence. +- **Publication:** [draft PR #10](https://github.com/kshiteesh28/DistributedRateGuard/pull/10), `feature/RG-004-certificate-registry` -> verified RG-004-A, head `6366df84903049fde3fd92243b3aa7bd06c43986`. One atomic code/test/build commit preserves the frozen input contract. Linux/OpenSSL/ASan execution remains pending. No B1 acceptance, full RG-004 completion, quota behavior or main merge is claimed. + +### LOG-030 — 2026-11-17 04:29 UTC observation: registry execution and independent acceptance + +- **Observed:** [run 44016873892](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44016873892) succeeded at head `6366df84903049fde3fd92243b3aa7bd06c43986`, tested merge `e03a5291889bb7fc9078bd5bda6b822657ea3cc7`. Both clean builds passed 21 CTest groups; clock sanitizers passed 3/3 and security sanitizers 6/6. Python checks total 16 (13 manifest verifier +3 policy oracle); 12 generated files match; C++20 evidence covers 39 project compile commands and exact package lock. +- **Tester:** Capacity returned; independently fetched exact source/logs and accepted the B1 input. Confirmed normal positive control then precise rejection of a compiled root-pin bypass; fractional validity/caps/lifetime tests and 21 signed profile cases passed. No material scoped test/code blocker remains. +- **Senior Dev:** Resumed a read-only audit at the exact published head and observed completed CI. Found no remaining registry/build/test blocker; no files changed during this final audit. +- **Master:** Archived [B1 evidence](evidence/RG-004-B1.md), manifest and native/Docker observations. Docker matched clocks under restricted capabilities again; registry tests ran on hosted Linux, so this is not actual service/container topology or epoch proof. +- **Master:** Marked PR #10 ready, kept it stacked on PR #9, and updated live board/context/input contracts. RG-006 consumes verified B1 metadata for manifest development, not full RG-004 Done. All full authentication ACs, operational guards, supervisor/witness/service integration and numerical release gates remain open. +- **Handoff:** Next code slice is B2 peer/policy authorization, then live validity/reconnect guards. No implementation branch was merged to main; prior component PRs remain unmerged. Estimates are still estimates; no active-agent effort is inferred from these observation timestamps. + +### LOG-031 — 2026-11-17 04:32 UTC observation: final Scrum audit and handoff consistency + +- **Scrum Master:** Independently confirmed PR #9/#10 ready and unmerged, exact B1 evidence counts and unchanged main `71393cf`. Found no overstated full-story, Docker deployment or quota claims; the A/B1 -> RG-006 -> final security integration split is consistent. +- **Master:** Addressed the audit's three metadata findings: story heading now names both verified inputs; board names remaining manifest/auth integration; context lists actual B1 header/source paths as verified only on the unmerged review branch. Reconciled stale sprint wording and retained historical findings in earlier log entries. +- **Verification:** Re-reading JSON, unique story/log IDs, dependency references and changed Markdown fences before handoff. Full RG-004 AC01–03 stay open. Next implementation work is B2 authenticated peer/policy authorization; no merge or release completion. + +### LOG-032 — 2026-11-17 04:51 UTC observation: B2 ownership and error contract frozen + +- **Master:** Re-read main PRD 8 / SRD 5 / LLD 5, current live security defaults/context, frozen proto and verified PR #10 metadata. Created `feature/RG-004-peer-authorization` from `6366df84903049fde3fd92243b3aa7bd06c43986`. No AGENTS.md found in cwd/ancestors. GitHub stays the review source; temporary files are staging only. +- **Scrum Master:** Confirmed B2 consumes verified RG-001/002/A/B1 inputs without waiting for RG-006/full RG-004. Final trust rotation/privacy and service acceptance still require their separate integrations. Existing INVALID/UNAUTHENTICATED enum values remain frozen but are not successful decision responses. +- **Senior Dev:** Verified pinned gRPC 1.51.1 AuthContext/TLS source. Experimental TLS exposes `tls`, `peer_uri`, `x509_pem_cert`; chain PEM and convenience identities are not fallbacks. Assigned real peer extraction/pin/time validation and opaque identity. +- **Junior Dev:** Assigned pure authorization/result types, immutable cost/permission/epoch/slot checks and developer tests. “Pure” excludes quota/state/routing; it still rechecks current trusted UTC. +- **Tester:** Assigned independent actual-mTLS handler fixtures, state-port spy, same-connection expiry proof, opaque lifetimes and unsafe-variant detection. Original policy golden stays unchanged; replica-permission variants are test-only. +- **Master decisions:** [B2 contract revision 1](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-peer-authorization/docs/contracts/peer-authorization-v1.md) fixes unknown selectors/request binding/method-mode errors as INVALID_ARGUMENT, configured forbidden pairs/roles as PERMISSION_DENIED, trust or cross-registry tokens as UNAUTHENTICATED. Time/config/crypto dependency failures use application UNAVAILABLE on gRPC OK. Commitment is caller-owned, never inferred by these ports. +- **Ownership review:** Tokens/results retain their exact immutable registry and have no public arbitrary-principal constructors. Root identified raw-pointer/moved-from lifetime risk; Senior removed the raw pointer and used owned URI/role. Explicit copy-only semantics preserve rvalue-source ownership; deleting move operations was rejected because it can break variant conversion. +- **Pre-publication review:** Root found PEM_read can skip untrusted prefix text and flagged the missing strict-prefix check, oversized credential status, explicit URI ASCII/DER bounds and resolver role-before-field ordering. Owners are correcting these; no runtime pass is claimed. +- **Gate:** B2 code/tests are in progress; no B2 CI, full authentication AC, forwarding, grant/debit, benchmark or main merge. + +### LOG-033 — 2026-11-17 05:03 UTC observation: first B2 SDK build and stronger proof ownership + +- **Senior Dev / Junior Dev:** Delivered peer authenticator and resolver plus developer tests. Private results retain caller/method/epoch/digest/cost and fixed replica slot/incarnation. Senior review caught and Junior fixed missing mandatory slot provenance for StrictCheck. +- **Master-owned design correction:** Default memberwise assignment could change a proof's registry before an allocating string copy failed. All proof types now hold a single immutable shared payload; copying/assignment preserves a complete snapshot atomically with respect to exceptions. No default/arbitrary-principal constructors or destructive implicit moves exist. +- **Publication:** [draft PR #11](https://github.com/kshiteesh28/DistributedRateGuard/pull/11), head `42eb82959e5e868456dbac1f7d120d4aedafafce`, targets verified B1. [Run 44021072784](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44021072784) compiled actual gRPC/OpenSSL/protobuf and passed the primary developer/component tests. Clean rebuild and sanitizer steps remain pending at this observation. +- **Master local check:** YAML duplicate-key/step-name and shell syntax validation passed after replacing unavailable Psych.safe_load_file with the installed safe_load API. This preflight is not SDK execution. +- **Tester:** Initially extended the matrix/source review; Master redirected the next handoff to actual RPC fixture code. The fixture is now in progress, using the normal frozen services, exact endpoint roles, state-port spies and application error assertions. No product quota implementation is introduced. +- **Senior fixture review:** Identified private resolver-constructor misuse, a server verifier accidentally pinned to an empty expected identity, and authority dependency failures returning gRPC OK with an unspecified proto outcome. Tester is correcting these before publication. +- **Master fixture review:** Required shorter selected-leaf validity than root validity, unchanged verifier handshake count and stable connection evidence for same-connection expiry. Two RPCs on a channel alone are insufficient. Real reconnect/resumption and precommit/forward wiring remain open. +- **Acceptance:** B2 remains draft until independent real-RPC and unsafe-variant evidence passes; the primary developer pass does not close that gate. No main merge. + +### LOG-034 — 2026-11-17 05:13 UTC observation: real RPC and isolated unsafe variants published + +- **Observed first bundle:** [run 44021072784](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44021072784) passed at `42eb82959e5e868456dbac1f7d120d4aedafafce`, tested merge `7b7e0fb18c321c1ab87bcf6f3dac1257842624dd`: 23 CTest groups twice, clock 3/3 and security 8/8 sanitizer checks, 16 Python checks, 12 generated matches, 45 actual C++20 compilation commands and exact lock. This did not include the independent RPC fixture. +- **Tester:** Completed two real gRPC mTLS servers with Replica/Authority endpoint leaves, direct property assertions, role/policy/binding/status checks, state-port spies and unknown/changed-leaf TLS rejections. Shorter leaf than root validity plus stable endpoint, retained AuthContext and unchanged verifier count distinguish dispatch expiry from a new handshake. Probe sink emits UNAVAILABLE, never quota ALLOW or GRANTED. +- **Thread-safety correction:** Master identified plain cross-thread clock and observation fields in the draft fixture; Tester added mutex-protected clock/observation snapshots. State-spy atomics publish cost before the release counter. Fake clock resets isolate cases and are explicitly not supported epoch recovery. +- **Master integration:** Used the frozen no-retry enforcement-channel factory for fixture channels. Added bounded stdout/stderr file limits, 120-second process timeouts and generic PEM-armor scanning; child output is withheld. Preserved QA's normal-positive-first controls and exact unsafe failure markers. +- **Unsafe variants:** Separate compiled libraries remove only the CheckAdmission permission guard or the per-call leaf-pin comparison. Normal production targets have no bypass flags. The permission variant leaves the independent credit guard unchanged; no credit-mutation coverage is claimed. +- **Publication:** Atomic head `a0a072eb9992fac45439d46ab07e52410984bd57` adds the real fixture/mutants and sanitizer wiring. Its CI is pending; first-bundle green does not accept this new head. PR #11 stays draft and main is untouched. + +### LOG-035 — 2026-11-17 05:18 UTC observation: RPC compile findings fixed; primary run green + +- **Observed failure:** [run 44022535591](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44022535591), job `133835097642`, failed compiling the new RPC test. It referenced InvalidArgument/PermissionDenied members removed from PeerAuthDisposition; AuthorityProbe's local Check helper also hid the assertion function. No new RPC/mutation runtime test ran in this failed build. +- **Tester:** Independently fetched actual compiler logs and identified both fixture issues. +- **Master:** Removed impossible peer-auth switch cases and renamed HandleStrictCheck at head `9d14bb74bd937401471e96e039f651c17c226c43`. Production authentication/resolver code is unchanged. +- **Observed rerun:** [run 44022842950](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44022842950) compiled successfully and passed the primary test step, including the real RPC and isolated mutant controls. The clean rebuild and sanitizer lanes are still pending at this observation. +- **Gate:** PR #11 stays draft. A passing primary suite is not a completed workflow or final independent acceptance. No quota or release pass is claimed. + +### LOG-036 — 2026-11-17 05:24 UTC observation: independent B2 acceptance and documentation promotion + +- **Observed:** [run 44022842950](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44022842950), head `9d14bb74bd937401471e96e039f651c17c226c43` / merge `d1027f6a455284b6a4b626d4f6de15f1771cd2f8`, passed 25 CTest groups twice, clock 3/3 and security 9/9 sanitizer checks, 16 Python methods (13 manifest +3 policy), 12 generated matches and 53 C++20 compilation commands with exact package lock. +- **Tester:** Independently fetched source/logs and accepted actual TLS property, policy/state-spy, dispatch-expiry and isolated pair/pin controls. Rejected TLS clients do not reach handlers. No remaining scoped test blocker. +- **Senior Dev:** Independently reviewed exact source and observed complete CI; no material B2 code blocker. Flagged stale “evidence pending” text in the PR and contract. +- **Master:** Archived [B2 evidence](evidence/RG-004-B2.md), manifest and native/Docker observations. Docker remains capability-only; no quota service, commit, forwarding, fencing, reconnect/resumption or release gate is accepted. +- **Documentation promotion:** Updated only the contract status/link at `20210d5fbabcd891dbbb20ab89eca26f3a73a1db`. GitHub compare confirms one file, one added/deleted line, no implementation changes. PR body now distinguishes verified implementation evidence from the final documentation-head CI. The latter must finish before ready status; no further code change is planned without a new finding. + +### LOG-037 — 2026-11-17 05:30 UTC observation: final head green and B2 ready + +- **Final result:** [run 44023785687](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44023785687) passed at `20210d5fbabcd891dbbb20ab89eca26f3a73a1db`, merge `31084e66433126412a5e22457c13fde1f34350b1`: 25 CTest groups twice, 3 clock +9 security sanitizer checks, 16 Python methods, 12 generated-file matches, 53 C++20 commands and exact package lock. The implementation is unchanged from the independently accepted head. +- **Master:** Marked [PR #11](https://github.com/kshiteesh28/DistributedRateGuard/pull/11) ready and unmerged, refreshed its body, archived final manifest/native/Docker observations and linked them from [B2 evidence](evidence/RG-004-B2.md). Docker again returned OBSERVATIONS_MATCHED; this is capability evidence only. +- **Scrum Master:** Independently found current scope, dependencies, paths and full-story gates consistent, then flagged the work-log header/board still omitting B2. Master added PR #11 and narrowed the remaining-work wording to client guards and real service/lifecycle/export integrations. +- **Handoff validation:** Context now points to actual public headers/sources and immutable tested revisions, with separate code and documentation-head evidence. Full RG-004 AC01–03, all deployment and numerical release gates remain open. +- **Main:** Still `71393cf11a0f8508cfb7e85b85538ccc22067f75`; no implementation merge. No further feature-branch edit is needed for this scoped delivery. + +### LOG-038 — 2026-11-17 15:56 UTC observation: B3 contract, client boundary and agent assignments + +- **Master:** Re-read main PRD 8 / SRD 5 / LLD 5, live context/security decisions, verified B2 PR #11 head `20210d5fbabcd891dbbb20ab89eca26f3a73a1db`. Main remains `71393cf`; no cwd/ancestor AGENTS.md. Created `feature/RG-004-client-guards` from B2. +- **Scrum Master:** Confirmed B3 consumes named A/B1/B2 plus RG-001/002 inputs without RG-006 cycle. Full security AC01–03 stay open; actual commit/forward/fencing and event privacy are separate integrations. +- **Master decisions:** [B3 contract revision 1](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-client-guards/docs/contracts/pinned-client-v1.md) fixes own-client/root/pinned-server checks, sealed typed client/no raw escape, NotSent versus Invoked, no inferred prior commitment, raw reply retention and bounded configuration/deadlines. Production disables session caching/retries/hedging. +- **Senior Dev:** Assigned internal TLS credentials/pin/key construction and exact-once typed methods. Root required preallocated immutable invocation storage so an exception after stub entry cannot fabricate NotSent or mix reply/proof generations. Private keys are bounded in-memory inputs with no prompt/log output. +- **Junior Dev:** Delivered pure guard and boundary tests with private immutable tokens, exact binding, fresh health/UTC checks, root/client/server validity and pre-forward clock-regression rejection. Then independently reviewed the wrapper. +- **Tester:** Implementing real sealed-client fixtures and a separate bounded session-cache probe. Warm-channel expiry, fresh reconnect and actual TLS resumption are distinct evidence. The production factory remains cache-free even if native qualification succeeds. +- **Primary-source research:** Master/Senior independently verified gRPC v1.51.1 opt-in LRU session cache, TLS credential consumption, session-reused auth property and C++ pointer-vtable channel args. No resumed-session capability is claimed until actual new-transport reuse and required leaf/pin metadata are observed. +- **Pre-publication findings:** Junior caught an out-of-sync guard enum name. Master caught a three-argument CreateChannel call (requires CreateCustomChannel) and a private-key PEM parser that could skip a preceding unrelated block. Senior is correcting staging before publication; no SDK/test pass is claimed. +- **Gate:** B3 code/independent qualification is in progress. No quota/credit commit, forwarding, production PKI/provisioning, benchmark, epoch fencing, main merge or full AC completion. + +### LOG-039 — 2026-11-17 16:28 UTC observation: B3 first publication and compiler-led rework + +- **Publication:** [draft PR #12](https://github.com/kshiteesh28/DistributedRateGuard/pull/12) targets verified B2. Initial head `64a10b49d5983d8d0aef21dc6b625066dff54d74` supplied guard/wrapper and developer tests for pinned Linux SDK compilation; the local host lacks the SDK and no stub/shim pass is claimed. +- **Run 44121725431:** Build failed on the guard source alias ClientCallGuardFailureReason versus the declared ClientGuardFailureReason. No tests ran. Master corrected the alias while integrating QA. +- **Tester:** Completed independent real-client fixtures for root/own-client/server expiry, pre-forward/raw-reply preservation, factory/key/pin/deadline rejection, both CREDIT and in-memory STRICT authority methods, and a separate JSON session probe. The golden policy is untouched. +- **Qualification review:** Junior caught a false “fail closed” label after an accepted resumed RPC with insufficient evidence. Tester added unsafe-result failures and explicit native metadata/verifier-delta checks. Master narrowed non-OK/no-handler wording to “no dispatch observed,” not an invented cause; production caching remains disabled. +- **Master integration:** Added bounded/redacted child-output checks, exact preflight-bypass mutation detection and structured session evidence. Local Python syntax/mutant generation and 16-step YAML/shell validation passed; these are harness checks only. +- **Run 44124426978:** Build then failed on 14 stale enum references in the developer guard test. Master’s first correction was incomplete; Master replaced the test references. +- **Run 44124929387:** Build exposed another stale reference in the wrapper. A full source/test sweep also found five in QA. Master fixed wrapper+QA together at `1101d83071b78d3d1b8ddf3da9d18b01bd42e416`. No runtime acceptance is attributed to these failed builds. +- **Run 44125439681:** Production libraries compiled; QA compilation failed on two unsupported WallTime operator> comparisons and an unused expire_server parameter under -Werror. Tester/Senior independently fetched actual errors. Master changed comparisons to the supported ordering and asserted exactly one expiry case. +- **Current head:** `d45839a972386ae8da8186e56945e160fa5d8622`. Master’s first text patch used an incorrect local parameter name and aborted before writing; the fresh-blob retry succeeded. Complete runtime, sanitizer and session evidence remains pending. +- **Scope:** NotSent is local to the current attempt, Invoked retains raw uncertain transport/reply, and no component commits quota/forwards/fences. No B3/production/resumption pass or main merge is claimed. + +### LOG-040 — 2026-11-17 16:41 UTC observation: B3 runtime fixture correction + +- **Observed:** [run 44126127941](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44126127941) built all targets at `d45839a972386ae8da8186e56945e160fa5d8622`. Primary CTest passed 27/29 groups; normal B3 RPC and mutation controls failed at fixture_policy_load. Clean rebuild, sanitizers and session probe were skipped. This is not B3 acceptance. +- **Tester:** Independently identified that the in-memory STRICT fixture omitted the mode change while removing credit_batch_units. An earlier hypothesis about missing replica permissions was withdrawn after checking PolicyLoader; those permissions are not a loader requirement. The terse failure marker does not establish which earlier subcases ran. +- **Master:** Published `0a1b37b6147adb39c885459253d59c8561c9c5cc`, setting strict mode explicitly and adding a fixed numeric PolicyErrorCode diagnostic without policy/credential output. Golden fixture and production code are unchanged. +- **Verification:** [run 44128491936](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44128491936) is in progress. Senior Dev and Tester are reviewing current source/results independently; Scrum Master is checking dependency/handoff readiness and preparing RG-005 scope. +- **Gate:** PR #12 remains draft. Production session caching remains disabled. Full RG-004 AC01–03, real commit/forward/fencing, deployment and release gates remain open; no main merge. + +### LOG-041 — 2026-11-17 16:47 UTC observation: independent B3 acceptance + +- **Observed:** [run 44128491936](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44128491936) passed at `0a1b37b6147adb39c885459253d59c8561c9c5cc`, tested merge `1fe328849653f92486fa69695e649a6049e961b0`. Both clean builds passed 29/29 CTest groups; clock sanitizers 3/3 and security sanitizers 12/12 passed. Sixteen Python methods (13 manifest +3 policy), 12 generated-file matches, 65 C++20 compile commands and the exact build lock passed. +- **Tester:** Independently accepted actual mTLS fixtures, warm root/client/server expiry, both authority methods, retry counters, pre-forward reply retention and isolated preflight-bypass detection. Session JSON reports qualified: actual reuse on a new transport, cache capacity 1, two attempts, exact leaf pins and fresh verifier deltas of one on each side. Production cache remains disabled. +- **Senior Dev:** Exact-head source audit found no material scoped production blocker. Immutable shared payload ownership, pre-invocation allocation, post-entry uncertainty, no raw channel escape, retry/cache configuration, current trust checks and bounded deadlines were reviewed. Earlier claim about the first failing expiry case was corrected: expiry flags are not strict-policy flags; the prior terse error did not identify the failing subcase. +- **Master:** Archived [B3 evidence](evidence/RG-004-B3.md), manifest, session JSON and native/Docker observations. Docker OBSERVATIONS_MATCHED remains capability-only. Refreshed context/sprint/security evidence and PR #12 for review readiness without changing tested feature code. +- **Scrum Master:** Confirmed RG005 may start from RG001; it does not wait for full RG004 or RG006. Retained RG004 A/B1→RG006→final AC02 cycle break and RG011A strict UNKNOWN gate before RG008/Release A acceptance. +- **Junior Dev:** Proposed typed event envelopes and reserve/publish/seal tests; identified cross-process run-wide budget ownership, producer roster and encoded-size accounting as decisions to freeze before RG005 code. Incorrect live-ref lookup was corrected by Master: branch docs/scrum-work-log exists; fetch files with that ref, not as a path. +- **Scope:** Full RG004 AC01–03, live services, quota/witness/forwarding/fencing, deployment, benchmarks and model checking remain open. Main remains `71393cf11a0f8508cfb7e85b85538ccc22067f75`; no implementation merge. + +### LOG-042 — 2026-11-17 16:49 UTC observation: final scrum readback and handoff corrections + +- **Scrum Master:** Independently confirmed PR12 ready/unmerged, exact head/run/evidence, test-only resumption scope, cache disabled, full RG004 ACs open, RG005 next and RG011A Release A prerequisite. Found stale B3-pending wording in the story catalog, context first_action/remaining_evidence and security decision header. +- **Master:** Corrected those handoff fields without touching tested implementation or binding specs. Readback confirmed 14 unique context stories, a valid dependency DAG, 41 unique prior log IDs, exact evidence JSON and unchanged main. PR7 summary now points through current B3 evidence. +- **Next:** RG005 event component contract must fix producer roster, encoded byte accounting, reservations/publications/seals and one run-wide 1 GiB budget before code. Static disjoint producer partitions are being evaluated as a bounded option; no RG005 implementation or acceptance is claimed. + +### LOG-043 — RG-005 implementation starts (2026-11-21 UTC) + +- **Master:** Continued from PR #13's feature head `c3f9bbf`. [PR #14](https://github.com/kshiteesh28/DistributedRateGuard/pull/14) targets that feature. Published the [strict history contract](contracts/strict-event-history.md) in `f54e226` and the seven-day local export cleanup in `69a533b`. Its isolated boundary test passed, including unrelated files and symlink preservation. The exporter must invoke cleanup when it starts using the private output directory. +- **Senior developer:** Owns typed per-producer reservations, bounded run accounting, publication and sealing. +- **Junior developer:** Owns structural snapshot validation against the independent expected producer plan. +- **Tester:** Owns reserve races, exhaustion, evidence corruption and missing-seal checks against the implementation. Test results will be recorded after execution. +- **Scope:** RG-005 implementation is underway. Durability, runtime traffic stops, retention integration and release acceptance remain open. + +### LOG-044 — RG-005 components and independent review (2026-11-23 UTC) + +- **Master:** Resumed the existing story branch, read PR13/14 state and failed Actions logs, corrected CMake declaration syntax in `0e5ff3f`, checksum-fixture integer portability in `122a17d`, generated workflow content in `a67e47e`, and temporary test include path in `39224fc`. Added separate commits for Linux sanitizer coverage, durable publication and stage reconciliation. Latest code checkpoint is `0710354`. No whole-story acceptance is claimed. +- **Senior developer:** Finished POSIX streaming file publication with bounded output, private directory checks, exclusive temporary creation, file sync, no-overwrite hard-link publication, temporary removal and directory sync. Reported uncertain directory durability separately. Root review added exception cleanup and EINTR-safe fsync handling. Local publisher tests passed under Clang ASan/UBSan. +- **Junior developer (prior session):** Delivered independent structural validation and bounded aggregate counters with concurrency/saturation tests. A later CLI assignment ended at the agent usage limit and produced no accepted CLI deliverable. +- **Tester:** Finished independent strict reconciliation and regressions for lost/late/equal-deadline outcomes, duplicate stages, orphan evidence and forwarding. Root requested corrections to LIMITED/debit distinction, missing-offer detection and forwarding authorization; the tester addressed them and root reran the suite under ASan/UBSan. +- **Master verification:** Ran seven local C++20 component suites and the Python retention fixture. Added a Linux sanitizer lane. Earlier failed CI is preserved and excluded from passing evidence. See [RG-005 evidence](evidence/RG-005.md) for scope and pending runtime work. +- **Remaining:** Supervisor/process wiring, actual service event recording, traffic stop propagation, cleanup invocation, persisted incomplete summaries, CLI and RG-011A provenance/semantic checks. Review branches target the integration feature; PR13 remains the final promotion to main. + +### LOG-045 — Linux verification and component integration (2026-11-23 UTC) + +- **Master:** Fixed GCC's misleading-indentation rejection in the reconciliation fixture at `da19ea2`. [Run 45126587562](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45126587562) then passed on that exact head: 17 Python tests, 36 CTest groups twice, 12 matching generated files, three clock sanitizer groups, seven history sanitizer groups and twelve security sanitizer groups. +- **Scrum Master:** Independently confirmed PR14's scope/evidence and context wording leave runtime/story acceptance open. Flagged stale Planned labels in the story catalog and board; Master synchronized them to In progress. +- **Integration:** PR14 is ready to merge into `feature/distributed-rateguard` after documentation readback. PR13 remains the final promotion to main. Full RG004 and RG005 acceptance remains open. Next dependency order remains runtime owner/traffic-stop integration, RG006 lifecycle/fencing and RG007 witness, then RG011A evidence before strict RG008 acceptance. + +### LOG-046 — History inspector delivery and independent review (2026-11-23 UTC) + +- **Master:** Opened PR15 from the integration feature. Published the input contract, CLI, independent-fixture tests and evidence in separate commits. Reviewed diagnostic lifetime, checked-size overflow, field naming and failed-output handling; corrections were included before Linux acceptance. +- **Junior developer:** Implemented the offline C++ inspector using the existing reader/validator and existing nlohmann_json dependency. Added the strict decimal-string uint64 plan schema, duplicate-key detection, 1 MiB input cap and independent binary fixture driver. +- **Tester:** Independently rebuilt the CLI and ran its fixture, then checked escaped duplicate keys and secret-sentinel redaction. Root additionally exercised an independently constructed empty sealed history and ran the fixture under ASan/UBSan. +- **Result:** [Run 45129476268](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45129476268) passed at e0c9b554: 37 CTest groups twice, 17 Python tests, eight history / three clock / twelve security sanitizer groups, generated-file reproduction. PR15 merged into the feature as edaa0ab. [Evidence](evidence/RG-005-inspector.md). +- **Remaining:** Inspector success remains structural with safety UNKNOWN. RG005 actual service recording, stop propagation, cleanup invocation, incomplete-run persistence and RG011A remain open. + +### LOG-047 — Local epoch lifecycle gate (2026-11-23 UTC) + +- **Master:** Opened PR16 for the RG006 local gate, retaining the RG004 A/B1 dependency cycle break. Published contract, implementation, developer tests and independent tests separately. Merged the integration feature into this branch, preserving both inspector and lifecycle CMake/CI registration. +- **Senior developer:** Implemented immutable per-epoch inventory, PreActivation/ACTIVE/DRAINING/CLOSED phases, RAII commit permits and an internal controller port. Stop requests cover all adapters/replicas before exit inspection; authority/witness stop follows confirmed ingress/replica exits. Controller failures leave the gate draining. +- **Tester and Master review:** Found and corrected multiple-adapter rejection, missing startup cleanup, incorrect preactivation permit behavior, lease-owned mutex lifetime, stop ordering and terminal stop replay. PolicyLoader confirms arbitrary uint32 slot IDs with a maximum of eight entries; an assumed 1..8 ID range was rejected. Tester delivered separate adversarial/concurrency tests and synchronized its failure counter. Root reran both suites under ASan/UBSan. +- **Linux correction:** GCC reported helpers unused because NDEBUG removed developer assertions. Root replaced asserts with always-on checks and verified the release-mode fixture; a diagnostic formatting error in the intermediate fix was then corrected. Failed runs are excluded from acceptance. The current combined Linux run is pending. +- **Scrum Master:** Audited component versus full-story claims. Flagged source-revision metadata for the inspector contract and the gate's extra internal caps/topology assumptions. These are recorded as integration review items, with observable rejection and no silent SRD amendment. +- **Remaining:** No durable manifest, exclusive supervisor ownership, real OS/Docker evidence, host-reboot recovery, no-restart enforcement or successor-epoch fencing is implemented by this gate. Full RG006 acceptance stays open. [Evidence](evidence/RG-006-A.md). + +### LOG-048 — Combined Linux verification (2026-11-23 07:32 UTC) + +- **Master:** [Run 45130958093](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45130958093) passed at `6da5d90ce70be41cf9780a64b7bc360492a8d4ab` after combining the inspector and lifecycle build changes: 39 CTest groups twice, 17 Python tests, 12 matching generated files, two lifecycle / three clock / eight history / twelve security sanitizer groups. +- **Disposition:** PR16 is ready for integration into `feature/distributed-rateguard`; the following changes are documentation only. PR15 is already merged. PR13 remains the final promotion to main. +- **Acceptance scope:** RG005 and RG006 remain In progress. Gate/inspector component evidence does not complete actual services, durable manifest/controller recovery or RG011A. The 1 MiB plan cap and lifecycle participant/identifier bounds remain documented internal choices; broader supported deployment/configuration must be reconciled before full acceptance. + +### LOG-049 — Durable manifest codec and store (2026-11-23 UTC) + +- **Master:** Rechecked integration head 01a7438 and opened PR17. Published shared pure validation, exact candidate equality, the contract, codec, codec tests, store and filesystem tests in separate commits. Binding PRD/SRD/HLD/LLD sources remain unchanged. +- **Junior developer:** Implemented strict canonical JSON with SHA-256, decimal-string 64-bit values, fixed schema, 4 MiB input cap and a Python-derived golden digest. Root rejected initial assert-only fixtures and required always-on checks for NDEBUG builds. Codec [Linux run 45133952802](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45133952802) passed against real OpenSSL. +- **Senior developer:** Implemented store-directory ownership, new-only creation, generation/digest CAS, recovery-only reopening and synced replacement. Root review required explicit creation operation ID, metadata-only outcomes, exact success/error reporting, exception-safe ownership/reservation cleanup, responsive snapshots, parent-directory sync and all initial allocations before publication. +- **Tester:** Supplied independent tests for malformed/tampered artifacts, directory lock contention, failure injection, process exit around rename, stale temporary files, operation/phase checks and concurrent Busy/snapshot behavior. Re-digested edits are treated as structurally valid metadata, never authentication. +- **Interruption/recovery:** Prior Senior/Tester turns hit provider usage limits. After the user's continuation, Master resumed at 15:27 UTC, rechecked GitHub head and completed integration review. The elapsed interruption is not logged as developer effort. +- **Verification scope:** Local strict syntax checks pass. Local digest-stub smoke is excluded from real SHA-256 acceptance. Complete Linux store runtime results are pending. See [evidence](evidence/RG-006-B.md). +- **Open integration:** A store lock covers one directory. Durable global supervisor ownership and launcher bootstrap are still required. LLD's literal PID-start-before-launch wording needs an explicit staged launch-intent/identity-barrier resolution before launcher implementation. No existing ACTIVE manifest may resume service. + +### LOG-050 — Manifest persistence verified on Linux (2026-11-23 15:45 UTC) + +- **Master:** Linux [run 45207019201](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45207019201) passed at `ba2d14731b3f2e9e996049e67b9e4d702a2218d8`: 42 CTest groups twice, 17 Python tests, 12 matching generated files, three manifest / two lifecycle / three clock / eight history / twelve security sanitizer groups. +- **Corrections after initial CI:** Checked subprocess-pipe write results for fortified GCC. Added nonblocking manifest/lock opens and a named-pipe regression so invalid file types cannot block before validation. Real Linux runtime supersedes local syntax/stub smoke; earlier failed runs do not count as acceptance. +- **Audit:** Scrum Master independently confirmed scope/source revisions and no full-fencing, activation, authentication or rollback-freshness claims. The launch-order gap is recorded in the contract before any real launcher implementation. +- **Integration:** PR17 is ready for feature integration after documentation readback. PR13 remains the final promotion to main. Durable global supervisor ownership, bootstrap intents/identity barrier, actual process control and recovery still block full RG006. + +### LOG-051 — Startup design clarification (2026-11-23 UTC) + +- **Master:** Rechecked integration c65780d and opened PR18/19. Clarified HLD revision 5 and LLD revision 6 A-03: persist exact stopped-container launch intents before start; create non-serving processes; verify and persist host PID/start/clock identity before activation. The previous literal pre-process PID requirement was impossible. PRD 8/SRD 5 and all release gates remain unchanged. +- **Scope:** This resolves the design ordering; actual launcher/participant acknowledgements remain implementation work. Serving activation continues to require every policy, clock, trust, witness and lifecycle gate. + +### LOG-052 — Runtime-root ownership (2026-11-23 UTC) + +- **Senior developer:** Implemented RuntimeOwner and one-use InitialEpochClaim. The configured root's OS lock survives owner-object destruction while a claim exists; existing-root acquisition stays RecoveryRequired. The domain/path anchor is immutable and canonical. +- **Master review:** Required monotonic ownership invalidation, root/lock/anchor identity checks, FIFO-safe opens, bounded JSON parsing, realpath allocation ownership, fresh-OFD enumeration and pre-mutex inherited-PID rejection. Identified claim ordering that could taint a legitimate token after an epoch child appeared; fixed with one issuance reservation and non-poisoning repeat-claim outcomes. +- **Tester:** Independently exercised contention, token lifetime, inherited PID, restoration after taint, initialization/crash boundaries, root-path normalization and claim concurrency. Root checked child pipe writes before publication so fortified GCC can enforce their outcomes. +- **Evidence:** [Runtime ownership](evidence/RG-006-C.md). Local syntax tests pass. Shim-linked local POSIX/sanitizer checks are excluded from cryptographic acceptance; real OpenSSL/Linux CI is pending. +- **Remaining:** The configured-root guarantee does not cover alternate misconfigured roots. A fenced successor-epoch authorization protocol and actual process control remain open; root recreation cannot substitute for recovery. + +### LOG-053 — Runtime ownership verified on Linux (2026-11-23 23:20 UTC) + +- **Master:** [Run 45286150998](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45286150998) passed at `abd4a1bb30eecbc3d8eae3f5f582e5c5660d6780` (PR merge ref 79eb61f): 44 CTest groups twice, 17 Python tests, 12 matching generated files, three manifest / two owner / two lifecycle / three clock / eight history / twelve security sanitizer groups. Real OpenSSL evidence supersedes shim-only local smoke. +- **Correction:** After pre-mutex fork rejection was added, the independent child fixture still expected the older RecoveryRequired enum. Updated it to OwnerProcessChanged; no failed run is counted as acceptance. +- **Scrum Master:** Confirmed scope and staged startup ordering; flagged missing new-class detail in LLD and stale tracking metadata. Those documentation corrections are being recorded, with successor-epoch recovery explicitly open. +- **Integration:** PR18 is ready for feature integration after readback. PR19 depends on it and adds initial bootstrap inventory/persistence. Full RG006 process control, authenticated activation and positive-fencing acceptance remain pending; PR13 remains final promotion to main. + +### LOG-054 — Bootstrap inventory, persistence and independent review (2026-11-23 UTC) + +- **Junior developer:** Implemented the immutable BootstrapInventory, canonical schema-1 codec/digest, fixed planned roster and exact process-identity registration. Added a claim-consuming initial BootstrapStore with revision/digest CAS, explicit publication visibility and last-durable snapshots. Separate commits publish model, fixtures, store and tests. +- **Master review:** Required non-wrapping revision exhaustion, exception-safe validation, allocations before publication, independent storage/transition result fields, responsiveness during filesystem work and no implicit ready/serving grant. Refactored shared POSIX descriptor helpers without changing manifest behavior. +- **Senior developer:** Identified the temp-sync-to-rename revalidation gap. The store now rechecks exact old bytes/inode before update replacement; initial publication uses no-replace linkat. Drafted LLD 7's implemented-class boundaries and future controller handoff, including the unresolved create-success/intent-write-failure recovery window. +- **Tester:** Added independent callback-race tests for competing initial publication and later inode replacement, plus a durably recorded identity mismatch that remains recovery-required. Fake-EVP local sanitizer results are smoke only and excluded from real cryptographic acceptance. +- **Linux correction:** Run 45286601485 passed 47 of 48 CTest groups; the failing developer fixture had created the epoch child before the mutation hook, correctly triggering ExistingEpoch. Junior removed that setup only from the race test, preserving pre-existing-child rejection coverage. Failed and superseded/cancelled runs are not acceptance. +- **Scrum Master:** Confirmed no process-control/fencing/activation overclaim, flagged missing LLD class entries and stale metadata. Master synchronized the story catalog, context and sprint sources. A final LLD audit confirmed class scope and required explicit EpochSupervisor ownership of the still-missing intent recovery reader. PR18 merged as 90399f6; PR19 includes it as an ancestor before final Linux verification. +- **CI infrastructure:** Increased the expanded pipeline's job budget from 15 to 25 minutes and retained clean/bootstrap/manifest/owner/lifecycle/history sanitizer logs. This affects CI execution only; no product deadline, latency or throughput gate changed. +- **Remaining:** Initial epoch storage is a component only. Actual Docker identity/provenance, authenticated bootstrap acknowledgements, witness/trust gates, process cessation and verified successor-epoch claims remain RG006 integration work. [Evidence](evidence/RG-006-D.md). + +- **Next technical handoff (Senior developer):** Build the controller/orchestration boundary with exact create-stopped, start-non-serving, inspect, stop and positive-exit outcomes. Fake-controller tests may establish ordering only; real Docker/Linux evidence is required for process identity, cessation and activation. Reconcile create-success/intent-write-failure rather than inferring an empty inventory. + +### LOG-055 — Bootstrap component verified on Linux (2026-11-23 23:32 UTC) + +- **Master:** [Run 45287922499](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45287922499) passed at `03e618b311056227fe6bccb4b9143ced00d2f28c` (PR merge ref be6acc0697bca17f70803009327289de19c2abd0 against ownership integration 90399f6). Evidence: 48 CTest groups twice, 17 Python tests, 12 matching generated files, four bootstrap / three manifest / two owner / two lifecycle / three clock / eight history / twelve security sanitizer groups. No sanitizer errors were reported. +- **Design:** LLD 7 records the exact implemented ownership/bootstrap classes, corrects existing EpochGate/ManifestStore APIs and adds their class diagram. HLD remains 5; PRD 8 and SRD 5 are unchanged. Source/link/JSON/DAG checks pass; no class-design claim closes the remaining integration gates. +- **Scrum audit:** Confirmed candidate-only data handoff and no serving/fencing overclaim. Root made the absent EpochSupervisor-owned recovery reader explicit and qualified RuntimeOwner::OpenExisting; these are not recovery or successor-epoch capabilities. +- **Integration:** PR19 is ready for feature integration after readback. Only documentation follows the tested source. PR13 remains the pending final promotion to main. RG006 remains In progress; recovery reader/controller/activation/fencing work continues. + +### LOG-056 — Existing-intent recovery reader started (2026-11-23 UTC) + +- **Master:** PR18/19 are merged into the feature (90399f6 / cb98d78) with real Linux component evidence. Opened a separate recovery-reader branch from cb98d78; main remains unchanged and PR13 is the final promotion. +- **Senior developer:** Proposed a recovery-mode-only diagnostic reader with immutable per-epoch records, exact ownership/domain/basename validation and bounded scans. No serving/candidate/successor API is proposed. +- **Junior developer:** Independently identified that RuntimeOwner::OpenExisting does not enumerate root contents; reviewed mkdir/initial publication/update crash windows and required retaining pending-container IDs while blocking incomplete inventories. +- **Tester:** Preparing separate adversarial filesystem, identity, input-limit and mutation fixtures against the reviewed header. Local shim checks remain excluded from real cryptographic acceptance. +- **Master decisions:** Accepted finite reader-only caps in [contract](contracts/bootstrap-recovery-v1.md), typed diagnostic outcomes, all-entry bounds, immutable known-target retention and conservative attempted-byte charging. A structurally complete scan cannot prove historic durability or process cessation. Implementation and Linux verification are pending. + +### LOG-057 — Recovery reader implementation and independent checks (2026-11-23 UTC) + +- **Senior developer:** Implemented recovery-only immutable diagnostics, canonical domain/epoch binding, pending-identity retention, typed issues, repeated metadata/listing/owner validation and finite resource budgets. Added developer fixtures for 17×1,024 participants, attempted bytes including malformed files and 1,024+1 epoch directories. +- **Master review:** Required RAII directory cleanup and fdopendir ownership, fresh sorted enumeration, hard issue caps that preserve readable intents, UID/link/time/inode revalidation, and root metadata comparison. Isolated the epoch cap with valid fixtures so unrelated issue saturation cannot mask it. Published API, library, developer tests and independent tests/build integration in separate commits. +- **Tester:** Independently exercised read-only repeats, historical/pending data, suspicious file types, replacements and mutation hooks, binding/collision errors and scan/issue caps. Corrected a filesystem-order-dependent root-overflow assertion. Both independent and corrected developer suites passed strict NDEBUG + ASan/UBSan locally with fake EVP; this is smoke, not cryptographic acceptance. +- **Linux correction:** [Run 45292023290](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45292023290) passed 49/50 groups including independent reader checks, but a developer fixture reused a newly created ownership root and failed at CreateNew. Master separated the fixtures using a distinct TempRoot in commit87c784b; production ownership/reader behavior is unchanged. Earlier failed/superseded runs are excluded. +- **Junior developer:** Drafted LLD 8 with the reader class, API/result ownership, exact caps and diagnostic-only handoff. Master corrected diagram dependency directions and post-scan failure wording; HLD 5 / PRD 8 / SRD 5 remain unchanged. +- **Scrum Master:** Audited implementation against contract; no concrete behavior mismatch or fencing/serving overclaim found. Full real Linux/OpenSSL CI remains pending. [Evidence](evidence/RG-006-E.md). + +### LOG-058 — Diagnostic recovery reader verified on Linux (2026-11-24 00:05 UTC) + +- **Master:** [Run 45292546023](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45292546023) passed source `87c784b25d47dd97527709756fd63673671af470`, merge ref `0784213de9ec24bf7e111224363f04a56909f4cb` against cb98d78. Result: 50 CTest groups twice, 17 Python tests, 12 matching generated files; six bootstrap/reader / three manifest / two owner / two lifecycle / three clock / eight history / twelve security sanitizer groups. No sanitizer errors. Real OpenSSL evidence supersedes shim-only local smoke. +- **Design and handoff:** LLD 8, JSON context, story and sprint sources now describe the actual diagnostic-only reader, exact caps, and initial-fatal versus later-incomplete ownership failure. All source links/JSON/story DAG checks pass. PRD 8 / SRD 5 / HLD 5 are unchanged. +- **Integration:** PR20 is ready for feature integration after readback. Only documentation follows tested source. Full RG006 remains In progress and PR13 remains the final promotion to main. +- **Next review finding (Senior/Master):** BootstrapStore creates epoch/intent.json while ManifestStore requires a separate new directory; current reader rejects all other siblings. Master selected a shared versioned manifest-store layout and format-specific validation for the next separate PR. Pending-identity controller targets, positive Docker exit evidence, durable recovery orchestration and successor authorization remain required. + +### LOG-059 — Epoch artifact-layout integration started (2026-11-24 UTC) + +- **Master:** PR20 merged as 9d90746 after real Linux verification; opened the separate artifact-layout branch from that feature head. Selected [layout v1](contracts/epoch-artifact-layout-v1.md): epoch intent plus optional private manifest-store directory. Missing/unknown/temporary artifacts remain uncertainty; a manifest phase never proves process cessation. +- **Senior developer:** Extending the read-only reader with independent manifest scanning, canonical cross-artifact candidate comparison, bounded nested validation and diagnostic manifest retention even when the intent is unavailable. Identified pending-bootstrap comparison as unavailable rather than an actual candidate mismatch. +- **Junior developer:** Implemented shared exact names and pure checked epoch parse/format helpers; grammar tests pass under strict NDEBUG. Prepared narrow BootstrapStore/ManifestStore name-reuse patches. Root review preserved existing validation precedence before formatting and publication. +- **Tester:** Independently preparing matching-phase, missing/corrupt/mismatched-artifact, nested type/link/mode/temp/mutation and shared-budget cases. Flagged pending-bootstrap classification before publication. +- **Scope:** This integration resolves artifact composition only. Controller targets for pending identities, real Docker exit evidence, recovery orchestration and verified successor authorization remain required. Source/tests and Linux acceptance for this increment are pending; no full RG006 acceptance is claimed. + +### LOG-060 — Shared artifact composition, review and CI correction (2026-11-24 UTC) + +- **Master:** After continuation, re-read PR21/feature/main heads and resumed the unchanged draft. Elapsed interruption time is not treated as measured agent effort. Published shared grammar/store reuse, manifest reader, developer tests and independent tests/CI integration in four separate commits. +- **Junior developer:** Supplied pure canonical epoch parsing/formatting and exact names, strict NDEBUG grammar checks and narrow store reuse patches. Root review restored original error-validation precedence before formatting. +- **Senior developer:** Implemented independent optional-manifest scanning, bounded private nested files, complete-candidate comparison, shared byte/participant accounting and metadata/presence revalidation. No writable store reopen, process action or epoch capability is produced. +- **Tester:** Caught pending-bootstrap comparison being mislabeled as a mismatch and the developer phase-fixture predicate advancing beyond its target. Verified all phases, corrupt/missing/pending intent retention, unsafe files/locks, mutations/appearance, shared bytes and exactly 16,384 dual-representation records plus overflow. New independent, extended developer and legacy-reader suites passed strict Clang/ASan/UBSan with fake EVP; this is behavior smoke only. +- **Scrum Master:** Independently reviewed the artifact contract and class boundaries; requested explicit absent-to-present manifest-store detection, now implemented and covered by developer/independent race fixtures. No process-exit/reset proof is claimed. +- **Master CI error:** Run45328285923 passed 52 CTest groups twice, 17 Python tests and 12 matching generated files, but a JavaScript replacement interpreted the selector suffix and dropped the shell quote. Sanitizer binaries built but their tests did not run; overall failure is not acceptance. Commit a3c4d7e fixed the selector, but run45330502633 exposed a second effect of the original replacement: duplicated workflow steps caused a duplicate-artifact conflict after all suites passed. Master rebuilt from the verified feature baseline and validated YAML, 21 unique named steps and all18 shell blocks; commit7fc9895e also scopes artifact names by run attempt. Both failed runs are excluded from overall acceptance. Production C++ is unchanged; full run45332588272 is pending. +- **Documentation:** LLD 9 records the namespace helper, optional-manifest API/caps and generic-store binding boundary. Current README/source pointers and context/story metadata are being synchronized. PRD 8 / SRD 5 / HLD 5 remain unchanged. +- **Next technical decision:** Selected bounded Docker Engine HTTP over the fixed local Unix socket, avoiding CLI subprocess/environment containment. The next controller will inspect/stop exact pending or observed targets; stop ACK, observed exit and epoch authorization remain distinct. No implementation or Docker qualification is claimed for that next slice. + +### LOG-061 — Artifact-layout Linux acceptance and integration review (2026-11-24 UTC) + +- **Master:** Run [45332588272](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45332588272) passed tested source `7fc9895e5f928ad1576d5b2119b79f4a717151e9` as merge ref `a93680850e190bb7e4d6a3c11f3dc4bb46a8051f` against feature base `9d9074601859c67541cd73343249ea11e8e09a95`. Both clean builds passed all 52 CTest groups, all 17 Python tests and all 12 generated files reproduced. All 38 selected sanitizer groups passed with real OpenSSL. Artifact upload and exact toolchain verification succeeded; the earlier failed runs remain excluded from acceptance. +- **Tester:** Independent phase, mismatch, pending/corrupt intent, file safety, race and aggregate-budget checks are included in the verified Linux run. Component acceptance covers diagnostic artifact composition only. +- **Documentation:** LLD9, layout/reader contracts, README, stories, sprint checkpoint and JSON handoff now reflect implemented boundaries and remaining work. Re-read main PRD8/SRD5, checked 130 relative links and the 14-story dependency graph. Historical status entries retain their actual past revisions. +- **Review/integration:** PR21 is ready for merge into the feature after documentation readback and a documentation-only comparison. PR13 remains unmerged; main is unchanged. Full RG006 and all release-level numerical gates remain open. +- **Next increment — Master/Junior/Tester:** Fixed local Unix HTTP transport selected; independent review identified connect-backlog ambiguity, final deadline/cancellation gating, allocation-error classification and throwing-clock exception safety. Developer corrections and independent fixtures are being prepared; Linux transport compilation/execution are not yet accepted. Darwin fallback compilation is not Linux fixture evidence. +- **Coordination:** Master narrowed the Senior's next delivery to internal controller/probe headers and the Junior's delivery to the concrete reviewed transport fixes before further implementation. No measured active-agent effort is inferred from elapsed design/CI time. + +### LOG-062 — Docker Unix transport increment opened (2026-11-24 UTC) + +- **Master:** PR21 merged into the integration feature as `e2d6aeaef0b9ac4e595eb6c50e26afda3e6ee314`; compared its tree with the tested source and confirmed only documentation followed. Main stayed at `71393cf11a0f8508cfb7e85b85538ccc22067f75`. PR13 remains the final unmerged promotion. Opened a separate transport branch from the verified feature head. +- **Junior developer:** Prepared the bounded HTTP parser and Linux AF_UNIX exchange. Review corrections cover EAGAIN connect ambiguity, a final success gate, safe handling of throwing clock dependencies, distinct allocation errors and bounded fake-peer cleanup. Source handoff and Linux verification are pending. +- **Tester:** Independently prepared parser grammar/boundary and allocation-failure suites, plus native socket exact-request/UID/replacement/cancel/deadline/concurrency/throwing-clock fixtures. Parser suites passed local strict Clang and ASan/UBSan. Darwin fallback compilation does not validate Linux fixture code; native compilation/execution remains pending. +- **Senior developer:** Preparing exact pending/observed container targets and a read-only recorded-process probe interface for the next inspect/stop component. Observer host-PID namespace qualification is distinct from a participant's private PID namespace. No container start, activation or successor capability is included. +- **Scope/coverage:** No Docker containers are launched by transport fixtures. Short-write injection and the exact post-EOF scheduling race are not yet exercised; source review must not be reported as fault-injection evidence. The transport does not interpret HTTP status as cessation or authorize reset. Full RG006 remains In progress. + +### LOG-063 — Native transport verification and socket fault completion (2026-11-25 UTC) + +- **Master:** Resumed the staged work after the previous agent turns ended on a usage-limit error. Re-read GitHub heads: PR22 remained draft at e785bc1; feature remained e2d6aea; main remained 71393cf. No elapsed interruption/CI time is counted as measured active-agent effort. +- **Linux evidence:** Initial [run45335005143](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45335005143) passed all 57 CTest groups in both clean builds, all 17 Python tests, reproduction of all 12 generated files, all 5 transport sanitizer groups and all 38 prior sanitizer groups, frozen toolchain verification and artifact upload. This source does not include the later socket-fault fixture. +- **Tester:** Supplied the independent GNU-link-wrapped connect/send/poll fixture: zero-byte versus one-byte EPIPE uncertainty, connect EAGAIN/no retry, fragmented writes with finite EINTR/EAGAIN, and shrinking 80/50/20 ms poll budgets before/after request bytes. Corrected stage-specific timeout recording so the normal initial write wait does not contaminate the after-send assertion. These are injected OS-boundary errors, not observations of spontaneous kernel backlog/signal failures. +- **Master review:** Tightened developer and independent fake-peer listeners to nonblocking; developer request reads and hold waits now have finite bounds. Made the internal transport library explicitly STATIC so only the fault executable receives GNU wrapping; production methods and public interfaces are unchanged. +- **Publication:** Published separate fault/test integration commit 3a5bc4e on PR22. Final [run45557524588](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45557524588) failed: both58-group clean builds, Python checks and generated-file reproduction passed; five transport sanitizer groups passed, but the new fault suite's injected poll-deadline cases failed under sanitizers. Remaining checks were skipped; overall acceptance is not passed. Master/Tester are investigating the compiled poll-call boundary without weakening assertions. +- **Senior/Junior/Tester:** Resumed controller, recorded-process probe and independent-controller QA work from existing staged files. The next component remains unpublished and unaccepted. Principal review identified hidden procfs entries as insufficient absence evidence; the selected read-only pidfd-open corroboration is being added. This is not a process-stop or successor capability. + +- **Scrum Master audit:** Independently caught terminal CI status and stale PR22 body/LOG062. Master updated the review description and published this checkpoint; initial57-group evidence remains scoped to its exact source. A temporary standalone symbol diagnostic is being used to identify sanitizer linkage; it is not acceptance evidence. + +- **Confirmed diagnosis:** Standalone Linux [diagnostic45558599588](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45558599588) showed the ordinary object references poll while its sanitized counterpart references __poll_chk. This diagnostic deliberately records failures and is not acceptance evidence. Tester added a typed fortified-call wrapper and Master added its target-only linker flag. The exact80/50/20ms deadline checks, fortification and ASan/UBSan remain enabled. Removed the temporary workflow after diagnosis; no production decision function changed. A complete corrected-source run is required. + +### LOG-064 — Unix transport accepted on Linux (2026-11-25 UTC) + +- **Master:** Corrected-source [run45558880696](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45558880696) passed source `195ed15d2535ff6b599412f009cfb897d2c971d4` as merge ref `0df8f68b7770196f0a7e2546b495697993227fc2` against feature e2d6aea. Both clean builds passed 58 CTest groups; all 17 Python tests and 12 generated files reproduced. All 44 selected sanitizer groups passed, including all 6 transport groups, with real OpenSSL. Frozen toolchain and artifact verification succeeded. +- **Tester:** Independent socket/error/deadline/uncertainty assertions now execute through both poll and fortified __poll_chk. No sanitizer or exact budget check was disabled; failed/diagnostic runs remain excluded. +- **Scrum Master:** Read-only audit caught stale pending status after the first 58-group failure. Master corrected the PR/log, preserved exact-source evidence and kept full RG006 open. +- **Design/handoff:** LLD10, README, current story/sprint checkpoint and JSON context reflect the internal transport ownership, limits and remaining controller/recovery scope. PRD8 / SRD5 / HLD5 are unchanged. Only documentation follows tested source; readback/relative-link/DAG checks precede feature integration. +- **Next increment:** PR23 is a separate review of exact Docker inspect/stop, read-only recorded-process evidence and native qualification. The first Linux build found a redundant move and an unchecked fixture write; Master removed the redundant move and releases the owned child by closing its pipe writer. Its acceptance remains pending. Main/PR13 stays unmerged. diff --git a/docs/SPRINT-PLAN.md b/docs/SPRINT-PLAN.md index 00c9de8..8a56a8e 100644 --- a/docs/SPRINT-PLAN.md +++ b/docs/SPRINT-PLAN.md @@ -1,8 +1,12 @@ # Agile Sprint Plan — DistributedRateGuard -**Date:** 2026-11-12 -**Status:** Planning only. This plan authorizes no implementation or test execution. -**Source of truth:** `main` — [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md), [stories](STORIES.md), and [JSON context blocks](context-blocks.json). +**Date:** 2026-11-25 +**Status:** RG-001 component verified; Sprint 0 deployment gate open. RG-002 component verified; RG-003-A and RG-004-A/B1/B2/B3 implementation inputs verified; full integration pending. Product Owner authorized development and testing on 2026-11-12. +**Source contracts:** PRD 8 / SRD 5 from `main`; HLD 5 / LLD 10 startup, artifact-layout, diagnostic-recovery and bounded-transport clarification and current implementation tracking on `feature/distributed-rateguard`. See [PRD](PRD.md), [SRD](SRD.md), [HLD](HLD.md), [LLD](LLD.md), [stories](STORIES.md), and [JSON context blocks](context-blocks.json). Final promotion to `main` remains PR #13. + +## Current delivery checkpoint — 2026-11-24 + +PRs #5–12 and #14–21 are merged into the integration feature. Artifact-layout [Linux verification](evidence/RG-006-F.md) passed. PR #22 supplies a bounded parser/Unix HTTP exchange; [Linux verification](evidence/RG-006-G.md) passed; the component remains separate from runtime acceptance. RG-006 is still In progress: real process control, authenticated activation, durable recovery/orphan reconciliation and successor authorization remain open. Full quota services, replay/evaluation and distributed-credit assurance are later dependent work. Historical progress entries below retain their original status. Only PR #13 promotes the feature to `main`, and remains unmerged. ## Team and control @@ -75,12 +79,36 @@ Implement credits only after Release A acceptance. Keep fixed-Q grants, same-seq ## Workflow, acceptance, and PR rules -- A story is **Ready** only when its dependencies are accepted, its source requirements/design are linked, failure behavior is explicit, and acceptance evidence is identified. +- A story is **Ready** only when its explicitly named input dependency contracts are verified, its source requirements/design are linked, failure behavior is explicit, and acceptance evidence is identified. - A story is **Done** only when code is reviewed, required tests have actually run, independent evidence is recorded against the commit and environment, and the story/context status is updated. Planned tests or documentation alone are not evidence. -- After the Product Owner’s proceed command, use a separate feature branch and PR for each coherent story or vertical slice, based on the current `main`. PRs include story IDs, PRD/SRD IDs, failure cases, evidence IDs, and observed results. +- After the Product Owner’s proceed command, use a separate feature branch and PR for each coherent story or vertical slice, based on current `main` or a verified prerequisite feature branch for a stacked PR. Stacked PRs target that feature branch so their diff remains independent; main merge requires Product Owner authorization. Rebase/retarget and rerun checks after the base changes. PRs include story IDs, PRD/SRD IDs, failure cases, evidence IDs, and observed results. - Senior Dev reviews implementation and concurrency; Tester independently reviews acceptance; Scrum Master tracks dependencies and status; Master reviews integration. Do not merge or mark releases complete without the Product Owner’s authorization. - Track work as **Ready → In Progress → Review → Acceptance → Done**, or **Blocked** with the unmet dependency/evidence stated. Do not pull blocked credit work forward to fill capacity. -## Current gates and explicit wait +## Current gates and work log + +RG-001 API/helpers and the primary hosted Ubuntu package build are verified in [PR #5](https://github.com/kshiteesh28/DistributedRateGuard/pull/5); this is component acceptance. **Sprint 0 remains open for the actual Docker target, image digest and topology evidence**, owned by Master/Senior Dev. The optional gRPC source-build experiment remains unverified. + +RG-002 policy/arithmetic is implemented on a stacked branch in [PR #6](https://github.com/kshiteesh28/DistributedRateGuard/pull/6); its final cap/crypto extensions passed both clean builds in run 43353832066 and independent Tester acceptance. See [RG-002 evidence](evidence/RG-002.md). RG-003-A clock component passed Linux/sanitizer checks and independent review; full RG-003 integration remains pending. Pure foundations may proceed; enforcement cannot activate until its runtime prerequisites pass. RG-004-A TLS/UTC compatibility is independently accepted in [PR #9](https://github.com/kshiteesh28/DistributedRateGuard/pull/9); [run 43980308204](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43980308204) passed normal/clean/sanitizer checks. Constrained Docker clock observations matched, but service topology and the actual target deployment gate remain open. Typed certificate-registry input B1 is verified separately below. Production manifest binding, authorization, expiry wrappers, full-system tests, benchmarks, model checking, witness durability and process fencing remain pending. + +The [per-agent scrum work log](SCRUM-WORK-LOG.md) records handoffs, findings, failures, corrections and exact evidence. Earlier agent-minute estimates remain estimates; actual historical effort was not recorded. No release completion or main merge is claimed. + +## Named dependency contracts + +Implementation readiness depends on verified input deliverables rather than completion of their entire parent stories. Each contract identifies interface, tested revision/evidence, permitted consumers and excluded guarantees. Component acceptance permits dependent development only; system activation, story completion and release acceptance still require all applicable integration/product gates. Changes to a consumed contract require affected consumers to be reviewed and retested. + +**RG-003-A** supplies IClock/LinuxMonotonicClock at `2d55c6e032ae75947f045ac76ffa383b2b1dd9d8`, [run 43355987772](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43355987772). RG-006/007/008 may consume its verified startup identity, initial sample, serialized sampling and sticky failure behavior. **RG-003-B** (RG-006) still must prove every participant's topology; **RG-003-C** (RG-007/008) must complete actual commit/deadline mapping; **RG-003-D** is the Release A strict provenance evidence gate, delivered in RG-011A using RG-005 completeness and RG-006/007/008 runtime provenance/commit inputs. Missing, inconsistent or uncertain evidence must produce UNKNOWN and block a strict safety PASS before RG-008 acceptance and Release A completion. RG-013 extends this guard for credit/formal checks in C; it cannot postpone the A obligation. Full RG-003 remains incomplete until its applicable A integrations close. This removes a scheduling dependency cycle without changing any acceptance criterion or release gate. + + +**RG-004-A** supplies the pin-verifier compatibility and trusted UTC primitive at `f5b3e975225c869e4a9638af57ab9f7c8a06e546`, run 43980308204. It permits registry/authorization development; it does not permit enforcement activation or close RG-004 AC01–03. Verified RG-004-B1 supplies immutable certificate metadata; RG-006 owns manifest/topology/epoch fencing; RG-008/009 own live commit/forward guard integration. SEC-01–11 revision 2 remains the selected default contract. The 4,980-minute expanded estimate overlaps other stories and is not adopted; neither it nor the historical 720-minute estimate is measured actual effort. + +**Dependency correction (2026-11-16):** RG-006 consumes named verified RG-004-A/B1 security inputs rather than full RG-004 Done. Full RG-004-AC02 consumes RG-006 manifest/fencing evidence and AC03 consumes RG-005 real export/privacy evidence. This removes the implicit story-level cycle; all integration and activation gates remain required. RG-004-B1 is typed public-certificate validation and an immutable metadata snapshot, with no manifest format, authorization or service readiness claim. Its 64 KiB/certificate and 64 MiB aggregate PEM caps are implementation bounds; the 10,000 principal cap comes from policy-v1, not SRD D6's tenant cap. + + +**RG-004-B1** passed [run 44016873892](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44016873892) at `6366df84903049fde3fd92243b3aa7bd06c43986`; [PR #10](https://github.com/kshiteesh28/DistributedRateGuard/pull/10) is ready and unmerged. [Independent evidence](evidence/RG-004-B1.md) covers typed public-certificate validation and owned metadata only. RG-006 may consume it for manifest development; B2 runtime authorization and all lifecycle/service activation gates remain open. + + +**RG-004-B2** peer authentication/authorization passed run 44022842950 at `9d14bb74bd937401471e96e039f651c17c226c43`; QA and Senior accepted the scoped input. [PR #11](https://github.com/kshiteesh28/DistributedRateGuard/pull/11) is ready and unmerged after final run 44023785687 passed at `20210d5fbabcd891dbbb20ab89eca26f3a73a1db`. [B2 evidence](evidence/RG-004-B2.md) covers actual TLS dispatch/spy/expiry and two isolated unsafe variants, not quota/commit/forward/fencing or reconnect/resumption. RG-006 retains A/B1 named prerequisites; B2 does not create a new lifecycle cycle. Remaining integration and full-story gates are unchanged. + -The design is specified, but implementation, tests, benchmarks, model checking, shared-clock proof, witness durability evidence, process-fencing evidence, and certificate fixtures are not claimed as completed. The actual target build environment and local Git checkout still need verification. This document and its planning metadata may be committed now; **all development and test work waits for the Product Owner’s explicit proceed command.** +**RG-004-B3** passed [run 44128491936](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44128491936) at `0a1b37b6147adb39c885459253d59c8561c9c5cc`; [PR #12](https://github.com/kshiteesh28/DistributedRateGuard/pull/12) is ready and unmerged. [Evidence](evidence/RG-004-B3.md) covers the sealed client/guards, independent mTLS/mutant and test-only SDK resumption qualification. Production caching remains disabled; actual service commit/forward/fencing and full RG004 ACs stay open. RG005 is the next ready component from RG001; freeze run-wide budget/producer/encoding decisions before implementation. diff --git a/docs/STORIES.md b/docs/STORIES.md index c59b0c2..cd1795d 100644 --- a/docs/STORIES.md +++ b/docs/STORIES.md @@ -1,12 +1,12 @@ # Implementation stories -**Date:** 2026-11-12 · **Status:** Planned; no implementation or acceptance results claimed. +**Updated:** 2026-11-25 · **Status:** Foundation/security/history/lifecycle components are integrated on `feature/distributed-rateguard`; full runtime story acceptance remains pending. PR #13 is the final promotion to `main`. Earlier per-increment PR notes below record historical states. Machine-readable handoff: [context blocks](context-blocks.json). Follow dependency IDs rather than numeric order. Release labels indicate the deliverable; independent oracle work precedes dependent correctness checks even when delivered with release B. ## RG-001 -**Freeze wire contracts and build manifest** · Release A · Planned +**Freeze wire contracts and build manifest** · Release A · Component accepted; merged to feature Dependencies: none. @@ -16,9 +16,9 @@ Proposed files: `proto/rateguard/v1/admission.proto`, `proto/rateguard/v1/author Classes: AdmissionService, AuthorityService. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-005, PRD-021, FR-005, FR-020. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-005, PRD-021, FR-005, FR-020. -Acceptance criteria (not run): +Acceptance criteria: component PASS; see [RG-001 evidence](evidence/RG-001.md). Product/service integration remains assigned to later stories. - **RG-001-AC01** — Golden protobuf/encoding fixtures reject unspecified enums, invalid widths and malformed payloads without quota mutation. Evidence: AT-04, AT-06. - **RG-001-AC02** — Build manifest records exact tool/compiler/library versions and reproducible build commands; no runtime metric is claimed. Evidence: AT-13, AT-20. @@ -26,7 +26,7 @@ Acceptance criteria (not run): ## RG-002 -**Implement immutable policy and checked arithmetic** · Release A · Planned +**Implement immutable policy and checked arithmetic** · Release A · Component accepted; merged to feature Dependencies: RG-001. @@ -36,9 +36,9 @@ Proposed files: `src/policy/policy_snapshot.h`, `src/policy/policy_loader.h`, `s Classes: PolicySnapshot, PolicyLoader, CanonicalPolicyCodec, BucketMath. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-001, PRD-002, PRD-003, FR-001, FR-002, FR-003. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-001, PRD-002, PRD-003, FR-001, FR-002, FR-003. -Acceptance criteria (not run): +Acceptance criteria: component PASS after corrected [run 43353832066](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43353832066) and independent Tester review. See [RG-002 evidence](evidence/RG-002.md) and [scrum log](SCRUM-WORK-LOG.md). Runtime quota/identity/clock integration remains separately gated. - **RG-002-AC01** — Canonical byte fixtures produce identical digests regardless of input map order; duplicate IDs and invalid policy bounds reject. Evidence: AT-01, AT-04. - **RG-002-AC02** — At available=c*S admit; at c*S-1 limit. Maximum bounds, saturation, fractions and overflow fixtures agree with independent arithmetic. Evidence: AT-02, AT-03. @@ -46,7 +46,7 @@ Acceptance criteria (not run): ## RG-003 -**Implement shared clock provenance and commit timing** · Release A · Planned +**Implement shared clock provenance and commit timing** · Release A · Component verified; integration pending Dependencies: RG-001. @@ -56,9 +56,18 @@ Proposed files: `src/platform/clock.h`, `src/platform/clock_linux.h`. Classes: IClock, LinuxMonotonicClock. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-002, PRD-024, FR-001, FR-017. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-002, PRD-024, FR-001, FR-017. -Acceptance criteria (not run): +Component evidence: [RG-003](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-003-clock-provenance/docs/evidence/RG-003.md), head `2d55c6e032ae75947f045ac76ffa383b2b1dd9d8`, run 43355987772, independent acceptance. Full story is not Done. + +| Deliverable | Status / owner | +| --- | --- | +| RG-003-A clock API/startup/sampling | Verified input for RG-006/007/008 development | +| RG-003-B participant topology | Pending RG-006; Master/Senior Dev | +| RG-003-C actual commit/deadline mapping | Pending RG-007/008; Senior Dev/Tester; AC02 | +| RG-003-D strict UNKNOWN evidence gate | Pending RG-011A with RG-005 completeness/runtime inputs; before RG-008 acceptance; AC03. RG-013 adds C credit/formal extensions | + +Acceptance criteria (unchanged; disposition above): - **RG-003-AC01** — Wrong namespace/boot/clock ID prevents readiness; backwards time or syscall failure stops transitions. Evidence: AT-01, AT-17. - **RG-003-AC02** — Clock samples and ordered state transitions have an auditable linearization mapping; late responses cannot move timestamps. Evidence: AT-02, AT-07. @@ -66,19 +75,27 @@ Acceptance criteria (not run): ## RG-004 -**Implement mTLS identity and operation authorization** · Release A · Planned +**Implement mTLS identity and operation authorization** · Release A · RG-004-A/B1/B2/B3 implementation inputs accepted; full story in progress Dependencies: RG-001, RG-002. Validate role/SAN/EKU/expiry every RPC including reused channels. Bind peer to tenant/operation and derive cost from policy. Use LLD sections 16 and 17 for exact sequencing and class ownership; evidence must be independent of production decision logic. -Proposed files: `src/security/peer_authenticator.h`, `src/security/authorization.h`. +Implemented component paths on review branches: `include/rateguard/security/{peer_authenticator,authorization_resolver,client_call_guard,pinned_peer_rpc_client}.h` and corresponding `src/security/*.cpp`. Service/lifecycle integration remains pending. -Classes: PeerAuthenticator, AuthorizationResolver. +Classes: PeerAuthenticator, AuthorizationResolver, ClientCallGuard, PinnedPeerRpcClient. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-008, PRD-024, FR-003. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-008, PRD-024, FR-003. -Acceptance criteria (not run): +Compatibility input **RG-004-A** is independently accepted in [PR #9](https://github.com/kshiteesh28/DistributedRateGuard/pull/9), head `f5b3e975225c869e4a9638af57ab9f7c8a06e546`, [run 43980308204](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43980308204). Exact URI/leaf pin verification, real TLS rejection controls, compiled bypass detection and trusted UTC primitive passed. Docker observations matched under restricted permissions; [the record](evidence/RG-004-A/docker-time-43980308204.json) is capability evidence only. This initial compatibility slice alone does not provide registry, authorization or connection-expiry guards; B1/B2/B3 supply the scoped inputs below. Manifest binding and epoch/service integration remain open. All full-story acceptance criteria below remain unverified. + +Registry input **RG-004-B1** is independently accepted in [PR #10](https://github.com/kshiteesh28/DistributedRateGuard/pull/10), head `6366df84903049fde3fd92243b3aa7bd06c43986`, [run 44016873892](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44016873892). Both 21-test builds and targeted sanitizers passed; the independent suite detects a separately compiled root-pin bypass. [Evidence](evidence/RG-004-B1.md). This permits typed-registry/manifest development, not service activation or full authentication acceptance. + +Peer/policy input **RG-004-B2** passed [run 44022842950](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44022842950) and independent QA/senior review: actual TLS handler/spy/dispatch-expiry and isolated permission/pin controls, 25 tests twice and 9 security sanitizer checks. [Evidence](evidence/RG-004-B2.md). [PR #11](https://github.com/kshiteesh28/DistributedRateGuard/pull/11) is ready and unmerged after final run 44023785687 at `20210d5fbabcd891dbbb20ab89eca26f3a73a1db`; no implementation has been merged. Actual commit/forward, manifest/fencing and full service acceptance remain open; B3 supplies the client primitives described next. + +Client input **RG-004-B3** passed [run 44128491936](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44128491936) at `0a1b37b6147adb39c885459253d59c8561c9c5cc`; [PR #12](https://github.com/kshiteesh28/DistributedRateGuard/pull/12) is ready and unmerged. [Evidence](evidence/RG-004-B3.md) covers the sealed typed client, current root/own-client/server validity guards, pre-forward time/identity primitive, independent mTLS/mutation checks and native SDK resumption qualification. Production caching remains disabled. This is not actual ALLOW/forwarding, epoch lifecycle, provisioning or full-story acceptance. + +Acceptance criteria (full integration not run): - **RG-004-AC01** — Wrong principal/role/SAN/EKU and spoofed overrides reject without quota allocation. Evidence: AT-04. - **RG-004-AC02** — Expired certificate on an existing connection is rejected; fenced new epoch is required for trust rotation. Evidence: AT-04, AT-14. @@ -86,19 +103,19 @@ Acceptance criteria (not run): ## RG-005 -**Implement bounded events and incomplete-history accounting** · Release A · Planned +**Implement bounded events and incomplete-history accounting** · Release A · In progress Dependencies: RG-001. Reserve slots before commit. Published checksummed records and producer seals distinguish complete evidence from crash gaps. Run-wide cap is 1 GiB. Use LLD sections 16 and 17 for exact sequencing and class ownership; evidence must be independent of production decision logic. -Proposed files: `src/events/event_recorder.h`, `src/events/history_exporter.h`. +Component files include `src/events/` and `tools/history/`. See [RG-005 evidence](evidence/RG-005.md) for exact scope and test results. Classes: EventRecorder, HistoryExporter. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-009, PRD-015, FR-009, FR-010. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-009, PRD-015, FR-009, FR-010. -Acceptance criteria (not run): +Component verification passed in Linux run 45126587562. Full acceptance remains pending service/supervisor wiring and the RG-011A provenance gate. - **RG-005-AC01** — Reserved but unpublished slots, gaps, checksum loss and missing producer seals mark a run incomplete/UNKNOWN. Evidence: AT-10, AT-11. - **RG-005-AC02** — Cap exhaustion stops correctness traffic; no event is silently dropped and no debit is refunded. Evidence: AT-11. @@ -106,17 +123,21 @@ Acceptance criteria (not run): ## RG-006 -**Implement supervisor lifecycle and positive fencing** · Release A · Planned +**Implement supervisor lifecycle and positive fencing** · Release A · In progress + +Local [gate](evidence/RG-006-A.md), [manifest](evidence/RG-006-B.md) and [runtime ownership](evidence/RG-006-C.md) components are verified on the integration feature. [Bootstrap inventory/store](evidence/RG-006-D.md), [recovery reader](evidence/RG-006-E.md) and [artifact composition](evidence/RG-006-F.md) components are verified; full runtime acceptance is tracked separately; the story remains In progress. + +Implemented component paths: `src/supervisor/epoch_gate.h`, `manifest_codec.{h,cpp}`, `manifest_store.{h,cpp}`, `runtime_owner.{h,cpp}`, `bootstrap_inventory.{h,cpp}` and `bootstrap_store.{h,cpp}` (all under `src/supervisor/`). New classes: RuntimeOwner, InitialEpochClaim, BootstrapInventory and BootstrapStore; see LLD 10 §21. The shared [artifact layout](contracts/epoch-artifact-layout-v1.md) and [manifest diagnostics](evidence/RG-006-F.md) extend the reader with a strictly validated optional manifest store. The diagnostic [recovery reader](evidence/RG-006-E.md) is a separate component; it preserves known pending-container identities and incomplete evidence without granting recovery authority. The [bounded Unix HTTP transport](evidence/RG-006-G.md) supplies an internal parser/socket exchange; it does not interpret container exit or perform process control. Concrete Docker control, authenticated activation and successor-epoch fencing remain pending. -Dependencies: RG-002, RG-003, RG-004, RG-005. +Dependencies: RG-002, RG-003-A, RG-005 and named verified RG-004-A/B1 inputs. B1 supplies typed certificate metadata only; RG-006 does not require full RG-004 completion. Full RG-004-AC02 later consumes RG-006 manifest/fencing evidence. This separates development inputs from final integration acceptance without waiving either gate. Use ACTIVE/DRAINING/CLOSED; preserve exact process/container inventory. Supervisor failure never adopts a running old epoch. Use LLD sections 16 and 17 for exact sequencing and class ownership; evidence must be independent of production decision logic. -Proposed files: `src/supervisor/epoch_gate.h`, `src/supervisor/manifest_store.h`, `src/supervisor/process_controller.h`, `src/supervisor/epoch_supervisor.h`, `src/supervisor/docker_process_controller.h`. +Remaining proposed integration files: `src/supervisor/process_controller.h`, `src/supervisor/epoch_supervisor.h` and `src/supervisor/docker_process_controller.h`. The current stop/inspect `IProcessController` interface is declared in `epoch_gate.h`; the launch/recovery integration remains proposed. The EpochSupervisor-owned diagnostic reader is implemented separately; complete artifact-layout/runtime reconciliation and recovery orchestration remain pending. Classes: EpochGate, ManifestStore, IProcessController, EpochSupervisor, DockerProcessController. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-007, PRD-024, PRD-025, FR-001, FR-007, FR-008, FR-022. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-007, PRD-024, PRD-025, FR-001, FR-007, FR-008, FR-022. Acceptance criteria (not run): @@ -136,7 +157,7 @@ Proposed files: `src/authority/witness_port.h`, `src/supervisor/witness_state.h` Classes: IStateWitness, WitnessStateMachine, JournalWriter, LocalStateWitnessClient, WitnessServer. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-007, PRD-015, PRD-024, FR-008, FR-010. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-007, PRD-015, PRD-024, FR-008, FR-010. Acceptance criteria (not run): @@ -156,7 +177,7 @@ Proposed files: `tools/replay/reference_model.h`, `tools/replay/main.cpp`. Classes: ReplayModel. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-006, FR-011, FR-012. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-006, FR-011, FR-012. Acceptance criteria (not run): @@ -176,7 +197,7 @@ Proposed files: `src/authority/tenant_ledger.h`, `src/authority/tenant_reservati Classes: TenantLedger, TenantReservation, AuthorityEngine, AuthorityService, AdmissionService, GrpcAuthorityClient. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-001, PRD-002, PRD-003, PRD-005, FR-002, FR-005, FR-006. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-001, PRD-002, PRD-003, PRD-005, FR-002, FR-005, FR-006. Acceptance criteria (not run): @@ -196,7 +217,7 @@ Proposed files: `adapter/forward_attempt.h`, `adapter/sample_adapter.h`. Classes: ForwardAttempt, SampleAdapter. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-004, PRD-005, FR-004, FR-006. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-004, PRD-005, FR-004, FR-006. Acceptance criteria (not run): @@ -216,7 +237,7 @@ Proposed files: `src/credits/tenant_credits.h`, `src/credits/credit_manager.h`, Classes: ReplicaTenantCredits, CreditManager, IAuthorityClient. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-016, PRD-017, PRD-018, PRD-019, FR-014, FR-015, FR-016, FR-017, FR-018. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-016, PRD-017, PRD-018, PRD-019, FR-014, FR-015, FR-016, FR-017, FR-018. Acceptance criteria (not run): @@ -236,7 +257,7 @@ Proposed files: `tools/loadgen/trace_generator.h`, `tools/loadgen/runner.h`, `to Classes: TraceGenerator, BenchmarkRunner. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-010, PRD-011, PRD-012, PRD-020, PRD-022, PRD-026, FR-013, FR-019, FR-023, NFR-002, NFR-003, NFR-004, NFR-005, NFR-006, NFR-007, NFR-009. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-010, PRD-011, PRD-012, PRD-020, PRD-022, PRD-026, FR-013, FR-019, FR-023, NFR-002, NFR-003, NFR-004, NFR-005, NFR-006, NFR-007, NFR-009. Acceptance criteria (not run): @@ -256,7 +277,7 @@ Proposed files: `model/runner`, `model/RateGuard.tla`, `tools/history_checker/ch Classes: HistoryChecker, ModelHarness. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-018, PRD-021, PRD-023, FR-017, FR-020, FR-021. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-018, PRD-021, PRD-023, FR-017, FR-020, FR-021. Acceptance criteria (not run): @@ -276,7 +297,7 @@ Proposed files: `docs/releases/manifest.json`, `docs/releases/requirements-evide Classes: release artifacts and runner integration. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 4](HLD.md), [LLD 5](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-010, PRD-011, PRD-012, PRD-021, PRD-023, FR-013, FR-020, FR-021, NFR-001, NFR-006. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 10](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-010, PRD-011, PRD-012, PRD-021, PRD-023, FR-013, FR-020, FR-021, NFR-001, NFR-006. Acceptance criteria (not run): @@ -287,4 +308,4 @@ Acceptance criteria (not run): ## Readiness clarification — 2026-11-12 -The full replay command/report remains a Release B deliverable. Its independent strict decision oracle and golden fixtures are required earlier as test support for Release A; this does not move replay product scope into A. The performance p99 population and target-build lock are defined in PRD 8 / SRD 5 / LLD 5. No story is implemented or accepted by this clarification. +The full replay command/report remains a Release B deliverable. Its independent strict decision oracle and golden fixtures are required earlier as test support for Release A; this does not move replay product scope into A. The performance p99 population and target-build lock are defined in PRD 8 / SRD 5 / LLD 9. No story is implemented or accepted by this clarification. diff --git a/docs/build.md b/docs/build.md new file mode 100644 index 0000000..e99d221 --- /dev/null +++ b/docs/build.md @@ -0,0 +1,39 @@ +# Building the foundation components + +The default Linux contract build uses the primary toolchain versions in [build-lock.json](../build-lock.json). The [acceptance evidence](evidence/RG-001.md) records passing CI, its tested revision and limitations. These components do not implement quota enforcement. [RG-002 evidence](evidence/RG-002.md) adds immutable policy, canonical digest and checked arithmetic verification. + +## Recorded Ubuntu environment + +Use Ubuntu 24.04 x86_64, CMake 3.31.6 and Ninja 1.11.1. Install the exact primary Protobuf/gRPC/OpenSSL/zlib/nlohmann-json package versions from the lock: + +```sh +sudo apt-get update +python3 - <<'PY' +import json, subprocess +lock = json.load(open("build-lock.json")) +packages = [name + "=" + version for name, version in lock["dependencies"]["package_versions"].items()] +subprocess.run(["sudo", "apt-get", "install", "--yes", "python3", *packages], check=True) +PY +python3 -m unittest discover -s tools/tests -v +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON +cmake --build build --parallel 2 +ctest --test-dir build --output-on-failure +python3 tools/capture_build_manifest.py --source-root . --build-dir build --codegen-tools build/codegen-tools.json --output build/build-manifest.json --build-result passed +python3 tools/verify_build_manifest.py --lock build-lock.json --manifest build/build-manifest.json +``` + +Pass `--build-result passed` only after build and tests succeed. The verifier rejects missing values, candidate/empty locks, package/compiler/tool/OS/architecture drift, and an observed project standard other than C++20. It uses actual compiler commands, not a declared standard alone. A different environment is unverified; record and review a deliberate lock refresh instead of silently updating versions. + +## Clean reproduction + +Repeat configure/build/CTest into `build-clean` with the same arguments. CI compares hashes for all 12 generated protobuf/gRPC source/header files between clean directories; both test suites must pass. This demonstrates repeatability of the declared component and generated bytes, not bit-for-bit binary or full transitive-OS reproducibility. Artifacts retain the observed runner image/version and package data; [a versioned manifest snapshot](evidence/RG-001/manifest-43327798021.json) persists after CI artifact expiry. + +## Transport and schema scope + +The tests cover the versioned wire layout, generated parsing/serialization, shape/configuration validation, status/commitment mapping and channel policy. The synthetic loopback retry fixture proves four calls with retries enabled versus one with enforcement arguments. Runtime clients must use `CreateEnforcementChannel`; the helper does not supply authentication or application retry logic. See the [upstream gRPC channel argument contract](https://github.com/grpc/grpc/blob/v1.51.1/include/grpc/impl/codegen/grpc_types.h) for retry/hedging semantics. + +Request helper tests are not production RPC/state integration. The gRPC receive-size limit, authenticated tenant resolution, real client uncertainty handling and quota atomicity remain in their assigned later stories. RG-002 adds the frozen [policy-v1](contracts/policy-v1.md) loader/encoder, independent Python byte/hash oracle, finite startup caps and arithmetic mutation checks. OpenSSL 3 provider APIs supply the digest; actual CA fingerprint matching is RG-004. `ctest` runs both C++ policy checks and the production-driver Python integration suite. + +## Optional source dependency experiment + +`-DRATEGUARD_FETCH_GRPC=ON` retains the pinned gRPC source/submodule build as a separate experiment. It is not covered by the Ubuntu package lock. The initial all-target build exceeded the hosted job's 45-minute budget before product tests; do not claim source-lane compatibility or use it as evidence for the verified package lane. diff --git a/docs/context-blocks.json b/docs/context-blocks.json index 19a145c..5aa0af6 100644 --- a/docs/context-blocks.json +++ b/docs/context-blocks.json @@ -1,32 +1,34 @@ { "schema_version": "1.0", - "generated_date": "2026-11-12", + "generated_date": "2026-11-25", "recheck_mutable_state": true, "objective": "Implement DistributedRateGuard releases A/B/C from the reviewed contracts, with independent acceptance evidence for every story.", "repository": { "url": "https://github.com/kshiteesh28/DistributedRateGuard", "target_branch": "main", - "review_branch": "main", + "review_branch": "feature/distributed-rateguard", "review_base_commit": "5df15b6312edae2a4e6b50808c051d7b4a96e667", "documentation_snapshot_before_class_and_story_additions": "5a6c8a1b6bc2338bb601b91ee9b0f504ff5e86ad", "local_path_hint": "/Users/kshiteesh/Developer/rateguard", "local_checkout_verified": false, - "current_source_branch": "main", + "current_source_branch": "feature/distributed-rateguard", "last_review_branch": "docs/spec-contract-closure-v1", - "local_checkout_note": "Observed path contains documentation only; no .git metadata, source tree, or build output was present." + "local_checkout_note": "Observed path contains documentation only; no .git metadata, source tree, or build output was present.", + "implementation_branch": "feature/distributed-rateguard", + "implementation_base_branch": "main" }, "document_revisions": { "PRD": 8, "SRD": 5, - "HLD": 4, - "LLD": 5 + "HLD": 5, + "LLD": 10 }, "state": { - "documents": "reviewed_specifications_revision_8_5_4_5", - "implementation": "not_created_or_verified", + "documents": "reviewed_specifications_revision_8_5_5_10", + "implementation": "rg006_unix_http_transport_component_verified_runtime_pending", "benchmarks": "not_run", "model_checking": "not_run", - "note": "Implementation plan and active-minute estimates are published on main. Await the Product Owner's explicit proceed command before development or test execution. The local path remains documentation-only and is not a verified Git checkout." + "note": "Foundation and security components are integrated on feature/distributed-rateguard. PR #13 is the pending promotion to main." }, "constraints": [ "Single Docker Linux VM/shared verified CLOCK_MONOTONIC provenance.", @@ -56,42 +58,262 @@ } ], "not_run": [ - "Generated implementation compilation/tests", "Real authority/replica fault injection", "Release benchmarks", "TLA/model checker execution" ], - "documentation_changes": [ + "previous_spec_merge_documentation_checks": [ + "Source revisions read from GitHub main before changes.", + "Markdown table widths and code-fence balance checked.", + "JSON parse, unique story IDs, dependency DAG, acceptance IDs and story/source link targets checked before merge." + ], + "latest_rg001": { + "evidence": "docs/evidence/RG-001.md", + "run": 43328571076, + "status": "component_verified_review_pending", + "remaining": "Docker target/image-digest and runtime integration gates are not satisfied by hosted package tests", + "pull_request": 5, + "pull_request_status": "merged_to_feature" + }, + "latest_rg002": { + "status": "component_verified_independent_acceptance_passed", + "passed_run": 43353832066, + "tested_head": "7640975031aee2af2ee7ae855ce88b76115f1569", + "merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "evidence": "docs/evidence/RG-002.md", + "scope": "Pure policy/arithmetic; no quota service, runtime certificate or clock claims", + "pull_request": 6, + "pull_request_status": "merged_to_feature" + }, + "historical_spec_merge_documentation_changes": [ "PRD 8 / SRD 5 / HLD 4 / LLD 5 now use one p99 population and timeout/cancellation rule.", "README and spec-to-code status text point to the current main-branch document bundle.", "RG-011 distinguishes Release A oracle/golden-fixture prerequisite from Release B replay CLI delivery.", "Build-lock versions remain unclaimed until selected and reproduced on the actual target Linux environment." ], - "previous_spec_merge_documentation_checks": [ - "Source revisions read from GitHub main before changes.", - "Markdown table widths and code-fence balance checked.", - "JSON parse, unique story IDs, dependency DAG, acceptance IDs and story/source link targets checked before merge." - ] + "latest_rg003": { + "status": "component_verified_independent_acceptance_passed", + "run": 43355987772, + "tested_head": "2d55c6e032ae75947f045ac76ffa383b2b1dd9d8", + "evidence": "docs/evidence/RG-003.md", + "excluded": "Participant topology, actual commit/deadline mapping, Release A strict UNKNOWN gate in RG-011A/005 and C extension in RG-013", + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-003-clock-provenance/docs/evidence/RG-003.md", + "final_documentation_head": "f656648c884ce9bbe6fcb917566898a2f01b4c0e", + "final_documentation_run": 43358083253, + "pull_request_status": "merged_to_feature", + "pull_request": 8 + }, + "latest_rg004": { + "status": "compatibility_input_independently_accepted", + "run": 43980308204, + "tested_head": "f5b3e975225c869e4a9638af57ab9f7c8a06e546", + "merge_ref": "a24c820d98aea8916a23c49d6129a4b88d14504b", + "pull_request": 9, + "pull_request_status": "merged_to_feature", + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-security-probes/docs/evidence/RG-004-A.md", + "docker_observation_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/evidence/RG-004-A/docker-time-43980308204.json", + "docker_result": "OBSERVATIONS_MATCHED_capability_only", + "scope": "Exact leaf pin/URI TLS compatibility, independent verifier-bypass detection, trusted UTC primitive; not production registry/authorization, connection-expiry or epoch fencing" + }, + "latest_rg004_b1": { + "id": "RG-004-B1", + "status": "verified_review_ready", + "branch": "feature/RG-004-certificate-registry", + "head": "6366df84903049fde3fd92243b3aa7bd06c43986", + "pull_request": 10, + "run": 44016873892, + "contract_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-certificate-registry/docs/contracts/certificate-registry-v1.md", + "scope": "Policy-bound typed certificate validation and immutable metadata only; no runtime authorization/readiness/fencing proof", + "merge_ref": "e03a5291889bb7fc9078bd5bda6b822657ea3cc7", + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/evidence/RG-004-B1.md", + "pull_request_status": "merged_to_feature" + }, + "latest_rg004_b2": { + "id": "RG-004-B2", + "status": "verified_review_ready", + "branch": "feature/RG-004-peer-authorization", + "head": "20210d5fbabcd891dbbb20ab89eca26f3a73a1db", + "pull_request": 11, + "run": 44023785687, + "contract_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-peer-authorization/docs/contracts/peer-authorization-v1.md", + "verified_implementation_head": "9d14bb74bd937401471e96e039f651c17c226c43", + "documentation_run": 44023785687, + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/evidence/RG-004-B2.md", + "scope": "Peer identity and policy authorization with actual TLS fixture/dispatch expiry; no quota, commit, forwarding, epoch fencing or reconnect/resumption proof", + "implementation_run": 44022842950, + "merge_ref": "31084e66433126412a5e22457c13fde1f34350b1", + "pull_request_status": "merged_to_feature", + "public_interfaces": [ + "PeerAuthenticator::Authenticate", + "AuthorizationResolver::Create", + "AuthorizationResolver::Resolve" + ], + "acceptance": "independent_QA_and_senior_review_passed", + "full_story_done": false + }, + "latest_rg004_b3": { + "id": "RG-004-B3", + "status": "verified_review_ready", + "branch": "feature/RG-004-client-guards", + "head": "0a1b37b6147adb39c885459253d59c8561c9c5cc", + "pull_request": 12, + "run": 44128491936, + "merge_ref": "1fe328849653f92486fa69695e649a6049e961b0", + "contract_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-client-guards/docs/contracts/pinned-client-v1.md", + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/evidence/RG-004-B3.md", + "scope": "Client trust guard/sealed typed calls and native SDK session qualification only; production caching disabled; no actual commit/forward/fencing", + "acceptance": "independent_QA_and_senior_review_passed", + "session_qualification": { + "status": "qualified_test_fixture_only", + "actual_resumed": true, + "cache_capacity": 1, + "new_transport": true, + "client_leaf_pin": true, + "server_leaf_pin": true, + "client_verifier_delta": 1, + "server_verifier_delta": 1, + "production_session_cache_enabled": false + }, + "full_story_done": false, + "pull_request_status": "merged_to_feature" + }, + "latest_rg005": { + "status": "component_verified_runtime_pending", + "tested_head": "da19ea21800c303acae4646d6159f67a1607a3b1", + "run": 45126587562, + "evidence": "docs/evidence/RG-005.md", + "pull_request": 14, + "full_story_done": false, + "pull_request_status": "merged_to_feature" + }, + "latest_rg005_inspector": { + "status": "component_verified_runtime_pending", + "tested_head": "e0c9b5540349a166c5797e0a70c06a02b88290f9", + "run": 45129476268, + "evidence": "docs/evidence/RG-005-inspector.md", + "pull_request": 15, + "full_story_done": false, + "pull_request_status": "merged_to_feature" + }, + "latest_rg006": { + "status": "local_gate_verified_runtime_pending", + "tested_head": "6da5d90ce70be41cf9780a64b7bc360492a8d4ab", + "run": 45130958093, + "evidence": "docs/evidence/RG-006-A.md", + "pull_request": 16, + "full_story_done": false, + "pull_request_status": "merged_to_feature" + }, + "latest_rg006_manifest": { + "status": "local_persistence_verified_runtime_pending", + "tested_head": "ba2d14731b3f2e9e996049e67b9e4d702a2218d8", + "run": 45207019201, + "evidence": "docs/evidence/RG-006-B.md", + "pull_request": 17, + "full_story_done": false, + "pull_request_status": "merged_to_feature" + }, + "current_design_checks": [ + "HLD 5 / LLD 6 clarify durable stopped-container intents, non-serving bootstrap and observed process-identity persistence before activation; PRD 8 / SRD 5 unchanged.", + "Historical documentation-check entries retain the revisions actually checked at that time.", + "LLD 7 records implemented ownership/bootstrap class boundaries; actual process control and successor-epoch authorization remain pending.", + "LLD 8 records recovery-reader API/caps and distinguishes fatal initial ownership failure from incomplete later diagnostics; read-only scan is not fencing.", + "LLD 9 and layout v1 define shared canonical paths, independent manifest retention, ReadyCandidate-only comparison, shared budgets and the generic-store path-binding integration boundary.", + "LLD10 records bounded internal Unix HTTP exchange, clock/deadline/uncertainty semantics, ownership and parser/transport boundaries; no actual Docker controller or process-fencing claim." + ], + "latest_rg006_runtime_ownership": { + "status": "component_verified_merged_to_feature", + "tested_head": "abd4a1bb30eecbc3d8eae3f5f582e5c5660d6780", + "tested_merge_ref": "79eb61fd0b5e9dd322a97eea0ee7ccd45375f22e", + "run": 45286150998, + "pull_request": 18, + "evidence": "docs/evidence/RG-006-C.md", + "full_story_done": false, + "merge_commit": "90399f64eb9bd2b6aef81384a9144bcff79f78af", + "pull_request_status": "merged_to_feature" + }, + "latest_rg006_bootstrap": { + "status": "component_verified_merged_to_feature", + "tested_head": "03e618b311056227fe6bccb4b9143ced00d2f28c", + "tested_merge_ref": "be6acc0697bca17f70803009327289de19c2abd0", + "run": 45287922499, + "pull_request": 19, + "evidence": "docs/evidence/RG-006-D.md", + "full_story_done": false, + "pull_request_status": "merged_to_feature", + "merge_commit": "cb98d7851fdac6f4eedab0d5f55a88a7fd98a798" + }, + "latest_rg006_bootstrap_recovery": { + "status": "component_verified_merged_to_feature", + "pull_request": 20, + "tested_head": "87c784b25d47dd97527709756fd63673671af470", + "tested_merge_ref": "0784213de9ec24bf7e111224363f04a56909f4cb", + "run": 45292546023, + "evidence": "docs/evidence/RG-006-E.md", + "full_story_done": false, + "pull_request_status": "merged_to_feature", + "merge_commit": "9d9074601859c67541cd73343249ea11e8e09a95" + }, + "latest_rg006_artifact_layout": { + "status": "component_verified", + "pull_request": 21, + "tested_head": "7fc9895e5f928ad1576d5b2119b79f4a717151e9", + "tested_merge_ref": "a93680850e190bb7e4d6a3c11f3dc4bb46a8051f", + "run": 45332588272, + "evidence": "docs/evidence/RG-006-F.md", + "scope": "Shared names and read-only optional manifest diagnostics; no Docker control, serving or successor capability", + "full_story_done": false, + "ctest_groups_per_clean_build": 52, + "clean_builds": 2, + "python_tests": 17, + "matching_generated_files": 12, + "sanitizer_groups": 38, + "artifact_id": 14893310876, + "artifact_sha256": "55e4f28c6a639bd8a09711b9842f3f40d8eca2cc7c144afe9f70721b951a188d", + "pull_request_status": "merged_to_feature", + "merge_commit": "e2d6aeaef0b9ac4e595eb6c50e26afda3e6ee314" + }, + "latest_rg006_unix_transport": { + "status": "component_verified", + "pull_request": 22, + "branch": "feature/RG-006-docker-unix-transport", + "tested_head": "195ed15d2535ff6b599412f009cfb897d2c971d4", + "tested_merge_ref": "0df8f68b7770196f0a7e2546b495697993227fc2", + "run": 45558880696, + "evidence": "docs/evidence/RG-006-G.md", + "ctest_groups_per_clean_build": 58, + "clean_builds": 2, + "python_tests": 17, + "matching_generated_files": 12, + "sanitizer_groups": 44, + "transport_sanitizer_groups": 6, + "artifact_id": 14997099492, + "artifact_sha256": "8c7e98465d00e0f03f54dfdc690a28c3b11bd5bfebe0a4e4db923a23ce92f595", + "full_story_done": false, + "pull_request_status": "verified_ready_for_feature_integration" + } }, "next_actions": [ - "Wait for the Product Owner's explicit proceed command; do not begin development or test execution before it.", - "After proceed, verify/sync main into a Git checkout and inspect the target Linux build environment, then execute RG-001.", - "Re-estimate after RG-001 and the first two implementation PRs using observed environment and review effort." + "Finish PR23 native Docker/process-evidence qualification and independent review, then integrate durable recovery/orphan reconciliation and verified successor authorization. No current component grants serving or reset authority.", + "Then RG006 manifest/fencing and RG007 witness before strict runtime/adapter/Release A acceptance.", + "Keep production session caching disabled; native SDK qualification is test-only.", + "Maintain per-agent logs and leave main implementation merges to Product Owner control." ], "authorization": { "documentation_and_merge": "Explicitly authorized by user in this task.", - "implementation": "Not requested in this documentation task; context does not itself authorize deployment or claim implementation.", + "implementation": "Development/testing authorized; main merge remains under Product Owner review.", "planning_documentation_main": "Explicitly authorized by the user in this task.", - "development_and_testing": "Wait for the user's explicit proceed command." + "development_and_testing": "Authorized by Product Owner on 2026-11-12: begin the implementation.", + "main_implementation_merge": "Component PRs merge into feature/distributed-rateguard after verification. Final feature-to-main promotion is PR #13 and remains pending Product Owner review." }, "stories": [ { "id": "RG-001", "title": "Freeze wire contracts and build manifest", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-001", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-001", "link_type": "repository_story", "release": "A", - "status": "planned_not_implemented", + "status": "component_accepted_merged_to_feature", "depends_on": [], "prd_ids": [ "PRD-005", @@ -104,19 +326,19 @@ "planned_files": [ { "path": "proto/rateguard/v1/admission.proto", - "status": "proposed_not_present" + "status": "implemented_on_feature_branch" }, { "path": "proto/rateguard/v1/authority.proto", - "status": "proposed_not_present" + "status": "implemented_on_feature_branch" }, { "path": "CMakeLists.txt", - "status": "proposed_not_present" + "status": "implemented_on_feature_branch" }, { "path": "build-lock.json", - "status": "proposed_not_present" + "status": "implemented_on_feature_branch" } ], "classes": [ @@ -141,13 +363,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -158,7 +380,7 @@ "AT-04", "AT-06" ], - "status": "not_run" + "status": "passed_component_scope_see_evidence" }, { "id": "RG-001-AC02", @@ -167,7 +389,7 @@ "AT-13", "AT-20" ], - "status": "not_run" + "status": "passed_component_scope_see_evidence" }, { "id": "RG-001-AC03", @@ -175,18 +397,25 @@ "evidence_ids": [ "AT-07" ], - "status": "not_run" + "status": "passed_component_scope_see_evidence" } ], - "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files." + "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files.", + "implementation_evidence": { + "path": "docs/evidence/RG-001.md", + "pull_request": "https://github.com/kshiteesh28/DistributedRateGuard/pull/5", + "run": 43327798021, + "tested_head": "4c924495a1303054a2c3b26edfae757430ea4d72", + "scope": "API/helpers/build/synthetic transport; no quota service" + } }, { "id": "RG-002", "title": "Implement immutable policy and checked arithmetic", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-002", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-002", "link_type": "repository_story", "release": "A", - "status": "planned_not_implemented", + "status": "component_accepted_merged_to_feature", "depends_on": [ "RG-001" ], @@ -203,19 +432,19 @@ "planned_files": [ { "path": "src/policy/policy_snapshot.h", - "status": "proposed_not_present" + "status": "implemented_on_feature_branch" }, { "path": "src/policy/policy_loader.h", - "status": "proposed_not_present" + "status": "implemented_on_feature_branch" }, { "path": "src/policy/canonical_codec.h", - "status": "proposed_not_present" + "status": "implemented_on_feature_branch" }, { "path": "src/authority/bucket_math.h", - "status": "proposed_not_present" + "status": "implemented_on_feature_branch" } ], "classes": [ @@ -241,13 +470,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -258,7 +487,7 @@ "AT-01", "AT-04" ], - "status": "not_run" + "status": "passed_component_scope_see_evidence" }, { "id": "RG-002-AC02", @@ -267,7 +496,7 @@ "AT-02", "AT-03" ], - "status": "not_run" + "status": "passed_component_scope_see_evidence" }, { "id": "RG-002-AC03", @@ -275,18 +504,25 @@ "evidence_ids": [ "AT-21" ], - "status": "not_run" + "status": "passed_component_scope_see_evidence" } ], - "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files." + "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files.", + "implementation_evidence": { + "path": "docs/evidence/RG-002.md", + "pull_request": "https://github.com/kshiteesh28/DistributedRateGuard/pull/6", + "run": 43353832066, + "tested_head": "7640975031aee2af2ee7ae855ce88b76115f1569", + "scope": "Pure policy/encoding/arithmetic; independent component acceptance" + } }, { "id": "RG-003", "title": "Implement shared clock provenance and commit timing", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-003", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-003", "link_type": "repository_story", "release": "A", - "status": "planned_not_implemented", + "status": "component_verified_integration_pending", "depends_on": [ "RG-001" ], @@ -301,11 +537,11 @@ "planned_files": [ { "path": "src/platform/clock.h", - "status": "proposed_not_present" + "status": "implemented_on_RG003_feature_branch" }, { "path": "src/platform/clock_linux.h", - "status": "proposed_not_present" + "status": "implemented_on_RG003_feature_branch" } ], "classes": [ @@ -329,13 +565,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -346,7 +582,7 @@ "AT-01", "AT-17" ], - "status": "not_run" + "status": "passed_component_scope_see_evidence" }, { "id": "RG-003-AC02", @@ -355,7 +591,7 @@ "AT-02", "AT-07" ], - "status": "not_run" + "status": "integration_pending_named_owner" }, { "id": "RG-003-AC03", @@ -363,18 +599,81 @@ "evidence_ids": [ "AT-17" ], - "status": "not_run" + "status": "integration_pending_named_owner" } ], - "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files." + "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files.", + "dependency_contracts": [ + { + "id": "RG-003-A", + "interface": "IClock/LinuxMonotonicClock", + "status": "verified_component", + "tested_revision": "2d55c6e032ae75947f045ac76ffa383b2b1dd9d8", + "evidence": "docs/evidence/RG-003.md", + "run": 43355987772, + "permitted_consumers": [ + "RG-006", + "RG-007", + "RG-008" + ], + "excluded_guarantees": [ + "Docker participant provenance", + "Service commit/deadline mapping", + "Checker UNKNOWN classification" + ], + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-003-clock-provenance/docs/evidence/RG-003.md" + }, + { + "id": "RG-003-B", + "status": "pending", + "owners": [ + "RG-006" + ] + }, + { + "id": "RG-003-C", + "status": "pending", + "owners": [ + "RG-007", + "RG-008" + ], + "acceptance": [ + "RG-003-AC02" + ] + }, + { + "id": "RG-003-D", + "status": "pending", + "owners": [ + "RG-011" + ], + "acceptance": [ + "RG-003-AC03" + ], + "owner_deliverable": "RG-011A", + "release": "A", + "inputs": [ + "RG-005 completeness", + "RG-006 participant/epoch provenance", + "RG-007/008 commit mapping" + ], + "acceptance_owner": "Tester", + "required_behavior": "Missing, incomparable, inconsistent or incomplete clock/history evidence produces UNKNOWN with reason and blocks strict safety PASS.", + "required_before": [ + "RG-008 strict acceptance", + "Release A completion" + ], + "release_c_extension": "RG-013 credit conservation, interval bound and formal trace/model checks" + } + ] }, { "id": "RG-004", "title": "Implement mTLS identity and operation authorization", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-004", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-004", "link_type": "repository_story", "release": "A", - "status": "planned_not_implemented", + "status": "a_b1_b2_b3_component_verified_full_integration_pending", "depends_on": [ "RG-001", "RG-002" @@ -388,17 +687,64 @@ ], "planned_files": [ { - "path": "src/security/peer_authenticator.h", - "status": "proposed_not_present" + "path": "include/rateguard/security/peer_authenticator.h", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-peer-authorization", + "head": "9d14bb74bd937401471e96e039f651c17c226c43" }, { - "path": "src/security/authorization.h", - "status": "proposed_not_present" + "path": "src/security/peer_authenticator.cpp", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-peer-authorization", + "head": "9d14bb74bd937401471e96e039f651c17c226c43" + }, + { + "path": "include/rateguard/security/authorization_resolver.h", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-peer-authorization", + "head": "9d14bb74bd937401471e96e039f651c17c226c43" + }, + { + "path": "src/security/authorization_resolver.cpp", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-peer-authorization", + "head": "9d14bb74bd937401471e96e039f651c17c226c43" + }, + { + "path": "include/rateguard/security/client_call_guard.h", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-client-guards", + "head": "0a1b37b6147adb39c885459253d59c8561c9c5cc" + }, + { + "path": "src/security/client_call_guard.cpp", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-client-guards", + "head": "0a1b37b6147adb39c885459253d59c8561c9c5cc" + }, + { + "path": "include/rateguard/security/pinned_peer_rpc_client.h", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-client-guards", + "head": "0a1b37b6147adb39c885459253d59c8561c9c5cc" + }, + { + "path": "src/security/pinned_peer_rpc_client.cpp", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-client-guards", + "head": "0a1b37b6147adb39c885459253d59c8561c9c5cc" } ], "classes": [ "PeerAuthenticator", - "AuthorizationResolver" + "AuthenticatedPeer", + "AuthorizationResolver", + "AuthorizedOperation", + "AuthorizedGrant", + "ClientCallGuard", + "PreparedClientCall", + "PinnedPeerRpcClient", + "Invoked" ], "code_design_notes": [ "Validate role/SAN/EKU/expiry every RPC including reused channels. Bind peer to tenant/operation and derive cost from policy.", @@ -417,13 +763,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -454,15 +800,154 @@ "status": "not_run" } ], - "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files." + "first_action": "Integrate verified security inputs at actual service precommit/pregrant/preforward points, with RG006 manifest/fencing and RG005 event/export privacy; full-story ACs remain unverified.", + "implementation_decisions": { + "path": "docs/decisions/RG-004-security-v1.md", + "revision": 2, + "branch": "docs/scrum-work-log", + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/decisions/RG-004-security-v1.md", + "status": "selected_defaults_partial_implementation_verified", + "remaining_evidence": [ + "Production manifest binding, credential provisioning and participant readiness/fenced rotation", + "Actual service precommit/pregrant/preforward wiring and deadline/epoch checks; B3 supplies only reusable certificate/time primitives", + "Real service no-allocation fault cases, event/export privacy and remaining full-story acceptance" + ] + }, + "component_inputs": [ + { + "id": "RG-004-A", + "status": "verified_review_ready", + "branch": "feature/RG-004-security-probes", + "head": "f5b3e975225c869e4a9638af57ab9f7c8a06e546", + "run": 43980308204, + "scope": "Exact leaf pin/URI TLS compatibility, independent verifier-bypass detection, trusted UTC primitive; not production registry/authorization, connection-expiry or epoch fencing" + }, + { + "id": "RG-004-B1", + "status": "verified_review_ready", + "branch": "feature/RG-004-certificate-registry", + "head": "6366df84903049fde3fd92243b3aa7bd06c43986", + "pull_request": 10, + "run": 44016873892, + "contract_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-certificate-registry/docs/contracts/certificate-registry-v1.md", + "scope": "Typed public-certificate validation and immutable metadata only; no manifest/auth/service readiness claim", + "merge_ref": "e03a5291889bb7fc9078bd5bda6b822657ea3cc7", + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/evidence/RG-004-B1.md" + }, + { + "id": "RG-004-B2", + "status": "verified_review_ready", + "branch": "feature/RG-004-peer-authorization", + "head": "20210d5fbabcd891dbbb20ab89eca26f3a73a1db", + "pull_request": 11, + "run": 44023785687, + "contract_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-peer-authorization/docs/contracts/peer-authorization-v1.md", + "verified_implementation_head": "9d14bb74bd937401471e96e039f651c17c226c43", + "documentation_run": 44023785687, + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/evidence/RG-004-B2.md", + "scope": "Peer identity and policy authorization with actual TLS fixture/dispatch expiry; no quota, commit, forwarding, epoch fencing or reconnect/resumption proof", + "implementation_run": 44022842950, + "merge_ref": "31084e66433126412a5e22457c13fde1f34350b1", + "pull_request_status": "ready_unmerged" + }, + { + "id": "RG-004-B3", + "status": "verified_review_ready", + "branch": "feature/RG-004-client-guards", + "head": "0a1b37b6147adb39c885459253d59c8561c9c5cc", + "pull_request": 12, + "run": 44128491936, + "merge_ref": "1fe328849653f92486fa69695e649a6049e961b0", + "contract_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-client-guards/docs/contracts/pinned-client-v1.md", + "evidence_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/evidence/RG-004-B3.md", + "scope": "Client trust guard/sealed typed calls and native SDK session qualification only; production caching disabled; no actual commit/forward/fencing", + "acceptance": "independent_QA_and_senior_review_passed", + "session_qualification": { + "status": "qualified_test_fixture_only", + "actual_resumed": true, + "cache_capacity": 1, + "new_transport": true, + "client_leaf_pin": true, + "server_leaf_pin": true, + "client_verifier_delta": 1, + "server_verifier_delta": 1, + "production_session_cache_enabled": false + }, + "full_story_done": false, + "pull_request_status": "ready_unmerged" + } + ], + "integration_dependencies": [ + { + "producer_story": "RG-006", + "contract": "epoch_manifest_and_positive_fencing", + "status": "pending", + "required_for": [ + "RG-004-AC02" + ], + "purpose": "Fenced trust replacement; full-story acceptance follows supervisor lifecycle evidence" + }, + { + "producer_story": "RG-005", + "contract": "real_event_and_export_privacy", + "status": "pending", + "required_for": [ + "RG-004-AC03" + ] + } + ], + "implemented_input_files": [ + { + "path": "include/rateguard/security/certificate_registry.h", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-certificate-registry", + "head": "6366df84903049fde3fd92243b3aa7bd06c43986" + }, + { + "path": "src/security/certificate_registry.cpp", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-certificate-registry", + "head": "6366df84903049fde3fd92243b3aa7bd06c43986" + }, + { + "path": "include/rateguard/security/peer_authenticator.h", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-peer-authorization", + "head": "9d14bb74bd937401471e96e039f651c17c226c43" + }, + { + "path": "src/security/peer_authenticator.cpp", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-peer-authorization", + "head": "9d14bb74bd937401471e96e039f651c17c226c43" + }, + { + "path": "include/rateguard/security/authorization_resolver.h", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-peer-authorization", + "head": "9d14bb74bd937401471e96e039f651c17c226c43" + }, + { + "path": "src/security/authorization_resolver.cpp", + "status": "verified_on_unmerged_review_branch", + "branch": "feature/RG-004-peer-authorization", + "head": "9d14bb74bd937401471e96e039f651c17c226c43" + } + ], + "authorization_contract": { + "path": "docs/contracts/peer-authorization-v1.md", + "revision": 1, + "branch": "feature/RG-004-peer-authorization", + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/20210d5fbabcd891dbbb20ab89eca26f3a73a1db/docs/contracts/peer-authorization-v1.md" + } }, { "id": "RG-005", "title": "Implement bounded events and incomplete-history accounting", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-005", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-005", "link_type": "repository_story", "release": "A", - "status": "planned_not_implemented", + "status": "in_progress", "depends_on": [ "RG-001" ], @@ -477,11 +962,39 @@ "planned_files": [ { "path": "src/events/event_recorder.h", - "status": "proposed_not_present" + "status": "implemented_component_verified" }, { "path": "src/events/history_exporter.h", - "status": "proposed_not_present" + "status": "implemented_component_verified" + }, + { + "path": "src/events/history_validator.h", + "status": "implemented_component_verified" + }, + { + "path": "src/events/file_publisher.h", + "status": "implemented_component_verified" + }, + { + "path": "src/events/aggregate_metrics.h", + "status": "implemented_component_verified" + }, + { + "path": "tools/history/history_reader.h", + "status": "implemented_component_verified" + }, + { + "path": "tools/history/strict_reconciliation.h", + "status": "implemented_component_verified" + }, + { + "path": "tools/history/retention.py", + "status": "implemented_component_verified" + }, + { + "path": "tools/history/inspect_main.cpp", + "status": "implemented_component_verified" } ], "classes": [ @@ -505,13 +1018,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -522,7 +1035,7 @@ "AT-10", "AT-11" ], - "status": "not_run" + "status": "component_verified_runtime_pending" }, { "id": "RG-005-AC02", @@ -530,7 +1043,7 @@ "evidence_ids": [ "AT-11" ], - "status": "not_run" + "status": "component_verified_runtime_pending" }, { "id": "RG-005-AC03", @@ -539,22 +1052,23 @@ "AT-10", "AT-13" ], - "status": "not_run" + "status": "component_verified_runtime_pending" } ], - "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files." + "first_action": "Finish runtime/supervisor event owner binding, stop propagation, private output lifecycle and persisted incomplete evidence; integrate RG006/RG007 and RG011A before full RG005/Release A acceptance.", + "component_evidence": "docs/evidence/RG-005.md", + "inspector_evidence": "docs/evidence/RG-005-inspector.md" }, { "id": "RG-006", "title": "Implement supervisor lifecycle and positive fencing", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-006", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-006", "link_type": "repository_story", "release": "A", - "status": "planned_not_implemented", + "status": "in_progress", "depends_on": [ "RG-002", "RG-003", - "RG-004", "RG-005" ], "prd_ids": [ @@ -571,11 +1085,11 @@ "planned_files": [ { "path": "src/supervisor/epoch_gate.h", - "status": "proposed_not_present" + "status": "implemented_component_verified" }, { "path": "src/supervisor/manifest_store.h", - "status": "proposed_not_present" + "status": "implemented_component_verified" }, { "path": "src/supervisor/process_controller.h", @@ -588,6 +1102,70 @@ { "path": "src/supervisor/docker_process_controller.h", "status": "proposed_not_present" + }, + { + "path": "src/supervisor/manifest_codec.h", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/manifest_codec.cpp", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/manifest_store.cpp", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/runtime_owner.h", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/runtime_owner.cpp", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/bootstrap_inventory.h", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/bootstrap_inventory.cpp", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/bootstrap_store.h", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/bootstrap_store.cpp", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/bootstrap_recovery_reader.h", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/bootstrap_recovery_reader.cpp", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/epoch_artifact_layout.h", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/unix_http_transport.h", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/unix_http_transport.cpp", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/http1_parser.h", + "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/http1_parser.cpp", + "status": "implemented_component_verified" } ], "classes": [ @@ -595,11 +1173,23 @@ "ManifestStore", "IProcessController", "EpochSupervisor", - "DockerProcessController" + "DockerProcessController", + "RuntimeOwner", + "InitialEpochClaim", + "BootstrapInventory", + "BootstrapStore", + "BootstrapRecoveryReader", + "IUnixHttpTransport", + "NativeUnixHttpTransport (private)" ], "code_design_notes": [ "Use ACTIVE/DRAINING/CLOSED; preserve exact process/container inventory. Supervisor failure never adopts a running old epoch.", - "Use LLD sections 16 and 17 for exact sequencing and class ownership; evidence must be independent of production decision logic." + "Use LLD sections 16 and 17 for exact sequencing and class ownership; evidence must be independent of production decision logic.", + "LLD 7 §21 defines initial-claim ownership, durable visibility versus transition status and candidate-data handoff. BootstrapStore does not launch, activate, recover or fence participants.", + "EpochSupervisor owns the future existing-intent recovery reader. RuntimeOwner existing acquisition does not load bootstrap state; missing or uncertain inventory blocks reset.", + "LLD 8 §21.1 defines diagnostic-only bounded recovery reading. Pending container IDs/historical provenance are retained; scan_complete never proves prior durability, cessation or safe reset.", + "epoch_layout_v1 is a pure namespace utility, not a service or capability. Optional nested manifest diagnostics use independent codecs and the same byte/participant budgets. CLOSED metadata is not process-exit evidence.", + "LLD10 §21.3 and transport v1 define a Linux-only bounded Unix HTTP exchange. The controller must construct API-qualified paths and fix root peer/socket UIDs; response status, stop ACK and exit proof remain separate." ], "files_to_refer": [ { @@ -614,13 +1204,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -652,12 +1242,44 @@ "status": "not_run" } ], - "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files." + "first_action": "Finish PR23 native Docker/process-evidence qualification and independent review, then integrate durable recovery/orphan reconciliation and verified successor authorization. No current component grants serving or reset authority.", + "input_dependency_contracts": [ + { + "contract": "RG-003-A", + "revision": "2d55c6e032ae75947f045ac76ffa383b2b1dd9d8", + "evidence": "docs/evidence/RG-003.md", + "purpose": "Verified clock for development; full RG-003 integration not waived" + }, + { + "contract": "RG-004-A", + "producer_story": "RG-004", + "revision": "f5b3e975225c869e4a9638af57ab9f7c8a06e546", + "status": "verified", + "purpose": "TLS pin verifier/trusted UTC development input; not full authentication acceptance" + }, + { + "contract": "RG-004-B1", + "producer_story": "RG-004", + "status": "verified", + "purpose": "Validated immutable certificate metadata for manifest implementation; runtime authorization, service activation and final fencing gates remain separate", + "revision": "6366df84903049fde3fd92243b3aa7bd06c43986", + "run": 44016873892 + } + ], + "component_evidence": "docs/evidence/RG-006-A.md", + "manifest_evidence": "docs/evidence/RG-006-B.md", + "runtime_ownership_evidence": "docs/evidence/RG-006-C.md", + "bootstrap_evidence": "docs/evidence/RG-006-D.md", + "bootstrap_recovery_evidence": "docs/evidence/RG-006-E.md", + "artifact_layout_contract": "docs/contracts/epoch-artifact-layout-v1.md", + "artifact_layout_evidence": "docs/evidence/RG-006-F.md", + "unix_http_transport_contract": "docs/contracts/docker-engine-unix-http-v1.md", + "unix_http_transport_evidence": "docs/evidence/RG-006-G.md" }, { "id": "RG-007", "title": "Implement independently validated witness transactions", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-007", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-007", "link_type": "repository_story", "release": "A", "status": "planned_not_implemented", @@ -722,13 +1344,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -759,12 +1381,20 @@ "status": "not_run" } ], - "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files." + "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files.", + "input_dependency_contracts": [ + { + "contract": "RG-003-A", + "revision": "2d55c6e032ae75947f045ac76ffa383b2b1dd9d8", + "evidence": "docs/evidence/RG-003.md", + "purpose": "Verified clock for development; full RG-003 integration not waived" + } + ] }, { "id": "RG-011", "title": "Build independent oracle (A acceptance prerequisite; replay CLI in B)", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-011", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-011", "link_type": "repository_story", "release": "B", "status": "planned_not_implemented", @@ -794,7 +1424,8 @@ ], "code_design_notes": [ "Build a minimal independent strict serial oracle and golden fixtures before strict A acceptance. Complete the full offered-trace replay CLI in Release B. Never import production BucketMath or AuthorityEngine logic.", - "Use LLD sections 16 and 17 for exact sequencing and class ownership; evidence must be independent of production decision logic." + "Use LLD sections 16 and 17 for exact sequencing and class ownership; evidence must be independent of production decision logic.", + "RG-011A owns Release A strict provenance evidence gate RG-003-D: RG-005 completeness plus verified runtime provenance/commit mapping; inadequate evidence is UNKNOWN and cannot count as safety PASS before RG-008 acceptance. RG-013 adds C extensions." ], "files_to_refer": [ { @@ -809,13 +1440,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -851,7 +1482,7 @@ { "id": "RG-008", "title": "Implement strict authority and admission service", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-008", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-008", "link_type": "repository_story", "release": "A", "status": "planned_not_implemented", @@ -925,13 +1556,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -964,12 +1595,29 @@ "status": "not_run" } ], - "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files." + "first_action": "Read the linked source contracts and confirm prerequisite stories have evidence before editing proposed files.", + "input_dependency_contracts": [ + { + "contract": "RG-003-A", + "revision": "2d55c6e032ae75947f045ac76ffa383b2b1dd9d8", + "evidence": "docs/evidence/RG-003.md", + "purpose": "Verified clock for development; full RG-003 integration not waived" + } + ], + "acceptance_dependency_contracts": [ + { + "contract": "RG-003-D", + "owner_story": "RG-011", + "owner_deliverable": "RG-011A", + "status": "pending", + "scope": "Required before strict acceptance, not before development" + } + ] }, { "id": "RG-009", "title": "Implement trusted adapter forwarding gate", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-009", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-009", "link_type": "repository_story", "release": "A", "status": "planned_not_implemented", @@ -1017,13 +1665,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -1059,7 +1707,7 @@ { "id": "RG-010", "title": "Implement fixed-Q grants and replica credit state", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-010", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-010", "link_type": "repository_story", "release": "C", "status": "planned_not_implemented", @@ -1119,13 +1767,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -1162,7 +1810,7 @@ { "id": "RG-012", "title": "Implement frozen workloads and comparative reports", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-012", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-012", "link_type": "repository_story", "release": "B", "status": "planned_not_implemented", @@ -1226,13 +1874,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -1271,7 +1919,7 @@ { "id": "RG-013", "title": "Implement bounded formal model and history checker", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-013", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-013", "link_type": "repository_story", "release": "C", "status": "planned_not_implemented", @@ -1325,13 +1973,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -1368,7 +2016,7 @@ { "id": "RG-014", "title": "Assemble release evidence and reproducible handoff", - "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/STORIES.md#rg-014", + "story_url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/STORIES.md#rg-014", "link_type": "repository_story", "release": "C", "status": "planned_not_implemented", @@ -1423,13 +2071,13 @@ }, { "path": "docs/HLD.md", - "revision": 4, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/HLD.md" + "revision": 5, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/HLD.md" }, { "path": "docs/LLD.md", - "revision": 5, - "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/LLD.md#17-class-design-and-construction-contracts" + "revision": 10, + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], "acceptance_criteria": [ @@ -1480,7 +2128,7 @@ "sprint_plan": { "path": "docs/SPRINT-PLAN.md", "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/main/docs/SPRINT-PLAN.md", - "status": "planning_only_waiting_for_product_owner_proceed", + "status": "sprint_1_foundations_in_progress_sprint_0_deployment_gate_open", "estimates_unit": "active_agent_minutes", "baseline_total_minutes": 15250, "feasibility_spike_minutes": { @@ -1488,6 +2136,13 @@ "max": 240 }, "target_branch": "main", - "no_development_or_test_execution_before_proceed": true - } + "no_development_or_test_execution_before_proceed": false + }, + "work_log": { + "path": "docs/SCRUM-WORK-LOG.md", + "canonical_branch": "feature/distributed-rateguard", + "historical_actual_effort": "unknown_not_recorded", + "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/SCRUM-WORK-LOG.md" + }, + "generated_at_utc": "2026-11-25T06:30:00Z" } diff --git a/docs/contracts/bootstrap-inventory.md b/docs/contracts/bootstrap-inventory.md new file mode 100644 index 0000000..a2fdf38 --- /dev/null +++ b/docs/contracts/bootstrap-inventory.md @@ -0,0 +1,13 @@ +# Bootstrap inventory and durable registration + +Sources are PRD 8, SRD 5 and the HLD 5 / LLD 6 A-03 clarification in [PR #18](https://github.com/kshiteesh28/DistributedRateGuard/pull/18). This increment depends on runtime-root ownership; implementation and process-control acceptance are tracked separately. + +A fixed plan binds runtime domain, epoch, authority incarnation, policy digest, expected common clock identity and every participant's role, slot, incarnation and exact stopped-container ID. Every container belongs to the plan before start. Pending process identities use an explicit pending state; they do not become fake complete manifests. + +The value model records observed host PID/start/clock identity for each exact planned participant. Equal observations replay unchanged. Unknown participants, changed identities, PID collisions and revision exhaustion require recovery. Revisions never wrap. The complete candidate requires the full roster, identical clock provenance and the existing gate's pure validation. + +Model output describes data. Actual controller verification, durable storage and participant acknowledgement must supply their own evidence. The durable store consumes a move-only initial-epoch claim and binds its domain/epoch before writing the plan. It may expose a complete durable candidate only after every required record is synced and ownership remains valid. A failed or uncertain write prevents readiness; existing state cannot be adopted into serving automatically. + +Artifacts use a versioned strict canonical JSON envelope and SHA-256, the existing decimal-string integer rules and a 4 MiB encoded limit. Checksums detect corruption and do not establish writer authorization or rollback freshness. + +Full serving activation still requires policy, trust, witness, clock and epoch readiness. Container/process launch, authenticated bootstrap acknowledgement, positive fencing and successor-epoch recovery remain separate integration work. diff --git a/docs/contracts/bootstrap-recovery-v1.md b/docs/contracts/bootstrap-recovery-v1.md new file mode 100644 index 0000000..7cfcabe --- /dev/null +++ b/docs/contracts/bootstrap-recovery-v1.md @@ -0,0 +1,44 @@ +# Bootstrap recovery reader v1 + +**Layout extension:** [Epoch artifact layout v1](epoch-artifact-layout-v1.md) adds strictly validated optional `manifest-store` artifacts to the bootstrap-only child allowlist below. Other bounds and diagnostic-only semantics remain in force. The extension does not authorize serving, stopping or reset. + +**Status:** Proposed RG-006 component contract, 2026-11-23. Sources: PRD 8 / SRD 5, HLD 5 A-03, LLD 7 §21. This contract supplies the bounded read-only reader needed by the future EpochSupervisor recovery path. It does not complete that path. + +## Boundary and result + +`BootstrapRecoveryReader::Read(const RuntimeOwner&, IRecoveryReaderIo*)` requires validated RecoveryRequired-mode root ownership. Fresh ownership, invalid ownership or inability to obtain the root descriptor returns a typed fatal result. Other uncertainty is represented in an immutable shared diagnostic snapshot where possible; allocation failure is fatal and implies unknown evidence. + +The snapshot binds the runtime domain and contains per-epoch decoded inventories, canonical digests, file/directory identity evidence and typed issues. It includes every planned container in a securely decoded inventory, including entries without a recorded PID/start identity. Persisted historical clock/boot provenance is retained; recovery decoding does not require it to match the current host boot. + +`scan_complete` means only that the bounded scan was structurally stable and all examined artifacts were valid. It does not prove past fsync completion, activation state, current process identity, cessation, absence of rollback or permission to stop, serve, reset or create a successor. No candidate, claim or fencing token is returned. Empty/no-valid-intent scans are incomplete. + +## Scan and validation + +1. Validate owner mode/domain/identity, duplicate a CLOEXEC root descriptor, and enumerate all root names, not merely a chosen latest epoch. +2. Check exact `epoch-<32 lowercase hex digits>` directories. The root's ownership anchor/lock are validated by RuntimeOwner. Unknown entries, noncanonical epoch names, unsafe types or resource exhaustion make the snapshot incomplete. +3. Inspect every bounded epoch-directory entry. Open only no-follow, nonblocking descriptors. Directories must be private owned directories; `intent.json` must be an owned regular 0600 single-link bounded file. Missing, special, symlinked, hard-linked or substituted artifacts are errors. +4. Decode with the existing bounded canonical schema/checksum codec. Bind payload domain to owner domain and epoch to the directory basename. Preserve every safe sibling inventory even when another child is bad. Unknown/temp child artifacts make the scan incomplete; they are not silently interpreted as an empty or trusted inventory. +5. Revalidate entry/file/directory identities, relevant size/mode/mtime/ctime metadata, and root/child entry snapshots before returning. Validate owner again. A detected change makes evidence incomplete. These checks narrow races; they are not an atomic filesystem snapshot and do not protect against a hostile same-UID writer. +6. Report duplicate container identities across decoded epochs as conflicts; never select the newest epoch or silently merge conflicting identities. Recovery-required inventories remain diagnostic and keep the scan incomplete. + +No directory/file mutation, removal, repair, fsync, process action or store adoption occurs. Raw arbitrary filesystem names and file contents are excluded from diagnostics; directory names are canonical known epoch names or empty. + +## Finite implementation limits + +| Resource | Limit / overflow | +| --- | --- | +| Each intent | Existing 4 MiB codec cap; reject before allocation/read | +| All root entries | 4,096 excluding dot entries; incomplete on overflow | +| All entries per epoch child | 16; incomplete on overflow | +| Epoch directories | 1,024; incomplete on overflow | +| Aggregate attempted input | 64 MiB; reserve file-size budget before reading, including failed reads/decodes; never refund it | +| Retained participants | 16,384 across inventories; incomplete on overflow | +| Global/per-epoch issues | 256 / 16; nonallocating truncation flags always force incomplete | + +These are reader implementation bounds, not amended SRD deployment or quota limits. At any limit, preserve previously collected known records and expose uncertainty; no overflow permits reset. + +## Verification and remaining gates + +Independent developer and tester suites must exercise pending and complete inventories, historical provenance, fresh-owner rejection, empty/missing/unknown artifacts, temp siblings, malformed/digest/domain/name mismatches, file types/permissions, detected races, duplicate identities and resource bounds. Tests must remain active under NDEBUG. Repeat-read results must be stable without changing files. + +Real pinned Linux/OpenSSL and sanitizer evidence is required before component acceptance. Local digest shims are smoke only. Actual controller inspection/stop, authenticated participant readiness, full recovery orchestration and a verified successor-epoch authorization remain unimplemented integration requirements. Incomplete inventory blocks reset pending reconciliation or the source contracts' controlled complete-VM shutdown evidence. diff --git a/docs/contracts/certificate-registry-v1.md b/docs/contracts/certificate-registry-v1.md new file mode 100644 index 0000000..36ee99f --- /dev/null +++ b/docs/contracts/certificate-registry-v1.md @@ -0,0 +1,39 @@ +# RG-004-B1 certificate registry input contract + +**Revision:** 1 · **Date:** 2026-11-16 · **Status:** Selected implementation contract; not accepted implementation evidence. +**Sources:** PRD 8 PRD-008/024; SRD 5 FR-003/D9/NFR-008; LLD 5 A-02; [SEC-01–11 revision 2](https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/decisions/RG-004-security-v1.md). +**Branch:** `feature/RG-004-certificate-registry`, based on verified RG-004-A head `f5b3e975225c869e4a9638af57ab9f7c8a06e546`. + +## Boundary + +Consume an already-validated immutable PolicySnapshot, caller-owned public root/leaf PEM views and ITrustedWallClock. Return either an immutable registry snapshot or bounded reason-only error. Do not read/write files, accept private keys, serialize supervisor manifests, authorize requests, rotate credentials or claim service readiness. RG-006 owns manifest binding and positive fencing; B2 owns authenticated peer/policy authorization. + +The snapshot binds canonical policy digest, epoch/authority/slot identities, root fingerprint, and exactly one leaf per configured principal. Only public identity/fingerprint/validity metadata survives loading. The trusted validation timestamp describes construction; fresh validity/trust checks remain mandatory before later readiness/calls/commit/forwarding. No immutable snapshot makes an expired certificate valid. + +## Validation contract + +- At most 10,000 principals, using policy-v1's existing cap; at most 64 KiB per PEM certificate and 64 MiB aggregate root plus leaves. The byte caps are explicit NFR-008 implementation bounds, not new product capacity claims. Reject excess before certificate parsing; never silently truncate. +- Exactly one certificate per input, with only surrounding whitespace; reject embedded NUL, trailing certificates/keys or other data. No raw PEM or OpenSSL error text in returned diagnostics/logs. +- Bind the root's DER SHA-256 to policy trust_root_sha256. Require self-signature, EC P-256/SHA-256, CA=true, pathLen=0 and certificate-signing usage. +- Each directly signed leaf uses EC P-256/SHA-256, CA=false and digitalSignature. Apply strict chain validation and each role's required OpenSSL purpose. Accept no intermediates. +- Require exact role EKUs: adapter clientAuth; authority serverAuth; replica both. Do not derive role from CN or request fields. +- Require exactly one NUL-free URI SAN, matching one configured policy principal byte-for-byte. Reject missing/extra/duplicate principals and retain exact leaf DER SHA-256 pins. +- Use an explicit trusted UTC sample, checked integer certificate-time conversion (RFC 5280 UTCTime for 1950–2049; GeneralizedTime for 2050–9999) and `notBefore <= now < notAfter`, including fractional current seconds. Bind the resulting snapshot to unchanged canonical policy bytes/digest. +- Invalid input, crypto/provider failure, allocation/resource failure or trusted-clock failure returns no snapshot. Immutable lookups do not insert or mutate state. + +## Evidence and owners + +Senior Dev implements and supplies developer tests. Junior independently reviews integer time, lifetime and cap boundaries. Tester independently constructs positive/negative fixtures and defect controls against compiled production code. Master integrates a stacked PR and records actual Linux/OpenSSL/ASan results before review readiness. + +Full RG-004 AC01–03, live authorization, established-channel expiry, reconnect/resumption, end-to-end guards and export privacy remain open. A successful B1 test run will only validate this input contract. + +## Slice acceptance criteria + +| ID | Required evidence | +| --- | --- | +| RG-004-B1-AC01 | Real OpenSSL positive fixtures for adapter, replica and authority produce exact independently calculated pins, policy digest and epoch/authority bindings. Reordered input leaves preserve the same identity map. | +| RG-004-B1-AC02 | Wrong root pin, issuer/signature/profile/EKU, unknown/duplicate/missing/extra URI and malformed PEM return no registry. | +| RG-004-B1-AC03 | Injected clock failure and exact/fractional notBefore/notAfter boundaries fail or pass as specified, including expiry exactly at notAfter. | +| RG-004-B1-AC04 | Exact/over certificate and aggregate bounds, principal-count bounds, immutable ownership and unknown lookup behavior are independently checked. Diagnostics contain bounded codes only; review confirms public metadata retention. | + +Linux CI and targeted ASan/UBSan must pass for the exact reviewed source. Full-story AT-04/14 and actual service privacy/rotation acceptance stay open. diff --git a/docs/contracts/clock-v1.md b/docs/contracts/clock-v1.md new file mode 100644 index 0000000..3649fec --- /dev/null +++ b/docs/contracts/clock-v1.md @@ -0,0 +1,27 @@ +# Linux clock v1 — implementation decision record + +Revision 1 · 2026-11-13 · Owner: Master technical lead. Proposed component design approved for RG-003 implementation; no executable result is claimed. + +Sources: PRD 8 / SRD 5 D3–D4, FR-001/017 / LLD 5 §§5,7,16.1,16.3,17. RG-003 depends on verified RG-001 interfaces. This record selects internal mechanisms, not new quota or release behavior. + +## Identity and startup + +ClockIdentity contains a 16-byte kernel boot UUID; uint64 namespace device/inode; signed int64 seconds plus uint32 nanoseconds for each of monotonic and boottime namespace offsets; and int32 numeric CLOCK_MONOTONIC ID (Linux 1). Offset nanoseconds are 0..999999999. Namespace inode is nonzero. Identity compares all fields exactly; no wall/client clock conversion is permitted. + +The supported target is Ubuntu 24.04 x86_64 on Linux >=5.6 with CONFIG_TIME_NS and the required readable proc entries. The kernel, privileged operator and standard unshadowed proc namespace mounts are trusted; this component does not prove hostile-host integrity. Production boot/offset files are opened once, verified with fstatfs as PROC_SUPER_MAGIC, and read bounded from that same descriptor. Namespace descriptors must report NSFS_MAGIC; fstat supplies their device/inode. Any source/type/read failure rejects startup; there is no fallback. The production platform reads the boot UUID from /proc/sys/kernel/random/boot_id, and stats /proc/self/ns/time AND /proc/self/ns/time_for_children. All four snapshots (current-before, children-before, current-after, children-after) must have identical device/inode around reading /proc/self/timens_offsets. Reject split identities, unreadable/malformed/truncated/overlong input, duplicate/missing/unknown offset rows, or a changed snapshot. Bound boot input to 64 bytes and offsets to 512 bytes; a helper must detect one byte over its bound rather than truncate. Boot UUID grammar is exactly lowercase hexadecimal 8-4-4-4-12, followed by at most one LF; no leading/trailing spaces. Offset input has exactly two nonempty rows (optional final LF), each with three tokens separated by spaces/tabs: monotonic|boottime, signed decimal seconds, unsigned decimal nanoseconds. Allow leading/trailing spaces/tabs within a row, but reject CR/NUL, empty rows, duplicate/unknown clocks, extra tokens, leading plus signs, leading zeroes except 0, and negative zero. Parse only complete decimal integers with checked conversion. Accept negative offset seconds and reject invalid offset nanoseconds. + +The children comparison is essential: Linux proc_timens_show_offsets reads time_ns_for_children, while clock_gettime uses current time_ns. See [kernel implementation](https://github.com/torvalds/linux/blob/v6.8/kernel/time/namespace.c#L345) and [time_namespaces(7)](https://www.man7.org/linux/man-pages/man7/time_namespaces.7.html). Device/inode equality follows [namespaces(7)](https://www.man7.org/linux/man-pages/man7/namespaces.7.html). + +Create requires expected identity supplied by the trusted epoch manifest; self-probing is not authority to become ready. Probe and factory APIs remain internal. A smoke test may deliberately use its own identity to test OS plumbing, but does not prove common Docker participant provenance. Production probing is performed on the process leader (gettid()==getpid()), before worker creation; a probe called by a nonleader thread fails. The leader-only /proc/self path is deliberate because the per-thread task directory does not expose timens_offsets on all supported kernels. Startup probing precedes worker creation; workers inherit this namespace. Runtime setns/unshare/namespace mutation is prohibited. RG-006 must enforce topology/manifest ownership and all participant comparisons before activation; absent that evidence RG-003 alone cannot prove system readiness or a quota bound. + +## Sampling, ownership and errors + +IClock exposes Now -> Result, Provenance -> Result, and Healthy. LinuxMonotonicClock owns its platform port and one mutex protecting terminal health, last sample, and the complete clock_gettime(CLOCK_MONOTONIC) call/conversion/comparison. Typed internal failures never fall back, clamp, or substitute a timestamp. Failures latch for object/epoch lifetime with no reset API. A fresh object alone is not authorization to resume an epoch; supervisor integration must fence the failed epoch. + +Sample seconds must be nonnegative and nanoseconds in 0..999999999. Convert to uint64 nanoseconds with checked multiplication/addition; overflow, syscall failure, or a value below the preceding serialized observation latches failure. Equal samples are legal. The factory performs an initial successful Now after identity matching and before returning an object; that sample establishes the lower observation reference. A failed startup clock read returns a typed failure, never a usable object. Later Now calls compare against the retained startup sample. Healthy and Provenance use the same mutex; Healthy is false after the first latched error, and no successful factory result is exposed before identity validation. Unsupported proc/kernel features fail startup without fallback. Provenance after failure returns the first latched error, preserving historical captured identity only in explicitly non-readiness evidence. Allocation/proc parsing happen outside the hot path. + +Lock order is tenant transition lock -> clock lock; never reverse. Now holds no other callbacks, RPC, file reads or logging beyond its owned bounded platform clock-read port. A tenant transition must sample while protected and recheck deadline against that sample before mutation; expiry is now >= deadline. Advancing the clock observation on a rejected/expired attempt is legal; changing bucket state is not. The service/witness transition mapping and real deadline races remain RG-007/008 integration evidence. Global clock serialization trades simplicity for contention; latency must be measured, never inferred. + +## Verification boundary + +Inject only internal platform/clock dependencies. Deterministic tests cover every identity field mismatch, split namespaces and malformed bounded provenance, failed/invalid/overflow/backwards/equal samples, sticky failure, and concurrent serialized samples. Independent reviewer tests must detect a clamp-regression defect. Real Linux tests independently compare kernel/proc identity and fork/exec child identity and timestamps. Namespace-isolation tests must report unsupported permissions explicitly; missing tests do not become a PASS. Docker shared-namespace proof, full commit linearization, runtime epoch shutdown, TLS validity, benchmarks, and interval checker UNKNOWN semantics remain separately gated stories. diff --git a/docs/contracts/docker-engine-unix-http-v1.md b/docs/contracts/docker-engine-unix-http-v1.md new file mode 100644 index 0000000..8abe08f --- /dev/null +++ b/docs/contracts/docker-engine-unix-http-v1.md @@ -0,0 +1,37 @@ +# Docker Engine Unix HTTP Transport Contract + +**Status:** Selected internal component contract; implementation and verification are tracked separately. No Docker deployment, process-fencing or release guarantee is claimed. + +## Boundary and API + +`IUnixHttpTransport::RoundTrip` in `src/supervisor/unix_http_transport.h` carries only GET or POST, an origin-form target, an absolute `CLOCK_MONOTONIC` deadline (`platform::MonoNanos`), and a cancellation flag. Requests have no caller-controlled headers or body. The controller constructs and validates the Docker API-version-qualified target; the transport never chooses or upgrades an API version. The response exposes the final status and bounded decoded body. Transport failures contain a bounded reason and `request_possibly_sent`; that flag is false until a first request byte is written and true thereafter. Failure reasons include invalid target/deadline, unconfigured socket, unsupported platform, peer mismatch, overload, cancellation, deadline expiry, clock failure, socket/protocol error, response limit, and allocation failure. Any failure after dispatch is uncertain to its caller. HTTP error statuses remain responses. There are no automatic retries or redirects. + +## Local socket and trust boundary + +The concrete Linux transport uses only a configured pathname AF_UNIX stream socket. The factory validates the canonical socket path and expected socket metadata, then captures device/inode/owner identity. Each exchange rechecks that identity, creates a fresh `SOCK_NONBLOCK | SOCK_CLOEXEC` descriptor, and verifies peer credentials with `SO_PEERCRED`. Both expected peer UID and socket owner UID default to root (0); nonzero overrides exist only for internal tests, and the production controller must keep both at 0. TCP, abstract sockets, proxy variables, Docker context/config directories, redirects, TLS, and caller-supplied endpoint selection are excluded. Socket ownership/path validation and privileged host configuration remain operator assumptions; peer UID verification does not authenticate a particular daemon binary. + +## Request validation and resource bounds + +Reject targets over 2,048 bytes; require a leading `/` and visible ASCII bytes only (`0x21–0x7e`), excluding `#`, CR, LF, and NUL. Requests are GET or POST with an empty body and generated fixed headers; total encoded request is at most 4 KiB. Allow at most four in-flight exchanges; do not queue, and fail fast as `Overloaded` when full. No mutex is held during socket operations. + +Proposed parser caps: 8 KiB total response headers, at most 64 header fields, 512 KiB total response wire bytes, 256 KiB decoded body, at most 4,096 chunks, and at most 128 bytes per chunk-size line. Wire accumulation stops before exceeding its cap; the bounded parser checks header/count/chunk/body caps before returning a decoded response. Allocation failure is a bounded transport error. No raw request, response, socket path, or daemon error text is logged by this component. + +## HTTP framing + +Parse strict HTTP/1.0 or HTTP/1.1 status and header lines with CRLF. Reject informational responses, malformed status/header syntax, duplicate Content-Length, Transfer-Encoding combined with Content-Length, unsupported transfer/content codings, invalid chunk framing, chunk extensions, nonempty trailers, and bytes beyond the framed response. Support exactly one `chunked` transfer coding, a single valid Content-Length, or close-delimited bodies completed by EOF. For this Docker transport profile, 204 and 304 must have no transfer coding and may omit Content-Length or use Content-Length: 0 only; any body bytes are rejected. This is narrower than all general HTTP 304 metadata use. A framed response must also satisfy the connection-close exchange contract; failure to observe EOF before the deadline is an error. The transport rechecks cancellation and the injected clock/deadline after parsing and before reporting success. Never reinterpret malformed or truncated framing as a successful empty response. + +These deliberately narrow framing rules follow HTTP/1.1 message framing and parsing in [RFC 9112](https://www.rfc-editor.org/rfc/rfc9112.html). This component implements only HTTP framing and local socket transport; it does not interpret paths, response bodies/status meaning, container state, or lifecycle operations. + +## Deadlines, cancellation, and uncertainty + +Use the injected trusted monotonic clock and absolute deadlines for connect, writes, reads, and waits. Recompute remaining time after EINTR, EAGAIN/EWOULDBLOCK, and each readiness notification; do not restart the timeout. Cancellation is checked at each wait and I/O boundary. Cancellation or timeout after any request byte was written reports `request_possibly_sent=true`; callers must treat a stop outcome as unknown and inspect/reconcile rather than retry automatically. The transport rejects deadlines already expired or more than 30 seconds ahead, using the injected `IClock`. Higher layers may choose shorter budgets; this hard cap is an implementation bound, not a product latency guarantee. + +Linux AF_UNIX provides local process communication and peer credentials; `poll` readiness waits are bounded by a timeout and can be interrupted, so callers must recompute their deadline after interruptions. See Linux man-pages for [`connect(2)`](https://man7.org/linux/man-pages/man2/connect.2.html), [`unix(7)`](https://man7.org/linux/man-pages/man7/unix.7.html), and [`poll(2)`](https://man7.org/linux/man-pages/man2/poll.2.html). A nonblocking Unix socket `connect` that returns `EAGAIN` is a safe transport failure here; only `EINPROGRESS` proceeds to readiness polling and `SO_ERROR` validation. The transport is Linux-only; other platforms return an explicit unsupported result. + +## Error and response ownership + +Stable failure reasons are `InvalidTarget`, `InvalidDeadline`, `NotConfigured`, `UnsupportedPlatform`, `PeerCredentialMismatch`, `Overloaded`, `Cancelled`, `DeadlineExpired`, `ClockFailure`, `SocketFailure`, `ProtocolError`, `ResponseTooLarge`, and `AllocationFailure`. No raw errno strings or daemon response text are emitted as telemetry. Callers own interpretation of Docker status/body and operation state; transport success alone does not prove a container stopped, exited, or was fenced. + +## Required verification before implementation acceptance + +Use a fake Unix HTTP peer and injected clock/cancellation seam to verify exact request bytes; HTTP status and all three framing modes; 204/304; every byte/count bound; malformed and ambiguous framing; extra bytes; EOF truncation; cancellation/deadline at connect/write/read; EINTR/EAGAIN deadline preservation; peer UID mismatch; concurrency cap; and both `request_possibly_sent` states. Add a Linux integration probe for real `SO_PEERCRED` behavior. These checks are acceptance work, not completed evidence. diff --git a/docs/contracts/epoch-artifact-layout-v1.md b/docs/contracts/epoch-artifact-layout-v1.md new file mode 100644 index 0000000..de9d540 --- /dev/null +++ b/docs/contracts/epoch-artifact-layout-v1.md @@ -0,0 +1,50 @@ +# Epoch artifact layout v1 + +**Status:** Selected component layout; implementation verification tracked in [RG-006-F evidence](../evidence/RG-006-F.md). Sources: PRD 8 / SRD 5, HLD 5 A-03 and LLD 9 §21. These choices preserve product behavior and release gates. + +## Directory contract + +```text +/ + owner.lock + runtime-anchor.json + epoch-<32 lowercase hexadecimal digits>/ + intent.json + manifest-store/ # optional until manifest creation + owner.lock # empty + manifest.json +``` + +Epoch IDs are nonzero. Shared `epoch_layout_v1` constants and checked parse/format helpers define these exact names. Helpers do not access the filesystem or confer ownership. Root ownership remains RuntimeOwner's responsibility. + +BootstrapStore creates the epoch directory and durable intent before process start. ManifestStore creates a separate, new `manifest-store` directory after the complete observed candidate is available. It does not initialize over an existing directory or adopt an existing ACTIVE epoch. Creation/phase persistence remain separate transitions; this layout does not make them one transaction. + +Witness/journal and recovery-operation artifacts are not yet recognized. Their paths and validators must be added before those modules are integrated. An unknown directory is never accepted merely because a future feature might use it. + +## Recovery interpretation + +The recovery reader independently examines the bootstrap intent and optional manifest store. A missing manifest directory is valid for a bootstrap-only structural scan and proves no activation state. If a manifest directory was observed, missing or changed contents are uncertainty. + +The manifest directory must be owned/private 0700. Its only accepted entries are an empty, owned regular single-link 0600 `owner.lock` and an owned regular single-link 0600 `manifest.json`. Known files are opened no-follow/nonblocking. `manifest.tmp`, `intent.tmp`, unknown entries, unsafe types, wrong modes, nonempty locks, missing files and detected mutations make the scan incomplete. Safely readable known artifacts remain diagnostic evidence. + +A manifest is decoded by the existing canonical schema/checksum codec within its 4 MiB limit. The reader never calls writable store reopening or acquires a serving capability. It retains a safely decoded immutable manifest even when the intent is missing, corrupt or inconsistent, where other budgets permit. + +A matching manifest requires the exact complete BootstrapInventory ReadyCandidate, including epoch, authority incarnation, policy digest, common clock provenance and every participant identity. Canonical ordering in both codecs is role, participant ID and slot. Missing/incomplete comparison data or a difference makes the scan incomplete. All manifest phases—Prepared, Active, Draining and Closed—are metadata only. CLOSED is not independent process-exit evidence. + +Historical clock/boot provenance is retained. Checksums are corruption checks, not authentication, rollback freshness or proof of prior fsync completion. No scan result permits adoption, stop, reset or successor activation. + +## Bounded evidence and consistency + +Root and epoch entry caps remain 4,096 and 16. The manifest-store entry cap is also 16. Epoch count remains 1,024; global/per-epoch issue caps remain 256/16, with explicit truncation and incomplete output. + +All attempted intent and manifest sizes consume the same 64 MiB input budget before allocation/read. Failed reads/decodes never refund it. Both retained bootstrap and manifest participant records consume the same 16,384-record budget, including matching duplicated representations, because both models occupy memory. + +Matching records in two artifacts within one epoch are expected representations, not cross-epoch collisions. Duplicate container/process identities across epoch directories remain conflicts. Inconsistent same-epoch candidate data is also incomplete; never select the latest artifact or silently replace one with the other. + +Validate directory, lock and manifest identities, owner UID/link count/mode/size/time metadata and bounded entry listings around reads. Validate epoch/root ownership again. This detects observed changes, not an atomic filesystem snapshot or hostile same-UID mutation. + +## Verification and remaining work + +Keep all bootstrap-only reader tests. Add independent matching-phase, incomplete/mismatched-candidate, missing/corrupt intent with readable manifest, file-type/mode/link, unknown/temp/missing entry, nested-limit, mutation and shared-budget cases. Pure grammar/name tests cover lowercase/nonzero canonical IDs and round trips. Require pinned real Linux/OpenSSL clean builds and sanitizers before integration acceptance. + +Real Docker/OS control, pending-identity stop targets, durable recovery orchestration, authenticated readiness/activation, witness integration and verified successor-epoch authorization remain separate requirements. This layout does not implement or prove them. diff --git a/docs/contracts/epoch-gate.md b/docs/contracts/epoch-gate.md new file mode 100644 index 0000000..eef34e4 --- /dev/null +++ b/docs/contracts/epoch-gate.md @@ -0,0 +1,19 @@ +# RG-006 local lifecycle gate + +This first RG-006 component translates PRD-007/024/025 and SRD FR-008/022 into an internal, bounded lifecycle state machine. Its source design inputs are LLD 5 §8, §12, A-03 and LLD-08. + +## Required transitions + +A newly constructed gate does not serve traffic before validated startup. An active epoch may enter DRAINING on authority, integrity, supervision or evidence failure. Observers of DRAINING stop new commits and forwarding. Isolated participants may still act under their old ACTIVE view; their actions remain in the old epoch. + +CLOSED requires exit confirmation for every identity in the fixed old inventory. A stop request, timeout, disconnected channel, unknown process or reused PID cannot substitute for exit evidence. Identity comparisons must include the recorded process/container identity and boot/start identity. All registered participant roles remain in the inventory through closure. + +A new epoch requires completed fencing plus fresh epoch and authority identity. Loss of the supervisor or its trusted inventory never authorizes adopting an existing active epoch. No automatic same-epoch process restart is supported. + +## Component boundary + +The local gate owns lifecycle state and validates exact-identity observations from an internal process-controller boundary. Production observation must eventually bind Docker inspection and OS evidence to the persisted inventory. Deterministic fake-controller tests verify the gate's decisions. They cannot establish actual process exit, durable inventory, exclusive supervisor ownership or deployment fencing. + +The implementation must keep finite state, serialize lifecycle transitions, reject conflicting or stale evidence, and avoid external calls while holding state locks. A bounded configured inventory cannot silently grow after startup. Runtime limits and any narrower fixture constraints must be explicit implementation choices. + +The manifest store, real process controller, launch/stop ordering, trust registry integration and recovery procedure need separate implementation and acceptance evidence. Full RG-006 and Release A acceptance remain open. diff --git a/docs/contracts/history-inspector.md b/docs/contracts/history-inspector.md new file mode 100644 index 0000000..3774a64 --- /dev/null +++ b/docs/contracts/history-inspector.md @@ -0,0 +1,33 @@ +# Strict history inspection + +Source contracts are PRD revision 8, SRD revision 5 (FR-009), HLD revision 4 and LLD revision 5 §16. The executable extends the existing RG-005 component. + +This RG-005 increment exposes the existing version-1 binary reader as an offline command. It supports FR-009 evidence diagnosis. The tool reports structural evidence only; semantic quota and clock-provenance validation remain RG-011A work. + +## Invocation and input + +The executable is `rateguard_history_inspect PLAN.json HISTORY.bin`. Build it with `cmake --build build --target rateguard_history_inspect` after the repository's standard CMake configuration. Run `build/rateguard_history_inspect PLAN.json HISTORY.bin`. Both paths must be supplied explicitly. The plan comes from the trusted run configuration, independently of the history being inspected. The tool never derives its expected plan from history bytes. + +The plan is a JSON object with exactly these fields. + +```json +{ + "schema_version": 1, + "epoch_id": "00000000000000000000000000000001", + "policy_digest": "0000000000000000000000000000000000000000000000000000000000000002", + "budget_bytes": "4096", + "producers": [ + {"producer_owner": 2, "producer_index": 0, "event_capacity": "2"} + ] +} +``` + +Epoch and policy identifiers use exact-length lowercase hexadecimal. Owner is an integer from 1 through 5, following the recorder's registered owner enum. Producer index is a uint32 JSON integer. Capacity and byte budget use canonical decimal-string uint64 values, as specified for artifacts in LLD §16. Duplicate keys, unknown fields, duplicate producer identities, floating-point integers and unsupported schemas fail validation. + +The CLI limits plan input to 1 MiB before JSON parsing. This bounds this tool's configuration input. It adds no product tenant or participant limit. The existing reader checks plan arithmetic, run ceiling, expected roster, seals, checksums and complete binary extent. A plan reaching 1 GiB is invalid under the existing D6 contract. + +## Results and lifecycle + +Successful structural validation returns machine-readable JSON with schema version, complete status and published-event count. Its safety verdict is UNKNOWN. Missing files, malformed plans, truncated/corrupt histories and trailing bytes return a nonzero process status with an explicit diagnostic. + +This command reads existing artifacts. Service shutdown, output publication, retention invocation, incomplete-run summaries and semantic release acceptance remain separate runtime work. See [RG-005 evidence](../evidence/RG-005.md). diff --git a/docs/contracts/manifest-store.md b/docs/contracts/manifest-store.md new file mode 100644 index 0000000..a0176bb --- /dev/null +++ b/docs/contracts/manifest-store.md @@ -0,0 +1,29 @@ +# Durable epoch manifest store + +Source contracts are PRD 8 (PRD-007/024/025), SRD 5 (FR-008/022 and D5), and LLD 5 §8/A-03. This RG-006 increment implements local manifest serialization, atomic replacement and exclusive ownership of one configured store directory. Full supervisor and process-controller acceptance remains open. + +## Persisted record + +Schema 1 contains one immutable epoch candidate, a PREPARED/ACTIVE/DRAINING/CLOSED phase, a positive non-wrapping uint64 generation and a nonzero transition operation ID. The epoch candidate reuses the existing gate inventory and clock identity types. Participants are sorted by role and participant ID. Artifact uint64 values use canonical decimal strings; signed clock offsets use signed canonical decimal strings. Required keys and encodings are versioned and strict. + +The JSON envelope contains exactly `manifest` and `sha256`. SHA-256 covers the compact, sorted-key canonical manifest payload. Canonical encoding, exact widths, duplicate/unknown-key rejection and bounded decoding make corrupted or partial records explicit failures. The encoded file is limited to 4 MiB, an internal artifact limit shared by codec and store. The digest detects corruption; it does not authenticate an adversarially rewritten record or prove absence of historical rollback. + +## Ownership and writes + +CreateNew requires a new owner-only directory. An existing directory, even an empty one, cannot be treated as an unused epoch. OpenExisting requires its existing lock and manifest, obtains exclusive nonblocking ownership of that directory, and returns inventory for recovery inspection. Missing records never initialize default state. + +A store-directory lock cannot exclude supervisors configured with different directories. A real supervisor still needs one trusted global runtime ownership path. Lock/inventory loss or uncertainty prevents further writes on the affected handle. + +Updates compare the expected generation and digest, retain the same epoch candidate, advance generation without wrap and obey PREPARED→ACTIVE→DRAINING→CLOSED or PREPARED→DRAINING cleanup. CLOSED remains terminal. Reopening existing state never restores ACTIVE service or grants successor-epoch authority. + +A bounded temporary file is written and file-synced before atomic rename. Directory sync follows publication. Results distinguish prepublication failure from a visible update whose crash durability is uncertain. An attempted storage/integrity failure or uncertain persisted result latches the writer unavailable. Invalid caller inputs, stale caller CAS values and Busy responses do not themselves invalidate a healthy writer. Recovery requires independent fencing; a prior file is never used to resume admission automatically. Manifest and lock files are private owner-owned regular files with a single link; symlinks, extra hard links and identity replacement fail validation. + +## Verification boundary + +Developer and independent tests must cover generation/digest conflicts, unchanged inventory, interrupted writes, file/directory sync errors, missing/replaced files, locking and reopen behavior. Fake I/O tests establish transition/error handling. Real local filesystem tests establish observed write/lock behavior. Neither proves Docker process termination or power-loss durability on every storage device. + +## Launcher ordering clarification + +LLD A-03 asks for exact PID-start identity to be durably recorded before launching each participant. The PID-start identity becomes available after process creation. HLD 5 / LLD 6 A-03 resolves this with durable stopped-container launch intents followed by non-serving bootstrap and persisted exact identity before activation. The actual launcher must implement that sequence. This store accepts a complete supplied inventory; it does not satisfy that launch-order clause by itself. + +Global supervisor ownership, validated launch intents, actual OS/runtime observations, no-restart enforcement, channel closure, fenced recovery and successor activation remain full RG-006 work. diff --git a/docs/contracts/peer-authorization-v1.md b/docs/contracts/peer-authorization-v1.md new file mode 100644 index 0000000..3497165 --- /dev/null +++ b/docs/contracts/peer-authorization-v1.md @@ -0,0 +1,70 @@ +# RG-004-B2 peer authentication and authorization contract + +**Revision:** 1 · **Date:** 2026-11-17 UTC · **Status:** Selected implementation contract. Current verification is tracked in [B2 evidence](https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/evidence/RG-004-B2.md); full RG-004 remains incomplete. +**Branch:** `feature/RG-004-peer-authorization`, based on B1 head `6366df84903049fde3fd92243b3aa7bd06c43986`. +**Sources:** PRD 8 PRD-008/024; SRD 5 FR-003/D1/D2/D9; LLD 5 A-02/A-05/§17; [SEC-01–11 revision 2](https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/decisions/RG-004-security-v1.md); frozen [admission](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-certificate-registry/proto/rateguard/v1/admission.proto) and [authority](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-certificate-registry/proto/rateguard/v1/authority.proto) messages. PRD/SRD/protobuf fields are unchanged. + +## Boundary and ownership + +PeerAuthenticator consumes the real server-side gRPC AuthContext, the verified immutable CertificateRegistry and trusted wall-clock provider. It alone constructs an opaque AuthenticatedPeer. AuthorizationResolver owns the same registry, derives its policy exclusively from that snapshot and alone constructs private authorized-operation/request values. These values contain trusted principal/method/tenant/operation/cost and the applicable epoch, digest and replica identity. Authorization is not quota ALLOW, a credit allocation or a forwarding permit. + +A token belongs to the exact registry instance that created it; transfer to another instance fails closed, including byte-identical independently loaded snapshots. This is a local capability rule, not wire identity. Registry ownership survives caller input destruction and value copies/moves; no public default constructor or arbitrary-principal constructor exists. The injected wall-clock provider must outlive its authenticator/resolver; tokens do not reference that provider. + +No function creates quota state, performs RPC routing, forwards a request, debits a bucket or emits a grant. The caller's actual commitment phase is never inferred by an authentication failure. Runtime services must revalidate immediately before commit/pregrant/preforward in later integration. + +## Transport authentication + +Production callers must supply ServerContext::auth_context() from the trusted gRPC connector. Never manufacture it from request data or install an AuthMetadataProcessor that rewrites the protected TLS/URI/leaf properties. Synthetic contexts are internal test seams, not evidence of a real handshake. + +Require IsPeerAuthenticated() and exactly one of each property: + +| Property | Required value/bound | +| --- | --- | +| transport_security_type | Exact `tls`, the pinned experimental TLS connector's type | +| peer_uri | Exact registered ASCII URI, 1–256 bytes, no NUL | +| x509_pem_cert | One strict public leaf PEM, at most 64 KiB; no NUL or unrelated prefix/trailing data | + +Reject missing/ambiguous/malformed metadata. Do not use request headers, CN, GetPeerIdentity(), SPIFFE convenience properties or certificate-chain PEM as identity fallbacks. Decode the leaf, hash its DER with SHA-256 and match the registry's exact URI/pin. The registry already validated that exact certificate's role, profile and SAN. + +At every Authenticate invocation, sample trusted UTC and require healthy time plus root and selected peer validity `notBefore <= now < notAfter`. Resolver samples again on every Resolve, preventing reuse of an authenticated token after expiry. Check the selected caller, not every unrelated principal. Failure latches/fencing remain the clock/service/supervisor responsibilities; no instantaneous epoch-wide stop is implied. + +Pinned primary evidence: [AuthContext API](https://github.com/grpc/grpc/blob/v1.51.1/include/grpcpp/security/auth_context.h), [property constants](https://github.com/grpc/grpc/blob/v1.51.1/include/grpc/grpc_security_constants.h), [TLS connector](https://github.com/grpc/grpc/blob/v1.51.1/src/core/lib/security/security_connector/tls/tls_security_connector.cc), [property population](https://github.com/grpc/grpc/blob/v1.51.1/src/core/lib/security/security_connector/ssl_utils.cc). Leaf availability on reconnect/resumption still requires separate evidence; absence fails closed. + +## Authorization and binding + +| RPC | Caller and policy gate | Trusted result | +| --- | --- | --- | +| Admission.CheckAdmission | Adapter; permitted configured tenant/operation; either immutable epoch mode | Cost from policy; exact attempt/epoch/digest binding | +| Authority.StrictCheck | Replica with a registered fixed slot/incarnation; permitted pair; STRICT policy only | Cost and replica identity from policy; request has no slot field | +| Authority.AcquireCredit | Replica with permitted pair; CREDIT policy only | Exact request slot/incarnation, nonzero sequence and configured trigger cost | + +Authority principals are server identities and cannot call these methods. Resolve selectors against known immutable tenant/operation records, then their permission pair. Never insert unknown records. Enforce ASCII identifier syntax, 16-byte attempt/epoch/incarnation IDs, 32-byte digest, exact active request epoch/digest and the existing 16 KiB decoded-message cap. AcquireCredit's slot/incarnation must equal the authenticated replica's configured identity; its trigger cost must exactly equal policy cost. CheckAdmission has no supplied-cost field; unknown protobuf fields and metadata cannot override policy cost. Preserve frozen wire fields and enum values. + +## Selected error interpretations + +These implementation defaults close unspecified per-request classifications without changing release/product behavior: + +| Condition | Disposition | +| --- | --- | +| Missing/untrusted/ambiguous transport identity, wrong leaf pin, expired/not-yet-valid credential, token from another registry | UNAUTHENTICATED | +| Recognized caller with wrong method role or configured but unauthorized pair | PERMISSION_DENIED | +| Unknown tenant/operation, malformed fields/widths, stale request epoch/digest, incorrect credit slot/incarnation/cost, zero sequence, method/mode mismatch | INVALID_ARGUMENT | +| Clock trust loss or internal configuration/crypto/resource dependency failure | Application UNAVAILABLE on gRPC OK | + +Request-binding errors follow the verified RG-001 validation helpers. The method/mode gate is an explicit fail-closed default: StrictCheck cannot implement a credit fallback, and AcquireCredit cannot allocate in a strict epoch. There is no caller-supplied mode or adaptive grant choice. + +The 16 KiB transport receive limit is enforced before decoding by future server wiring; its gRPC RESOURCE_EXHAUSTED is distinct from the defense-in-depth post-decode INVALID_ARGUMENT check. B2 failure objects contain only bounded reasons/dispositions. Future handlers preserve actual NotCommitted/Possible/Committed phase, never refund, and must not turn dependency failure into LIMITED. INVALID/UNAUTHENTICATED enum values remain frozen but are not emitted as successful decision responses. + +## Acceptance and evidence + +| ID | Required evidence | +| --- | --- | +| B2-AC01 | Actual mTLS RPC exposes the required properties and validates registered URI/leaf pins; negative identities never reach the fixture state port. | +| B2-AC02 | Positive adapter/replica mapping and negative role/pair/epoch/digest/slot/incarnation/cost/mode cases match the table, with zero state-port calls on rejection. | +| B2-AC03 | Fake trusted UTC crosses root/leaf validity on an established TLS connection; verification count/connection evidence excludes a new handshake. Cached-token Resolve also rejects expiry. | +| B2-AC04 | Opaque construction, copies/moves/input lifetimes, metadata/payload caps and bounded reason-only failures are verified; PEM/keys are never diagnostic output. | +| B2-AC05 | Independent expected permission/cost fixtures and separately compiled unsafe variants detect widened permission/cost or pin checks; normal positive controls pass first. | + +Senior owns transport extraction; Junior owns resolver implementation; Tester owns independent fixtures/spy/defect checks; Master integrates and records exact CI evidence. Synthetic policy variants may grant a replica a pair, but the original policy-v1 golden fixture remains unchanged. + +Full RG-004 AC01 needs service integration; AC02 still needs precommit/preforward, reconnect/resumption and fenced rotation; AC03 needs real event/export privacy. Supervisor, quota service, deployment and all numerical release gates remain open. diff --git a/docs/contracts/pinned-client-v1.md b/docs/contracts/pinned-client-v1.md new file mode 100644 index 0000000..84eeba4 --- /dev/null +++ b/docs/contracts/pinned-client-v1.md @@ -0,0 +1,80 @@ +# RG-004-B3 pinned client and validity-guard contract + +**Revision:** 1 · **Date:** 2026-11-17 UTC · **Status:** Selected implementation contract. Current delivery/evidence is tracked in the [live work log](https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/SCRUM-WORK-LOG.md). +**Branch:** `feature/RG-004-client-guards`, based on verified B2 head `20210d5fbabcd891dbbb20ab89eca26f3a73a1db`. +**Sources:** PRD 8 PRD-008/024; SRD 5 D1/D2/D6/D9 and FR-003; LLD 5 A-02/A-05/§17; SEC-01–11 revision 2. Requirements/protobufs are unchanged. + +## Scope and owners + +B3 supplies a stateless certificate/time guard, a sealed typed gRPC client, and separate reconnect/resumption evidence. Junior owns ClientCallGuard; Senior owns PinnedPeerRpcClient; Tester independently owns real TLS and native session qualification; Master records decisions, integrates and verifies. + +No function commits quota, allocates credits, forwards a request, rotates credentials, fences processes or asserts an active epoch. Actual service dispatch/precommit/pregrant and adapter ALLOW/deadline/preforward composition remain with their service stories. Trusted clock providers must outlive guards/clients. + +## Guard and proof semantics + +Create one immutable guard binding from a B1 CertificateRegistry, trusted wall clock, local URI, expected server URI and purpose: + +| Purpose | Local role | Exact expected server role | +| --- | --- | --- | +| AdapterToReplicaAdmission | Adapter | Replica | +| ReplicaToAuthority | Replica | Authority | + +Validate registry/policy epoch, authority identity, root digest and canonical digest. Resolve URIs only through immutable policy/registry; never from headers. Require bounded ASCII URIs and exact registered identities, including replica slot/incarnation provenance. + +ValidateBeforeCall samples healthy-before/Now/healthy-after, checks a legal integer UTC tuple, and requires root, OWN client leaf and selected server leaf validity `notBefore <= now < notAfter`. Private PreparedClientCall retains the exact guard binding. ValidateBeforeForward repeats current checks, rejects foreign bindings and a sample earlier than the prepared sample, and returns only a fresh time-validation proof. + +Proofs use shared immutable payloads with exception-safe complete copies/assignments; rvalues do not detach ownership. They do not imply a timely ALLOW, known commitment, active epoch or forwarding eligibility. Guard failures contain bounded local CredentialInvalid/ApplicationUnavailable classifications, no gRPC status, secret text or inferred commitment. + +## Sealed client construction + +PinnedPeerRpcClient constructs its TLS credentials, channel and generated stubs internally. It exposes no raw credentials/channel/stub or arbitrary RPC callback. Configuration fixes one target, purpose, local principal and expected server for the object's lifetime. + +Root/leaf/private-key PEM inputs are individually capped at 64 KiB. Parse exactly one matching object with only surrounding whitespace, no NUL/extra blocks. Bind root and local leaf DER SHA-256 to the B1 registry; verify the local private key is present and matches the leaf. Reject encrypted keys without a password callback/prompt. Root signing keys are never inputs. Configuration and crypto failures expose bounded reasons only; key/cert text and OpenSSL diagnostics never enter logs/artifacts. + +Construct ordinary chain verification plus PinnedPeerVerifier for the exact expected server URI/role/leaf pin. Use static in-memory credentials, a private local subchannel pool, retry=0 and hedging=0. No caller-supplied channel arguments, service fallback, alternative server or session-cache option is accepted. + +Implementation bounds: send/receive messages and metadata each 16 KiB. These are finite client limits, not measured capacity. Caller deadlines must be finite and future; Authority StrictCheck/AcquireCredit use `min(caller deadline, now + 20 ms)` per D6. Admission uses the supplied finite deadline; the 50 ms benchmark deadline is not silently made a universal API maximum. gRPC transport deadlines do not replace the actual quota transition's shared CLOCK_MONOTONIC checks. + +## Exact-once invocation and raw results + +Public methods are CheckAdmission, StrictCheck and AcquireCredit. Enforce purpose and immutable mode: admission supports either epoch mode; StrictCheck requires STRICT; AcquireCredit requires CREDIT. Each method performs fresh preflight and invokes the generated stub at most once. No automatic strict retry, hedging or mode fallback exists. + +Return one of: + +- **NotSent:** stub was never invoked for this attempt, with no fabricated gRPC status/response. This establishes NotCommitted only for this attempt; it cannot erase a caller's earlier commitment. +- **Invoked:** preserve raw gRPC status when available, raw response and private prepared proof. These are not trusted ALLOW/grant/commitment results. An exception after stub entry remains Invoked with uncertain transport state. + +Allocate invocation storage before stub entry; after invocation, publication/failure handling must not allocate a replacement that could falsely return NotSent. One immutable payload prevents copy failure from mixing response/proof generations. Post-response trust failure never discards or rewrites the raw reply. + +The client's ValidateBeforeForward checks only certificate/time binding for its adapter invocation. The adapter must separately require valid response correlation, timely ALLOW, active epoch and its actual forwarding gate. This API never forwards. Local downstream trust failure becomes dependency unavailability at the caller's service boundary, not a forged server UNAUTHENTICATED response or quota LIMITED. + +## Reconnect and session qualification + +Production channels omit session caching. The pinned v1.51.1 source configures client cache behavior only with an explicit cache argument; qualification must independently verify no-cache fresh reconnect behavior. + +A test-only native fixture may attach one bounded LRU entry using grpc_ssl_session_cache_create_lru/create_channel_arg and ChannelArguments::SetPointerWithVtable. Keep registry, target/SNI and credentials fixed while creating a distinct local-pool transport; retain cache ownership, close old channel/stub and keep server alive. Same-channel RPC reuse is not TLS resumption. + +Record new transport/endpoint, verifier counts and actual GRPC_SSL_SESSION_REUSED_PROPERTY on both sides, plus required peer URI and leaf PEM/pin evidence. Full-chain PEM is not a substitute: OpenSSL can omit it on resumed sessions. + +| Qualification state | Interpretation | +| --- | --- | +| QUALIFIED | Actual new transport reports reuse=true and exact leaf/pin verification remains demonstrated | +| NOT_DEMONSTRATED | Bounded attempts did not establish actual resumption; never count as passing enablement | +| UNSAFE / insufficient identity evidence | Fail closed; resumed path stays disabled and cannot be claimed | + +No-cache fresh/forced-reconnect checks are required passing tests. A diagnostic collection step can succeed while reporting NOT_DEMONSTRATED; evidence must retain that distinction. Session caching remains unavailable through the production factory, even if the SDK probe qualifies it. Enabling production resumption needs explicit subsequent review/change control. + +Primary sources: [cache C API](https://github.com/grpc/grpc/blob/v1.51.1/include/grpc/grpc_security.h), [channel arguments](https://github.com/grpc/grpc/blob/v1.51.1/include/grpc/impl/codegen/grpc_types.h), [TLS credentials cache consumption](https://github.com/grpc/grpc/blob/v1.51.1/src/core/lib/security/credentials/tls/tls_credentials.cc), [TSI session implementation](https://github.com/grpc/grpc/blob/v1.51.1/src/core/tsi/ssl_transport_security.cc), [auth property mapping](https://github.com/grpc/grpc/blob/v1.51.1/src/core/lib/security/security_connector/ssl_utils.cc). + +## Acceptance and limits + +| ID | Required evidence | +| --- | --- | +| B3-AC01 | Independent root/client/server validity boundaries, clock failure/invalid/backwards samples, exact binding and immutable proof lifetimes | +| B3-AC02 | Actual sealed client calls at both endpoint roles; local expiry/trust/method/deadline failures are NotSent with unchanged handler count | +| B3-AC03 | Exact-once stub invocation, raw transport/reply retention and fresh post-response time rejection without invented forwarding/commitment | +| B3-AC04 | Forced fresh reconnect and endpoint substitution verify exact pins; missing/changed leaf identity fails closed | +| B3-AC05 | Versioned session probe distinguishes QUALIFIED from NOT_DEMONSTRATED/UNSAFE using actual session metadata; production cache remains disabled | +| B3-AC06 | Real crypto/config bounds and key mismatches, independent defect controls, normal/clean Linux tests and targeted sanitizers | + +Full RG-004 AC01–03, deployment, real event/export privacy, actual commit/forward/fencing, performance and formal-assurance gates remain open. No benchmark, implementation beyond this input, or production-readiness claim is implied. diff --git a/docs/contracts/policy-v1.md b/docs/contracts/policy-v1.md new file mode 100644 index 0000000..3ea68e6 --- /dev/null +++ b/docs/contracts/policy-v1.md @@ -0,0 +1,84 @@ +# Canonical policy v1 — implementation decision record + +**Revision:** 1 · **Date:** 2026-11-12 · **Decision owner:** Master technical lead +**Status:** Frozen for RG-002 implementation and independent verification. +**Sources:** PRD 8; SRD 5 D3/D6/D9; LLD 5 §§4,5,16.4,17. This fixes representation/startup limits, not a new quota algorithm or release gate. + +## Accepted decisions + +An epoch has one immutable mode (strict or credit), authority incarnation, trust-root fingerprint and registered replica set. Tenant buckets initialize **full B**, already specified by LLD §5; there is no configurable initial-balance override. Replay initial state is a separate artifact. + +Slot IDs are unique uint32 identities, with at most eight entries; they need not be contiguous or zero-based. Policy/transport compares configured membership and exact incarnation. The CA root is bound by SHA-256 of its DER certificate, not PEM formatting or private material. RG-004 must verify the actual CA matches this fingerprint before readiness. + +The loader accepts table/object order variation and sorts validated records for encoding. It rejects duplicates rather than overwriting or silently collapsing them. JSON uint64 values are canonical decimal **strings** and never pass through floating point. + +## Bounds and startup rejection + +Existing limits remain: 1..10,000 tenants, 1..8 registered replica slots, identifier length 1..128 ASCII [A-Za-z0-9_.-], B/r 1..10^9, operation cost 1..B, and credit Q between maximum operation cost and B. Every tenant has at least one operation. + +Additional finite v1 implementation limits are: 64 operations/tenant; 100,000 operations total; 10,000 principals; 100,000 permission pairs total; 256 ASCII bytes per principal URI; 64 MiB JSON input and canonical output; JSON nesting depth 32. These are independent ceilings, not a promise that every maximum-sized combination fits. Exceeding any limit rejects configuration before epoch readiness or quota-state creation. The values cover the frozen benchmark policies while bounding parser/registry memory. Raising them requires explicit configuration-schema review and new boundary evidence. + +## JSON schema + +All listed fields are required except credit_batch_units (required only in credit mode) and principal slot_id (required only for replica role). Unknown fields, duplicate keys, float/bool integer fields, trailing non-whitespace data and unsupported schema versions reject the whole input. + +```text +root: schema_version=1, mode="strict"|"credit", epoch_id, + authority_incarnation, trust_root_sha256, + replica_slots[], tenants[], principals[] +slot: slot_id (JSON uint32 integer), incarnation_id +tenant: tenant_id, capacity_units, rate_units_per_second, + [credit_batch_units], operations[] +operation: operation_id, cost_units +principal: uri, role="adapter"|"replica"|"authority", [slot_id], + permissions[] +permission: tenant_id, operation_id +``` + +Epoch/incarnation fields are exactly 32 lowercase hexadecimal characters (16 bytes); root fingerprint is 64 lowercase hexadecimal characters (32 bytes). All uint64 fields are decimal strings matching 0|[1-9][0-9]*, then range checked. schema_version and slot_id are nonnegative JSON integers, with no float conversion. + +Principal URIs follow the accepted A-02 identities: +- adapter: spiffe://rateguard.local/adapter/ +- replica: spiffe://rateguard.local/replica// +- authority: spiffe://rateguard.local/authority/ + +Require at least one adapter, exactly one authority, and exactly one replica principal per registered slot. Replica URI, slot_id and incarnation must agree. Authority URI must match the root authority incarnation. URI identities are unique and compare exactly. Adapter/replica permissions reference existing tenant/operation pairs and may be empty (deny all); authority permissions must be empty. Each principal has one role. Supervisor Unix peer-credential identity is manifest-owned, not an invented mTLS principal role. + +Strict tenants omit credit_batch_units; credit tenants provide it. Strict-mode replicas still have inventory/identity records, but no local quota credits. + +## Canonical bytes + +Unsigned integers are big-endian fixed-width values. str means u32 byte length followed by ASCII bytes. The digest is SHA-256 of all bytes below; the digest is not embedded in the input. + +```text +u32 schema_version (=1) +u32 mode (STRICT=1, CREDIT=2) +16 bytes epoch_id +16 bytes authority_incarnation +32 bytes trust_root_sha256 +u32 slot_count + slots sorted by numeric slot_id: + u32 slot_id; 16 bytes incarnation_id +u32 tenant_count + tenants sorted by ASCII tenant_id: + str tenant_id; u64 capacity_units; u64 rate_units_per_second + u8 q_present (0 strict, 1 credit); [u64 credit_batch_units if 1] + u32 operation_count + operations sorted by ASCII operation_id: + str operation_id; u64 cost_units +u32 principal_count + principals sorted by ASCII uri: + str uri; u32 role (ADAPTER=1, REPLICA=2, AUTHORITY=3) + [u32 slot_id only for replica] + u32 permission_count + permissions sorted by (tenant_id, operation_id): + u32 tenant_index; u32 operation_index +``` + +Indices are zero-based positions in the canonical tenant table and that tenant's canonical operation table. JSON supplies names, never indices. All lengths/counts and output growth are checked before appending; no narrowing/wrap is permitted. Permissions and IDs are checked before producing bytes or a digest. Immutable snapshots preserve ownership for returned views and never create entries for unknown lookups. + +The current implementation only needs JSON loading plus Encode/Digest. A future binary decoder must reject noncanonical order, unsupported versions, truncation and trailing bytes; no decoder or extension support is claimed here. New policy fields require a new canonical schema version. + +## Required independent evidence + +A separate Python encoder computes aggregate golden bytes and SHA-256 from the JSON schema; it must not call the C++ codec. Verify order invariance, each identity/authorization/quota field's effect on the digest, duplicate/unknown references, slot/incarnation/URI mismatch, strict/credit Q presence, numeric boundaries, resource caps, malformed/deep input and fail-closed crypto errors. This record does not claim those checks or the policy implementation already exist. diff --git a/docs/contracts/strict-event-history.md b/docs/contracts/strict-event-history.md new file mode 100644 index 0000000..aed8eda --- /dev/null +++ b/docs/contracts/strict-event-history.md @@ -0,0 +1,25 @@ +# RG-005 strict history recorder + +This increment provides opt-in event recording for Release A correctness runs. FR-009, FR-010 and NFR-008 require stage ownership, bounded storage and visible evidence loss. Performance runs keep aggregate metrics and leave detailed recording disabled by default. + +## Run budget + +At startup the run owner assigns a fixed number of slots to each expected producer. Validate the entire plan using checked arithmetic. The sum of the header, producer metadata, all slot allowances and terminal records must stay below 1 GiB. A plan reaching 1 GiB fails before slot allocation because D6 would invalidate the resulting correctness run. A smaller test budget permits an exact fit. Partitions cannot borrow slots from another producer. Exhausting one partition ends collection for the run, even if another partition has space. This trades utilization for an upper bound that can later be enforced across processes without a network call on each reservation. + +## Reservation and evidence + +Reserve before a state transition. A producer publishes each reservation once, using the immutable attempt identity and the monotonic timestamp supplied by the stage owner. The generator owns offered records, the authority owns strict decisions, the replica owns responses, the adapter owns receipt and forwarding, and the backend owns completion. Keep arbitrary request bytes, certificates and credentials out of records. Local spend and grant events belong to Release C. + +Quiesce producers before taking a final snapshot. Compare it to the independently supplied expected roster and epoch/policy binding. A gap, unfilled reservation, corrupted checksum, missing producer or missing seal makes the evidence incomplete. A structurally complete snapshot still requires a separate semantic checker. No recorder failure may undo a committed debit. + +## Version 1 binary format + +Integers use big-endian encoding. The 80-byte header contains the eight ASCII bytes `RGHIST01`, schema version (4), epoch ID (16), policy digest (32), producer count (4), encoded size (8) and budget (8). Producers appear in ascending (owner, index) order. + +Each producer has a 13-byte envelope (owner, index, capacity), a 51-byte record for every allocated slot, and a 26-byte seal (sealed, incomplete, reserved count, published count, checksum). Each slot carries status, local sequence, stage, outcome, attempt ID, monotonic time, cost and checksum. The 17-byte trailer contains the completion flag, encoded size and run checksum. The extent is `97 + 39 × producers + 51 × total slots` bytes. Fixed-width FNV-1a checksums detect accidental corruption. Files belong in a private synthetic-history directory. + +The exporter accepts a quiescent, structurally complete snapshot and an independent run plan. The offline reader requires the same plan, rejects trailing bytes and truncated files, and validates all seals before returning evidence. A failed write or incomplete snapshot cannot produce a successful export result. A complete structure alone establishes neither quota safety nor clock provenance. + +## Integration boundary + +The generator, adapter, authority, replica and backend must supply their own events. A supervisor must bind producer ownership, propagate stop signals across processes and reject runs with missing participants or evidence. Seven-day cleanup applies to managed final and partial regular files in the private output directory. Run-level acceptance requires the real services. See the [LLD](../LLD.md) and [story criteria](../STORIES.md#rg-005). diff --git a/docs/decisions/RG-004-security-v1.md b/docs/decisions/RG-004-security-v1.md new file mode 100644 index 0000000..5e9234a --- /dev/null +++ b/docs/decisions/RG-004-security-v1.md @@ -0,0 +1,57 @@ +# RG-004 security decisions — revision 2 + +**Date:** 2026-11-16 · **Decision owner:** Master technical lead +**Status:** Selected v1 defaults. RG-004-A/B1/B2/B3 component inputs independently accepted, including client guards and scoped native SDK reconnect/resumption qualification. Actual runtime service commit/forward, credential provisioning, fenced rotation and epoch/deployment integration remain pending; full AC01–03 remain open. +**Sources:** PRD 8; SRD 5 D1/D2/D9; LLD 5 A-02 / §§9,16,17; [policy-v1](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-002-policy-arithmetic/docs/contracts/policy-v1.md). +**Review:** Senior Dev performed requirements extraction and pinned-source review; Master selected the defaults below. This record adds internal configuration/provisioning detail without changing canonical policy-v1 or release gates. + +## Decisions and rationale + +| ID | Selected behavior | Reason / verification owner | +| --- | --- | --- | +| SEC-01 | One epoch-scoped CA and one immutable leaf/key per process. Add an immutable certificate registry to the supervisor manifest: registered URI/role → SHA-256 of that leaf's DER. Bind the registry to epoch/authority/slot incarnations and validate before readiness. Keep the existing CA DER hash in policy-v1; do not add fields to its frozen encoding. | Exact leaf identity enforces no in-epoch replacement and permits safe cached validity checks. Senior Dev implements; Tester verifies startup mismatches and stale leaves. | +| SEC-02 | Replica leaf has clientAuth and serverAuth; adapter leaf clientAuth; authority leaf serverAuth. Default generated profile: EC P-256 / SHA-256, root CA=true with pathLen=0 and certificate-signing usage; leaf CA=false with digitalSignature. All purposes, strict chain constraints and validity must pass. Only one root plus directly signed leaf is supported in v1. | Replica has both TLS roles. Direct issuance avoids an unspecified intermediate-chain/provisioning feature. Do not infer a role from CN. | +| SEC-03 | Exactly one URI SAN, matching a registered URI byte-for-byte; reject duplicate/ambiguous URI SANs, embedded NULs, unknown identities and malformed values. Other SAN types cannot supply RateGuard identity. Enforce registry leaf hashes for clients and servers at both trust boundaries. | Deterministic identity, no arbitrary SAN selection or CA-signed unregistered peer. | +| SEC-04 | An adapter→replica call requires adapter role and permission for its tenant/operation. A replica→authority call additionally requires the replica's own allowed pair, fixed slot/incarnation, epoch and digest. Resolve cost from immutable policy and reject a supplied mismatch. | Every boundary checks its own caller; upstream authorization cannot widen a replica's scope. Unknown selectors never create quota state. | +| SEC-05 | Pin the selected replica's exact URI and leaf hash per adapter channel; pin the authority URI/incarnation and leaf hash per replica channel. Configuration comes from the trusted registry, never a request header. Preserve ordinary TLS chain/cryptographic verification alongside the custom verifier. | Prevents accepting another registered service merely because it shares the CA. | +| SEC-06 | Trusted wall time is an internal dependency. Production uses CLOCK_REALTIME and read-only adjtimex status; TIME_ERROR, STA_UNSYNC, STA_CLOCKERR, read/syscall failure or observed backwards time fails closed and latches trust loss in that component instance. Service integration must mark the participant unready, notify RG-006 and complete epoch fencing before restart; this port does not prove instantaneous epoch-wide stop. The controlled VM, time authority and privileged operator are trusted; synchronization is a deployment precondition. | X.509 needs UTC, not quota CLOCK_MONOTONIC. This cannot detect an inaccurate but steadily advancing UTC source or prove hostile-host integrity. Actual VM preflight must pass before activation. | +| SEC-07 | Certificate validity is notBefore ≤ now < notAfter, checked for root and leaf. Server revalidates caller identity/validity/authorization at dispatch and immediately before quota/grant commit; the client wrapper validates its pinned server record before each call, and the adapter again before forwarding a received ALLOW. Expiry/trust failure before commit does not charge. | Covers queueing, reused connections and late responses. A post-commit error never reverses debit or authorizes a refund. Tests use an injected internal trusted-wall-time source. | +| SEC-08 | A channel wrapper owns the immutable expected server certificate metadata. The TLS custom verifier requires the actual peer leaf's DER hash to match that record, including on reconnect; wrapper checks therefore do not depend on ClientContext peer-leaf availability at PRE_SEND. Missing/malformed peer certificate or pin mismatch rejects TLS verification. | Resolves an unverified gRPC interceptor assumption without trusting a stale identity from another connection. Cached public metadata is not authentication by itself; successful mTLS and verifier checks remain required. | +| SEC-09 | Malformed request → INVALID_ARGUMENT; absent/untrusted/unregistered certificate identity → UNAUTHENTICATED; authenticated wrong role/pair → PERMISSION_DENIED. Clock trust loss means service unavailable, not quota LIMITED. Pre-commit failures are NotCommitted. The clock primitive itself returns only a bounded reason: callers must explicitly map the actual operation phase to NotCommitted, Possible or Committed. A post-ALLOW clock failure blocks forwarding but cannot erase a known debit or permit a refund. | Preserves D1/D2. TLS handshake rejection may occur before any RPC/status exists; do not promise a structured gRPC authentication result for it. Transport loss after dispatch may be Possible commitment. | +| SEC-10 | No online revocation/live rotation. Close channels and positively fence the old epoch before replacing registry, CA or leaves. Private keys/root signing material stay outside the repository/run artifacts; root signing key is not mounted into admission/authority processes. Never log/export full certificates, credentials or keys. | Matches immutable epochs and existing retention/security scope. | +| SEC-11 | Resumed/reconnected sessions must still provide enough peer leaf metadata to verify the exact pin. Missing metadata fails closed. If target SDK/session behavior cannot satisfy this, reject that resumption path; availability/performance is not assumed. | No permissive fallback to URI-only or cached unverifiable handshake identity. Compatibility must be demonstrated before enabling the path. | + +## Pinned API evidence and remaining prototypes + +Initial source review identified support in **gRPC C++ v1.51.1**: experimental ExternalCertificateVerifier, TlsChannelCredentialsOptions and TlsServerCredentialsOptions expose URI SANs and peer leaf PEM. The custom verifier runs after TLS handshake before peer-check completion; rejection prevents proceeding to RPC dispatch. Full-chain PEM is not guaranteed. Keep server-certificate verification enabled and server client-certificate request policy REQUIRE_AND_VERIFY. + +Primary sources: [certificate verifier API](https://github.com/grpc/grpc/blob/v1.51.1/include/grpcpp/security/tls_certificate_verifier.h), [TLS credentials options](https://github.com/grpc/grpc/blob/v1.51.1/include/grpcpp/security/tls_credentials_options.h), [TLS connector population and peer check](https://github.com/grpc/grpc/blob/v1.51.1/src/core/lib/security/security_connector/tls/tls_security_connector.cc), [adjtimex states and flags](https://man7.org/linux/man-pages/man2/adjtimex.2.html). + +Before security component acceptance, require: + +1. Compile/link the selected experimental APIs against the frozen Ubuntu package toolchain; prove exact wrong-URI/wrong-leaf/unknown-CA rejection before a test RPC handler executes. +2. Prove fresh, reused and resumed channel behavior, including leaf availability or deliberate fail-closed rejection, cached root/leaf expiry, and reconnect pinning. +3. Exercise incoming/outgoing role/EKU/permission checks, certificate/epoch/slot mismatch, spoofed selectors and queue-time expiry with an independent test matrix; no test-only public RPC. +4. Validate immutable manifest registry serialization/digest binding, startup consistency and fenced replacement with RG-006; do not silently change policy-v1. +5. Run read-only adjtimex plus real-time preflight in the actual Docker Linux VM. If unsupported or unsynchronized, enforcement remains unavailable; fake-clock unit tests do not pass deployment. +6. Keep implementation/test scope separate from quota service activation and product performance gates. The cost of per-call checks must be measured with witness/service integration. + +No remaining behavior is delegated to an unrecorded default. Prototype/operating evidence above is still required, and this document does not claim secure provisioning or runtime PKI exists. + +## Revision history + +- **Revision 2 (2026-11-16):** Senior review corrected the Master-assigned primitive commitment contract: operation commitment belongs to the caller, including after ALLOW. Clarified that the port's sticky trust-loss state is local; participant readiness and epoch-wide fencing remain service/supervisor integration. No PRD/SRD gate, canonical policy encoding, or quota algorithm changed. +- **Revision 1 (2026-11-13):** Selected SEC-01–11 before compatibility implementation; source research did not claim a compiled TLS or deployment result. + +## Current evidence status (2026-11-16) + +[PR #9](https://github.com/kshiteesh28/DistributedRateGuard/pull/9) and [run 43980308204](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43980308204) close the initial compile/handshake compatibility prerequisite: exact URI/leaf pin rejection before handler execution, positive TLS controls, independent bypass detection and trusted UTC primitive checks passed. [Restricted Docker observations](../evidence/RG-004-A/docker-time-43980308204.json) matched; they are not actual service topology or epoch activation evidence. Items 2–4 and live-service/deployment parts of 5–6 remain open. Historical feature-branch copies precede this evidence update; the selected SEC-01–11 behavior is unchanged. + +## B1/B2 implementation evidence update (2026-11-17 UTC) + +[B1 evidence](../evidence/RG-004-B1.md) verifies typed certificate-registry validation. [B2 evidence](../evidence/RG-004-B2.md) verifies actual TLS peer extraction, fresh dispatch/resolver expiry, policy binding/cost/permission checks and selected compiled unsafe variants. [B2's implementation contract](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-peer-authorization/docs/contracts/peer-authorization-v1.md) records exact request/status interpretations and the trusted-gRPC-context construction assumption. These inputs do not close full security component items 2–6: client guards, real commit/forward, reconnect/resumption, manifest/fenced replacement, actual service deployment and real export/retention remain separately gated. SEC-01–11 behavior, policy-v1 encoding and PRD/SRD release requirements are unchanged. + + +## B3 implementation evidence update (2026-11-17 UTC) + +[B3 evidence](../evidence/RG-004-B3.md) and [run 44128491936](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44128491936) verify the outgoing root/own-client/expected-server time guard, sealed typed client, reused-channel expiry and pre-forward recheck primitive. Separate SDK qualification observed actual resumption on a new transport with exact leaf pins and fresh verifier calls on both sides. Production session caching remains disabled. Prototype items 2–3 have scoped fixture evidence; actual commit/forward, manifest/fenced rotation, live-service Docker topology, provisioning and export privacy remain open. This update does not change SEC-01–11 or close full RG004 AC01–03. diff --git a/docs/evidence/RG-001.md b/docs/evidence/RG-001.md new file mode 100644 index 0000000..ca7bf8b --- /dev/null +++ b/docs/evidence/RG-001.md @@ -0,0 +1,31 @@ +# RG-001 acceptance evidence + +**Status:** Component acceptance passed; PR review pending. No main-branch merge. +**Sources:** PRD 8 / SRD 5 / HLD 4 / LLD 5. +**PR:** [#5](https://github.com/kshiteesh28/DistributedRateGuard/pull/5). + +## Verified revision and runs + +The final code and frozen dependency lock were checked at head `4c924495a1303054a2c3b26edfae757430ea4d72` in [run 43327798021](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43327798021). GitHub tested merge ref `691523ebc9727417cf5efc82d87592b4aafde8c7`. The [observed manifest snapshot](RG-001/manifest-43327798021.json) retains its original frozen-pending status; the checked-in lock was promoted only after that run passed. + +- **12 Python verifier tests passed:** candidate/missing values, version drift, validation flags, failed builds, C++ standard drift, and absent compilation evidence fail closed. +- **Five CTest checks passed in each of two clean build directories:** generated code smoke, generated API/validation contracts, transport errors, channel policy, and retry behavior. +- All **12 generated files matched** between clean builds. +- Manifest comparison verified the exact recorded primary dependency/tool versions, Ubuntu OS/architecture, and actual **C++20 flags across 11 project translation units**. +- The retry fixture demonstrated four application calls with configured retries enabled, versus one with enforcement channel arguments. It uses a synthetic loopback service, not a quota service. + +## Acceptance criteria + +| Criterion | Disposition and scope | +| --- | --- | +| RG-001-AC01 | PASS for generated wire contracts and validation helpers. Seven protobuf golden fixtures, enum/field descriptors, optional presence, unknown/zero enums, malformed wire, request bounds, trusted configuration matching and exact slot/incarnation checks passed. Fake-port ordering is component evidence; real RPC/state integration remains RG-008. Aggregate policy encoding/digest vectors belong to RG-002. | +| RG-001-AC02 | PASS for the recorded primary Ubuntu contract toolchain. Exact package versions, compiler/CMake/Ninja/protoc and build commands are frozen and checked. Clean rebuild and deterministic generated-file comparison passed. This is not hermetic/transitive-OS or bit-for-bit binary reproducibility. | +| RG-001-AC03 | PASS for transport contracts. Commitment/status helpers, actual retry/hedging channel arguments, invalid factory inputs and the retry-enabled control versus disabled policy passed. RG-008 must wire the real client to this factory and test its application-level uncertainty/failure paths. | + +## Independent review and limitations + +Scrum Master reviewed readiness and scoped acceptance; Senior Dev reviewed build integration; Junior Dev authored schemas/helpers; Tester independently inspected fixtures, request/identity binding, retry behavior and CI evidence. Review findings were fixed before acceptance. + +The earlier all-target source build timed out at 45 minutes before product tests. The default contract lane now uses exact recorded Ubuntu packages; the optional source-build lane remains unverified. This does not change the quota contract. + +No quota handler, mTLS runtime, shared-clock provenance, supervisor/witness, backend forwarding, benchmark, state-machine model, or release A/B/C acceptance is claimed by this component result. These remain in their assigned stories. See [build instructions](../build.md). diff --git a/docs/evidence/RG-001/manifest-43327798021.json b/docs/evidence/RG-001/manifest-43327798021.json new file mode 100644 index 0000000..ce53400 --- /dev/null +++ b/docs/evidence/RG-001/manifest-43327798021.json @@ -0,0 +1,133 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 11, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "frozen_pending_verification", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "8a9a88b8c00e692e7eeaf891ee398e2cd2885d3e", + "observed_run": 43327385231, + "pending": "Verify actual C++20 compiler flags with the frozen dependency lock", + "scope": "Primary contract toolchain and package versions on the recorded Ubuntu x86_64 environment", + "validated": false + } + }, + "captured_at_utc": "2026-11-12T23:19:54.188389+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "frozen_pending_verification", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261101.360.1", + "kernel": "7.0.0-1017-azure", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "691523ebc9727417cf5efc82d87592b4aafde8c7", + "github_head_ref": "feature/RG-001-contract-bootstrap", + "github_ref": "refs/pull/5/merge", + "github_sha": "691523ebc9727417cf5efc82d87592b4aafde8c7", + "run_id": "43327798021", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.0", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-002.md b/docs/evidence/RG-002.md new file mode 100644 index 0000000..46eb0d6 --- /dev/null +++ b/docs/evidence/RG-002.md @@ -0,0 +1,36 @@ +# RG-002 acceptance evidence + +**Status:** Component verification and independent Tester acceptance passed; PR review pending. No main merge. +**Sources:** PRD 8 / SRD 5 / HLD 4 / LLD 5 §19 and [policy-v1 revision 1](../contracts/policy-v1.md). +**PR:** [#6](https://github.com/kshiteesh28/DistributedRateGuard/pull/6), stacked on RG-001. + +## Verified revision and environment + +[Run 43353832066](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43353832066) checked head `7640975031aee2af2ee7ae855ce88b76115f1569`, merge ref `9be7be9861ddc0f0bd04718e6d500781de5b18ca`. The [observed manifest](RG-002/manifest-43353832066.json) records Ubuntu 24.04 x86_64, exact eight primary packages, CMake/Ninja/compiler/protoc and actual C++20 compilation across 16 project translation units. Original manifest status is retained; promotion of the checked-in lock is a separate recorded action. + +- All **nine CTest groups passed in two clean build directories**: five inherited contract checks, bucket arithmetic unit/oracle, and policy unit/oracle. +- **16 Python tests passed** before configure: 13 manifest-verifier cases plus three independent canonical-oracle tests. +- **12 generated files matched** between clean directories. This does not assert binary/hermetic/Docker reproducibility. +- No production loader/crypto result is inferred from earlier local shims or fake drivers. + +## Acceptance matrix + +| Criterion | Observed component evidence | +| --- | --- | +| RG-002-AC01 / AT-01,04 | Exact independent 580-byte aggregate encoding and SHA-256; input-order invariance; strict/credit Q presence; digest sensitivity to identity/quota/authorization changes; duplicate keys/IDs, unknown references/fields, malformed syntax, numeric/type/URI/incarnation rejection. Fourteen production-driver Python methods passed. | +| RG-002-AC02 / AT-02,03 | C++ boundary fixtures and independent Python arbitrary-precision calculations check sufficient balance exactly c*S, one subunit short, refill fractions, legal maxima, saturation, retry ceiling, invalid policy/state and backwards time. Checked 128-bit multiply/add precede saturation; no enforcement floating point. | +| RG-002-AC03 / AT-21 | LIMITED advances refill timestamp without cost debit. Independent seeded stateful oracle covers 3,000 decisions with interleaved refills. Actually compiled reject-all and double-debit mutants are detected. This is arithmetic defect detection, not the later formal model. | + +The production loader accepted/rejected exact/over caps: 8/9 slots; 10,000/10,001 tenants; 64/65 operations per tenant; 100,000/100,001 total operations; 10,000/10,001 principals; 100,000/100,001 permission pairs. Direct C++ calls accepted a valid JSON document padded to exactly 64 MiB and rejected one byte over with ResourceLimit. Unit/rate/cost/Q and uint32/uint64/identifier boundaries are also covered. These configuration ceilings are independent, not a guarantee that all maxima fit simultaneously. + +The OpenSSL 3 negative test runs in an isolated child with an unavailable provider property. Real production Digest returns typed CryptoFailure; child properties are restored, and the parent configuration is unchanged. Parser float tokens are invalid_json; bool/type/range errors invalid_value; field schema errors invalid_schema; cap overflow resource_limit. + +## Findings and ownership + +Junior Dev authored arithmetic; Senior Dev authored policy/codec/crypto implementation; Tester authored independent Python oracles, broad policy integration and direct cap tests; Master selected the representation, integrated/published, inspected CI and owns final scope. Tester independently fetched the actual run log and tested-head sources, confirmed all 14 integration methods, direct byte-cap and real crypto-failure cases ran in both directories, and reported no remaining component blocker. The [scrum log](../SCRUM-WORK-LOG.md) records handoffs and independent review. + +[Run 43353532557](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43353532557) caught one malformed unknown-field test fixture; production correctly rejected invalid JSON. Tester fixed mutation construction and Master reran through the successful revision above. Failure evidence is retained. + +## Remaining boundaries + +These are pure policy/accounting components. No RPC admission handler, live quota-state ownership, mTLS certificate validation, clock provenance, supervisor/witness, forwarding, distributed-credit grant protocol, benchmark, state-machine exploration, or release A/B/C acceptance is claimed. Docker target/image evidence remains an open Sprint 0 deployment gate. Unknown tenant lookups never insert, but runtime authentication/atomicity and epoch integration require their assigned stories. diff --git a/docs/evidence/RG-002/manifest-43353832066.json b/docs/evidence/RG-002/manifest-43353832066.json new file mode 100644 index 0000000..7fdd62e --- /dev/null +++ b/docs/evidence/RG-002/manifest-43353832066.json @@ -0,0 +1,135 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 16, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "nlohmann-json3-dev": "3.11.3-1", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "frozen_pending_verification", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "93b7e9e2f962ca07450b502ea84bf12814f69551", + "observed_run": 43331122781, + "pending": "Verify RG-002 policy/JSON extension against independently computed canonical fixtures and actual OpenSSL", + "scope": "Primary Ubuntu x86_64 contract toolchain/package snapshot; generated C++20 contracts and clean-directory code-generation repeat verified", + "validated": false + } + }, + "captured_at_utc": "2026-11-13T02:42:02.207068+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "frozen_pending_verification", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261101.360.1", + "kernel": "7.0.0-1017-azure", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "github_head_ref": "feature/RG-002-policy-arithmetic", + "github_ref": "refs/pull/6/merge", + "github_sha": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "run_id": "43353832066", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "nlohmann_json_dev": "3.11.3-1", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.0", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-003.md b/docs/evidence/RG-003.md new file mode 100644 index 0000000..093fa60 --- /dev/null +++ b/docs/evidence/RG-003.md @@ -0,0 +1,35 @@ +# RG-003 clock component evidence + +**Status:** Clock component verified and independently accepted; full story integration remains pending. +**Sources:** PRD 8 / SRD 5 / HLD 4 / LLD 5 §§16,17,20; [clock-v1 revision 1](../contracts/clock-v1.md). +**PR:** [#8](https://github.com/kshiteesh28/DistributedRateGuard/pull/8), stacked on verified RG-002. + +## Observed revision and checks + +[Run 43355987772](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43355987772), head `2d55c6e032ae75947f045ac76ffa383b2b1dd9d8`, tested merge ref `208c8ba13c8bbe7cfc36b5fe44a2e0b1b5490ae8`. [Manifest snapshot](RG-003/manifest-43355987772.json) records the actual primary toolchain/packages, runner kernel and C++20 flags over 20 project translation units. + +- **13 CTest groups passed in both clean build directories**, including independent clock tests, an actually compiled clamp mutant, and Linux fork/exec smoke. +- **Three targeted address/undefined-sanitizer tests passed**: developer clock tests, independent clock tests, real Linux smoke. They instrument the clock library and consuming tests. +- **16 Python verifier/oracle tests passed**; all **12 generated protobuf/gRPC files matched** between clean directories. Exact primary package/tool lock comparison passed. +- Supported-Linux smoke has no CTest skip mapping. Its successful exit verifies real proc/ns sources and child process sampling; macOS unsupported exit 77 is not a Linux pass. + +## Requirement disposition + +| Requirement / evidence | Component result and remaining boundary | +| --- | --- | +| RG-003-AC01; PRD-002/024, FR-001/017; AT-01/17 | PASS for clock component: exact manifest identity match, UUID/offset grammar and bounds, current/children and before/after namespace mismatch, all identity fields, initial read failure, illegal clock ID, syscall/invalid/overflow/regression failure, sticky health and equal timestamps. No usable factory object before identity and initial sample succeed. | +| Production provenance | Real Linux boot/proc reads and namespace filesystem type checks succeeded; actual fork/exec child has equal identity and nondecreasing sample. Same-descriptor PROC_SUPER_MAGIC/NSFS_MAGIC checks precede reads/fstat; bounded reader detects max+1 and leaves ownership with caller. Trusted kernel/operator and unshadowed proc mounts remain assumptions, not hostile-host integrity proof. | +| Concurrency / independent defect detection | Developer tests exercise serialized concurrent fake samples. Tester independently verifies integer endpoints, parser rejection, namespace snapshots, descriptor ownership/errors, startup sample retention and sticky failures. An actual backward-time clamp compiles and is rejected by specific independent assertions. | +| RG-003-AC02; AT-02/07 | **PENDING runtime integration:** authority/witness transition linearization and deadline checks under tenant protection remain RG-007/008. This library supplies a verified sample; it cannot prove a caller uses it at the commit point. | +| RG-003-AC03; AT-17 | **PENDING checker integration:** incomplete/unknown provenance must produce UNKNOWN in the Release A RG-011A strict evidence gate, using RG-005 completeness/runtime provenance inputs; it is required before RG-008 acceptance. RG-013 adds credit/formal extensions in C. Factory/provenance failures are input for those integrations, not an implemented history verdict. | +| PRD-024 / D4 Docker topology | **PENDING RG-006/deployment evidence:** supervisor must compare every participant against trusted manifest before activation. Parent/child Linux smoke is not a Docker multi-participant proof. | + +## Review findings and corrections + +Junior Dev authored the implementation and developer/Linux tests. Senior Dev independently reviewed design/code, requested same-descriptor source checks and initial sample readiness, and accepted the final cleanup for CI. Tester authored the separate test/mutant harness and independently fetched final CI logs/source to confirm normal, clean and sanitizer results. Senior Dev accepted final code changes by review, using the reported CI result rather than claiming a local Linux rerun. Master froze the implementation decisions, reviewed/integrated/published and inspected actual CI. + +Master found a path/embedded-NUL defect in the independent harness before publication; Tester corrected it. An additional local sanitizer check then found a separate out-of-bounds literal-length fixture in the developer unit test despite initial green Linux tests. Junior Dev fixed it, and Master added the required sanitizer CI step. Final evidence above includes the corrected fixture and shared production bounded-fd reader; the earlier run is preliminary only. See the [live scrum log](https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/SCRUM-WORK-LOG.md). + +## Scope + +No authority quota service, witness, actual deadline/commit coupling, supervisor fencing, Docker shared-clock proof, runtime mTLS, interval checker, performance gate, cross-host/cross-epoch guarantee, or release acceptance is claimed. Full RG-003 is not Done while AC02/03 integration remains pending. A new clock object is not authorization to restart a failed epoch. diff --git a/docs/evidence/RG-003/manifest-43355987772.json b/docs/evidence/RG-003/manifest-43355987772.json new file mode 100644 index 0000000..a0a97ec --- /dev/null +++ b/docs/evidence/RG-003/manifest-43355987772.json @@ -0,0 +1,135 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 20, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "nlohmann-json3-dev": "3.11.3-1", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "validated", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "7640975031aee2af2ee7ae855ce88b76115f1569", + "observed_run": 43353832066, + "scope": "Primary Ubuntu x86_64 foundation toolchain/package snapshot; generated C++20 contracts, policy/crypto and arithmetic component checks, two clean builds and code-generation repeat verified", + "tested_merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "validated": true + } + }, + "captured_at_utc": "2026-11-13T03:01:50.274357+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "validated", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261111.370.1", + "kernel": "7.0.0-1017-azure", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "208c8ba13c8bbe7cfc36b5fe44a2e0b1b5490ae8", + "github_head_ref": "feature/RG-003-clock-provenance", + "github_ref": "refs/pull/8/merge", + "github_sha": "208c8ba13c8bbe7cfc36b5fe44a2e0b1b5490ae8", + "run_id": "43355987772", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "nlohmann_json_dev": "3.11.3-1", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.1", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-004-A.md b/docs/evidence/RG-004-A.md new file mode 100644 index 0000000..1416ab3 --- /dev/null +++ b/docs/evidence/RG-004-A.md @@ -0,0 +1,44 @@ +# RG-004-A — TLS compatibility and trusted UTC component evidence + +**Status:** Compatibility input independently accepted for PR review; full RG-004 remains incomplete. +**PR:** [#9](https://github.com/kshiteesh28/DistributedRateGuard/pull/9), stacked over verified RG-003. +**Sources:** PRD 8 / SRD 5 / LLD 5; [security decisions revision 2](../decisions/RG-004-security-v1.md). + +## Verified revision + +[Run 43978267486](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43978267486), head `82a09370dac6840f8fe1ad48bd060d6e79862ea6`, merge `6fa243bbadce4e2637c9d04c93dd5e24af5f42d7`. The [manifest](RG-004-A/manifest-43978267486.json) records the pinned Ubuntu gRPC 1.51.1/OpenSSL 3 toolchain and actual C++20 compilation across 30 project translation units. + +- **17 CTest groups passed in each of two clean build directories.** +- **3 clock and 3 security/wall-clock sanitizer checks passed** under AddressSanitizer/UndefinedBehaviorSanitizer. +- **16 Python checks passed** (13 manifest-verifier and 3 policy-oracle tests); **12 generated files matched** between clean builds. Exact primary package/tool lock comparison passed. +- Native hosted-Linux UTC observation: synchronization state 0, flags 0, trusted=true. [Captured result](RG-004-A/native-time-43978267486.json) is explicitly host-only, not Docker/target deployment acceptance. + +## Observed scope + +| Check | Actual evidence and boundary | +| --- | --- | +| Real peer verification | A TCP gRPC fixture uses the production PinnedPeerVerifier with ordinary chain verification enabled. URI SAN and leaf DER SHA-256 must match the supplied trusted-input registry. This helper is not the production manifest/registry loader. | +| Positive control | Independent OpenSSL root→leaf client/server-purpose chain preflight passes before RPC startup. Valid peer reaches exactly one synthetic handler call. No quota engine or backend is invoked. | +| 13 RPC scenarios | Valid, wrong client URI, same URI/wrong client leaf, wrong client EKU, unknown client CA, absent client certificate, expired/future client leaves, multiple URI SANs, wrong server URI, same URI/wrong server leaf, unknown server CA, and two valid RPCs on one channel object. Rejected cases have zero handler calls. | +| Seeded verifier bypass | A separate test-only library replaces only the custom verifier with accept-all. Normal TLS chain checks remain configured. Wrong URI and same-URI wrong-leaf cases on both sides then reach the handler and fail the probe's assertions. The independent mutation checker detects these exact failures. No bypass is linked into the real library. | +| UTC trust helper | Owned injected platform, initial trusted sample, read-only adjtimex modes=0, state/flag failure, realtime failure, invalid values, backwards time, serialized sampling and sticky local health are covered by developer and independent tests. No floating-point time conversion. | +| Commitment correctness | Clock errors carry only bounded reason. ToServiceError requires explicit caller phase and preserves NotCommitted/Possible/Committed, including after ALLOW. The primitive cannot determine quota commitment. | +| Output/privacy | Probe checker bounds/scans captured output before reporting, withholds raw child output, and emits only allowlisted scenario/count fields or numeric preflight codes. This is fixture-output evidence, not application event/export AC03 completion. | + +Tester independently fetched actual logs and source at the tested head. Senior Dev reviewed final code and scoped its acceptance to this input. Master integrated/published, inspected CI and recorded source/environment identities. + +## Findings retained + +1. Master's initial workflow edit interpreted a shell-regex dollar/quote sequence as JavaScript replacement syntax; no CI started. Callback replacement plus duplicate-key and shell-syntax validation corrected it. +2. Senior's test BIO deleter alias assumed a void return; the real OpenSSL build exposed BIO_free's int return. Correct ownership type was applied. +3. Master's original primitive error contract incorrectly embedded NotCommitted. Senior review caught the post-ALLOW case; Junior and Tester implemented and independently checked explicit phase mapping. +4. Initial fixture CA/leaf subjects were identical and lacked SKI/AKI; the valid control and bypass both failed chain validation. Distinct subjects, SKI/AKI and an independent purpose preflight corrected the test profile without weakening CA verification. +5. Tester corrected diagnostic ordering so a failing child cannot print raw PEM before the privacy guard. + +Failure runs remain linked in the [live scrum log](https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/SCRUM-WORK-LOG.md). Later Docker observation and final documentation checks must be recorded separately; they do not rewrite this tested revision. + +## Remaining requirements + +RG-004-AC01 is not fully closed: production immutable certificate-registry/epoch-policy binding and adapter/replica role, tenant, operation and cost authorization are still pending. AC02 still requires actual expiry revalidation on established channels, reconnect/session-resumption behavior, per-call/precommit/pre-forward guards and fenced trust changes. Two successful calls on one channel object are not that proof. AC03 still requires real event/export redaction. + +UTC failure latch is instance-local; RG-006 must integrate participant readiness, notification and epoch fencing. Docker capability observation, actual target topology, service activation, workload performance and release A/B/C acceptance remain separate gates. No production readiness, full security completion or quota guarantee is claimed. diff --git a/docs/evidence/RG-004-A/docker-time-43980308204.json b/docs/evidence/RG-004-A/docker-time-43980308204.json new file mode 100644 index 0000000..96f20c6 --- /dev/null +++ b/docs/evidence/RG-004-A/docker-time-43980308204.json @@ -0,0 +1,155 @@ +{ + "container": { + "clock": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "a0fdde7d249d4cb3b7dbd72ba058a2ca", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 321802449618 + } + }, + "wall": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 771829433, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794872164 + }, + "return_code": 0, + "valid_json": true + } + }, + "docker": { + "available": true, + "error": null, + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "image_metadata_result": { + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "inspect_after": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "inspect_before": { + "error": null, + "return_code": 1, + "started": true, + "timed_out": false + }, + "pull": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "repo_digests": [ + "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8" + ] + }, + "repo_digest": "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8", + "version": "28.0.4|28.0.4", + "version_result": { + "error": null, + "return_code": 0, + "stdout": "28.0.4|28.0.4" + } + }, + "host": { + "clock_after": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "a0fdde7d249d4cb3b7dbd72ba058a2ca", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 321847325782 + } + }, + "clock_before": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "a0fdde7d249d4cb3b7dbd72ba058a2ca", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 321014700559 + } + }, + "wall_after": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 935899805, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794872164 + }, + "return_code": 0, + "valid_json": true + }, + "wall_before": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 103274678, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794872164 + }, + "return_code": 0, + "valid_json": true + } + }, + "limitations": [ + "A matched observation does not prove shared Docker deployment topology, epoch fencing, supervisor behavior, or a quota guarantee.", + "The image tag is mutable; the observed RepoDigest and image ID are recorded for this run.", + "No Docker permissions or capabilities are broadened to force a ready observation." + ], + "observed_at_utc": "2026-11-16T23:36:01.303253+00:00", + "readiness": { + "comparison": { + "container_ns": 321802449618, + "host_after_ns": 321847325782, + "host_before_ns": 321014700559, + "identity_fields_match": true, + "monotonic_samples_ordered": true + }, + "reason": null, + "state": "OBSERVATIONS_MATCHED" + }, + "requested_image_tag": "ubuntu:24.04", + "schema_version": 1, + "scope": "capability observation only, not full deployment/epoch supervision" +} diff --git a/docs/evidence/RG-004-A/manifest-43978267486.json b/docs/evidence/RG-004-A/manifest-43978267486.json new file mode 100644 index 0000000..0fd150a --- /dev/null +++ b/docs/evidence/RG-004-A/manifest-43978267486.json @@ -0,0 +1,135 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 30, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "nlohmann-json3-dev": "3.11.3-1", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "validated", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "7640975031aee2af2ee7ae855ce88b76115f1569", + "observed_run": 43353832066, + "scope": "Primary Ubuntu x86_64 foundation toolchain/package snapshot; generated C++20 contracts, policy/crypto and arithmetic component checks, two clean builds and code-generation repeat verified", + "tested_merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "validated": true + } + }, + "captured_at_utc": "2026-11-16T23:21:49.006078+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "validated", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261111.370.1", + "kernel": "7.0.0-1017-azure", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "6fa243bbadce4e2637c9d04c93dd5e24af5f42d7", + "github_head_ref": "feature/RG-004-security-probes", + "github_ref": "refs/pull/9/merge", + "github_sha": "6fa243bbadce4e2637c9d04c93dd5e24af5f42d7", + "run_id": "43978267486", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "nlohmann_json_dev": "3.11.3-1", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.1", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-004-A/manifest-43980308204.json b/docs/evidence/RG-004-A/manifest-43980308204.json new file mode 100644 index 0000000..0757af4 --- /dev/null +++ b/docs/evidence/RG-004-A/manifest-43980308204.json @@ -0,0 +1,135 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 30, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "nlohmann-json3-dev": "3.11.3-1", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "validated", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "7640975031aee2af2ee7ae855ce88b76115f1569", + "observed_run": 43353832066, + "scope": "Primary Ubuntu x86_64 foundation toolchain/package snapshot; generated C++20 contracts, policy/crypto and arithmetic component checks, two clean builds and code-generation repeat verified", + "tested_merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "validated": true + } + }, + "captured_at_utc": "2026-11-16T23:36:04.983877+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "validated", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261111.127.1", + "kernel": "7.0.0-1014-aws", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "a24c820d98aea8916a23c49d6129a4b88d14504b", + "github_head_ref": "feature/RG-004-security-probes", + "github_ref": "refs/pull/9/merge", + "github_sha": "a24c820d98aea8916a23c49d6129a4b88d14504b", + "run_id": "43980308204", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "nlohmann_json_dev": "3.11.3-1", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.1", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-004-A/native-time-43978267486.json b/docs/evidence/RG-004-A/native-time-43978267486.json new file mode 100644 index 0000000..a738771 --- /dev/null +++ b/docs/evidence/RG-004-A/native-time-43978267486.json @@ -0,0 +1,13 @@ +{ + "scope": "GitHub hosted Linux only; Docker/target deployment gate remains separate", + "exit_code": 0, + "observation": { + "platform": "linux", + "sync_state": 0, + "status_flags": 0, + "trusted": true, + "failure_reason": null, + "unix_seconds": 1794871308, + "nanoseconds": 952672979 + } +} diff --git a/docs/evidence/RG-004-B1.md b/docs/evidence/RG-004-B1.md new file mode 100644 index 0000000..287d7cd --- /dev/null +++ b/docs/evidence/RG-004-B1.md @@ -0,0 +1,42 @@ +# RG-004-B1 — certificate registry evidence + +**Status:** Input independently accepted for review; full RG-004 remains incomplete. +**PR:** [#10](https://github.com/kshiteesh28/DistributedRateGuard/pull/10) · **Branch:** `feature/RG-004-certificate-registry` +**Sources:** PRD 8 / SRD 5 / HLD 4 / LLD 5; [typed registry contract revision 1](https://github.com/kshiteesh28/DistributedRateGuard/blob/6366df84903049fde3fd92243b3aa7bd06c43986/docs/contracts/certificate-registry-v1.md). +**Passing head:** `6366df84903049fde3fd92243b3aa7bd06c43986` +**Tested merge:** `e03a5291889bb7fc9078bd5bda6b822657ea3cc7` + +## Implemented input and ownership + +Senior Dev implemented the bounded public-PEM loader and immutable registry/developer tests. It binds the root DER fingerprint and canonical policy digest, exact principal set, epoch/authority/slot identities through owned immutable policy, URI/role/leaf fingerprints and copied validity metadata. It validates self/direct signatures, strict chain purposes, P-256/SHA-256, CA/path length/key usage, exact role EKU and half-open UTC validity. Typed failures expose bounded codes. + +Tester independently authored expected identity/pin maps, foreign-chain, time-boundary, byte/count cap and caller-lifetime tests, plus a separately compiled root-pin defect control. Junior reviewed integer-time/profile/ownership paths and identified corrections. Master integrated the build, added signed certificate-profile cases, and inspected execution evidence. + +## Actual verification + +[Run 44016873892](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44016873892), job `133816799093`, passed: + +- 21/21 CTest groups in each of two clean Linux build directories. +- Registry developer, 21-case signed-profile, independent acceptance and root-pin mutation groups. +- 3/3 clock sanitizer checks and 6/6 security ASan/UBSan checks, including all three registry test executables. +- 16 Python checks: 13 manifest-verifier and 3 policy-oracle methods; 12 matching generated files. +- C++20 evidence over 39 project compile commands and exact frozen package-lock comparison. + +The mutation checker first requires the normal independent suite to pass, then requires the separately compiled bypass to fail exactly at `wrong_root_digest_rejected`. The production registry library has no bypass switch. + +[Manifest snapshot](RG-004-B1/manifest-44016873892.json) and [Docker observation](RG-004-B1/docker-time-44016873892.json) retain the original evidence. Docker clocks matched under restricted capabilities; registry integration tests ran on hosted Linux. This is not execution of the actual service topology inside its target VM. + +## Acceptance boundaries + +| Slice criterion | Evidence | +| --- | --- | +| B1-AC01 binding and positive roles | Developer/independent fixtures, independently derived DER pins, immutable epoch/policy comparisons, reversed input order | +| B1-AC02 profile/identity/root rejection | Signed profile and independent negative fixtures; compiled root-pin bypass detected | +| B1-AC03 time and trust | Fractional ±1 ns boundary cases, explicit expiry at notAfter, root validity, canonical year/tag and clock failure | +| B1-AC04 caps/ownership | Exact/over 64 KiB and 64 MiB input checks, 10,001-leaf rejection, lifetime and unknown-lookup checks; metadata/error-path review | + +Senior Dev and Tester independently inspected exact source and completed CI, finding no scoped blocker. Their earlier usage-limit interruptions are retained in LOG-029; later capacity returned and final audits completed. Local OpenSSL compilation was unavailable and is not claimed. + +## Still open + +B1 does not implement supervisor manifest serialization/authenticity, credential provisioning, positive fencing, current service readiness, PeerAuthenticator/AuthorizationResolver, per-call/precommit/preforward expiry, reconnect/resumption, real export privacy or quota enforcement. `validated_at` describes snapshot construction only. Full RG-004 AC01–03, deployment and numerical release gates remain open. No benchmark, formal-proof, production-readiness or main-merge claim. diff --git a/docs/evidence/RG-004-B1/docker-time-44016873892.json b/docs/evidence/RG-004-B1/docker-time-44016873892.json new file mode 100644 index 0000000..db29878 --- /dev/null +++ b/docs/evidence/RG-004-B1/docker-time-44016873892.json @@ -0,0 +1,155 @@ +{ + "container": { + "clock": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "77cd888a49bc4d4a850644166ba31cf7", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 488029541631 + } + }, + "wall": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 985044081, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794889621 + }, + "return_code": 0, + "valid_json": true + } + }, + "docker": { + "available": true, + "error": null, + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "image_metadata_result": { + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "inspect_after": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "inspect_before": { + "error": null, + "return_code": 1, + "started": true, + "timed_out": false + }, + "pull": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "repo_digests": [ + "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8" + ] + }, + "repo_digest": "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8", + "version": "28.0.4|28.0.4", + "version_result": { + "error": null, + "return_code": 0, + "stdout": "28.0.4|28.0.4" + } + }, + "host": { + "clock_after": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "77cd888a49bc4d4a850644166ba31cf7", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 488077736885 + } + }, + "clock_before": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "77cd888a49bc4d4a850644166ba31cf7", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 487144472141 + } + }, + "wall_after": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 169658036, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794889622 + }, + "return_code": 0, + "valid_json": true + }, + "wall_before": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 236326197, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794889621 + }, + "return_code": 0, + "valid_json": true + } + }, + "limitations": [ + "A matched observation does not prove shared Docker deployment topology, epoch fencing, supervisor behavior, or a quota guarantee.", + "The image tag is mutable; the observed RepoDigest and image ID are recorded for this run.", + "No Docker permissions or capabilities are broadened to force a ready observation." + ], + "observed_at_utc": "2026-11-17T04:26:57.875934+00:00", + "readiness": { + "comparison": { + "container_ns": 488029541631, + "host_after_ns": 488077736885, + "host_before_ns": 487144472141, + "identity_fields_match": true, + "monotonic_samples_ordered": true + }, + "reason": null, + "state": "OBSERVATIONS_MATCHED" + }, + "requested_image_tag": "ubuntu:24.04", + "schema_version": 1, + "scope": "capability observation only, not full deployment/epoch supervision" +} diff --git a/docs/evidence/RG-004-B1/manifest-44016873892.json b/docs/evidence/RG-004-B1/manifest-44016873892.json new file mode 100644 index 0000000..0b9e565 --- /dev/null +++ b/docs/evidence/RG-004-B1/manifest-44016873892.json @@ -0,0 +1,135 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 39, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "nlohmann-json3-dev": "3.11.3-1", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "validated", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "7640975031aee2af2ee7ae855ce88b76115f1569", + "observed_run": 43353832066, + "scope": "Primary Ubuntu x86_64 foundation toolchain/package snapshot; generated C++20 contracts, policy/crypto and arithmetic component checks, two clean builds and code-generation repeat verified", + "tested_merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "validated": true + } + }, + "captured_at_utc": "2026-11-17T04:27:02.217419+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "validated", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261111.127.1", + "kernel": "7.0.0-1014-aws", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "e03a5291889bb7fc9078bd5bda6b822657ea3cc7", + "github_head_ref": "feature/RG-004-certificate-registry", + "github_ref": "refs/pull/10/merge", + "github_sha": "e03a5291889bb7fc9078bd5bda6b822657ea3cc7", + "run_id": "44016873892", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "nlohmann_json_dev": "3.11.3-1", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.1", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-004-B1/native-time-44016873892.json b/docs/evidence/RG-004-B1/native-time-44016873892.json new file mode 100644 index 0000000..ae34eb5 --- /dev/null +++ b/docs/evidence/RG-004-B1/native-time-44016873892.json @@ -0,0 +1,13 @@ +{ + "scope": "GitHub hosted Linux only; Docker/target deployment gate remains separate", + "exit_code": 0, + "observation": { + "platform": "linux", + "sync_state": 0, + "status_flags": 0, + "trusted": true, + "failure_reason": null, + "unix_seconds": 1794889617, + "nanoseconds": 832510634 + } +} diff --git a/docs/evidence/RG-004-B2.md b/docs/evidence/RG-004-B2.md new file mode 100644 index 0000000..90cf216 --- /dev/null +++ b/docs/evidence/RG-004-B2.md @@ -0,0 +1,50 @@ +# RG-004-B2 — authentication and authorization evidence + +**Status:** Independently accepted component input; full RG-004 remains incomplete. +**PR:** [#11](https://github.com/kshiteesh28/DistributedRateGuard/pull/11) · **Branch:** `feature/RG-004-peer-authorization` +**Sources:** PRD 8 PRD-008/024; SRD 5 FR-003/D1/D2/D9; LLD 5 A-02/A-05/§17; [B2 contract revision 1](https://github.com/kshiteesh28/DistributedRateGuard/blob/9d14bb74bd937401471e96e039f651c17c226c43/docs/contracts/peer-authorization-v1.md). +**Verified implementation head:** `9d14bb74bd937401471e96e039f651c17c226c43` +**Tested merge:** `d1027f6a455284b6a4b626d4f6de15f1771cd2f8` + +## Delivered input + +PeerAuthenticator consumes actual TLS AuthContext properties, requires one `tls` transport/URI/leaf PEM, matches exact DER SHA-256 pin and rechecks root plus selected caller validity using trusted UTC. AuthorizationResolver owns the same registry, rechecks time, validates method/role/mode/request bindings and configured permission pairs, and derives cost from policy. Fixed replica identity is carried into private authorized values; unknown selectors never create quota records. + +Opaque peer/authorization values retain a single immutable shared payload. Copies, assignments and rvalue construction retain complete ownership without publishing partially updated proof fields. They authorize an input only; they are not quota ALLOW, GRANTED or forwarding permits. Actual commitment phase remains caller-owned. + +## Observed checks + +[Run 44022842950](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44022842950), job `133836072035`, passed at the implementation head above: + +- 25/25 CTest groups in each of two clean Linux builds. +- 3/3 clock and 9/9 security ASan/UBSan checks, including the real TLS RPC fixture. +- 16 Python checks (13 manifest verifier +3 policy oracle); 12 generated-file matches. +- Exact frozen package lock and C++20 compilation evidence in the [observed manifest](RG-004-B2/manifest-44022842950.json). + +The independent RPC fixture uses separate Replica/Authority server certificates and real server AuthContext. State-port spies verify authorized derived costs and no callback on rejected role, pair, unknown selector, epoch/digest, ID width, decoded size, slot/incarnation, sequence, trigger cost or mode. Dependency cases return application UNAVAILABLE with gRPC OK. The sink never emits quota ALLOW or a credit grant. + +The selected leaf expires before the root. Fake UTC crosses its boundary while a retained AuthContext, stable endpoint and unchanged verifier count show no new handshake; the call is denied before the spy. Cached-token Resolve expiry is also tested. Unregistered and same-URI alternate-leaf TLS clients are rejected before handler invocation. Fake clock resets isolate test cases and are not supported production recovery. + +Separate test-only libraries remove only the admission permission check or the per-call leaf-pin check. Each normal positive control passes first; the unsafe variant must exit at its exact expected failure marker. The production libraries contain no bypass switch. Child stdout/stderr is capped, scanned for PEM armor and withheld from CI output. + +## Acceptance trace + +| Contract criterion | Verification | +| --- | --- | +| B2-AC01 transport identity/pins | Actual TLS property assertions, peer module tests and rejected client handshakes | +| B2-AC02 method/pair/cost/binding | Developer and independent RPC expected cases, exact dispositions and state-spy counts | +| B2-AC03 fresh validity | Root/leaf boundaries, cached-token Resolve, established-connection dispatch expiry | +| B2-AC04 opaque/bounded values | Lifetime/rvalue/copy traits, metadata/message bounds, immutable payload review and sanitizers | +| B2-AC05 unsafe-variant detection | Independently expected permission result and compiled permission/pin mutants | + +Tester independently inspected exact source and logs; Senior completed a separate source/scope audit. Neither found a material B2 code blocker. + +## Failure history and limits + +The initial component bundle passed run 44021072784 (23 tests twice; security sanitizers 8/8). Adding the independent RPC fixture failed compilation in run 44022535591: stale auth enum cases and a helper hiding the assertion function. The corrected fixture then passed the complete run above. LOG-032–035 retain ownership and review corrections. + +[Docker](RG-004-B2/docker-time-44022842950.json) clock observations matched under restricted capabilities; this is hosted-runner capability evidence, not deployment/service topology or fencing. Full RG-004 AC01 still needs actual service integration; AC02 needs precommit/pregrant/preforward, reconnect/resumption and fenced rotation; AC03 needs real event/export privacy. No quota/credit commit, forwarding, supervisor, benchmark, formal-proof or release completion is claimed. + +## Final review head + +PR #11 is ready and unmerged at `20210d5fbabcd891dbbb20ab89eca26f3a73a1db`. [Final run 44023785687](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44023785687) passed the same 25×2 CTest, 3+9 sanitizer and 16 Python checks, exact lock and 12 generated-file matches; the observed manifest contains 53 C++20 commands. Tested merge: `31084e66433126412a5e22457c13fde1f34350b1`. GitHub comparison confirms this promotion changed only one contract status/link line from the independently accepted implementation. [Final manifest](RG-004-B2/manifest-44023785687.json), [Docker observation](RG-004-B2/docker-time-44023785687.json) and [native UTC](RG-004-B2/native-time-44023785687.json) are retained; capability observations do not close deployment gates. diff --git a/docs/evidence/RG-004-B2/docker-time-44022842950.json b/docs/evidence/RG-004-B2/docker-time-44022842950.json new file mode 100644 index 0000000..2f2ac2a --- /dev/null +++ b/docs/evidence/RG-004-B2/docker-time-44022842950.json @@ -0,0 +1,155 @@ +{ + "container": { + "clock": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "6a2fe24933ea462ca3f96266e9ef772a", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 342731252011 + } + }, + "wall": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 702624527, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794892799 + }, + "return_code": 0, + "valid_json": true + } + }, + "docker": { + "available": true, + "error": null, + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "image_metadata_result": { + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "inspect_after": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "inspect_before": { + "error": null, + "return_code": 1, + "started": true, + "timed_out": false + }, + "pull": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "repo_digests": [ + "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8" + ] + }, + "repo_digest": "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8", + "version": "28.0.4|28.0.4", + "version_result": { + "error": null, + "return_code": 0, + "stdout": "28.0.4|28.0.4" + } + }, + "host": { + "clock_after": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "6a2fe24933ea462ca3f96266e9ef772a", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 342775521261 + } + }, + "clock_before": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "6a2fe24933ea462ca3f96266e9ef772a", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 342143121461 + } + }, + "wall_after": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 859225054, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794892799 + }, + "return_code": 0, + "valid_json": true + }, + "wall_before": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 226753445, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794892799 + }, + "return_code": 0, + "valid_json": true + } + }, + "limitations": [ + "A matched observation does not prove shared Docker deployment topology, epoch fencing, supervisor behavior, or a quota guarantee.", + "The image tag is mutable; the observed RepoDigest and image ID are recorded for this run.", + "No Docker permissions or capabilities are broadened to force a ready observation." + ], + "observed_at_utc": "2026-11-17T05:19:55.755238+00:00", + "readiness": { + "comparison": { + "container_ns": 342731252011, + "host_after_ns": 342775521261, + "host_before_ns": 342143121461, + "identity_fields_match": true, + "monotonic_samples_ordered": true + }, + "reason": null, + "state": "OBSERVATIONS_MATCHED" + }, + "requested_image_tag": "ubuntu:24.04", + "schema_version": 1, + "scope": "capability observation only, not full deployment/epoch supervision" +} diff --git a/docs/evidence/RG-004-B2/docker-time-44023785687.json b/docs/evidence/RG-004-B2/docker-time-44023785687.json new file mode 100644 index 0000000..f79110f --- /dev/null +++ b/docs/evidence/RG-004-B2/docker-time-44023785687.json @@ -0,0 +1,155 @@ +{ + "container": { + "clock": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "b0efb082859841169990eea7aeb7f0af", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 376785129117 + } + }, + "wall": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 719859509, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794893298 + }, + "return_code": 0, + "valid_json": true + } + }, + "docker": { + "available": true, + "error": null, + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "image_metadata_result": { + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "inspect_after": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "inspect_before": { + "error": null, + "return_code": 1, + "started": true, + "timed_out": false + }, + "pull": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "repo_digests": [ + "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8" + ] + }, + "repo_digest": "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8", + "version": "28.0.4|28.0.4", + "version_result": { + "error": null, + "return_code": 0, + "stdout": "28.0.4|28.0.4" + } + }, + "host": { + "clock_after": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "b0efb082859841169990eea7aeb7f0af", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 376858993542 + } + }, + "clock_before": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "b0efb082859841169990eea7aeb7f0af", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 375321272839 + } + }, + "wall_after": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 977704810, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794893298 + }, + "return_code": 0, + "valid_json": true + }, + "wall_before": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 439831315, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794893297 + }, + "return_code": 0, + "valid_json": true + } + }, + "limitations": [ + "A matched observation does not prove shared Docker deployment topology, epoch fencing, supervisor behavior, or a quota guarantee.", + "The image tag is mutable; the observed RepoDigest and image ID are recorded for this run.", + "No Docker permissions or capabilities are broadened to force a ready observation." + ], + "observed_at_utc": "2026-11-17T05:28:14.971743+00:00", + "readiness": { + "comparison": { + "container_ns": 376785129117, + "host_after_ns": 376858993542, + "host_before_ns": 375321272839, + "identity_fields_match": true, + "monotonic_samples_ordered": true + }, + "reason": null, + "state": "OBSERVATIONS_MATCHED" + }, + "requested_image_tag": "ubuntu:24.04", + "schema_version": 1, + "scope": "capability observation only, not full deployment/epoch supervision" +} diff --git a/docs/evidence/RG-004-B2/manifest-44022842950.json b/docs/evidence/RG-004-B2/manifest-44022842950.json new file mode 100644 index 0000000..cade296 --- /dev/null +++ b/docs/evidence/RG-004-B2/manifest-44022842950.json @@ -0,0 +1,135 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 53, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "nlohmann-json3-dev": "3.11.3-1", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "validated", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "7640975031aee2af2ee7ae855ce88b76115f1569", + "observed_run": 43353832066, + "scope": "Primary Ubuntu x86_64 foundation toolchain/package snapshot; generated C++20 contracts, policy/crypto and arithmetic component checks, two clean builds and code-generation repeat verified", + "tested_merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "validated": true + } + }, + "captured_at_utc": "2026-11-17T05:19:59.906095+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "validated", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261111.127.1", + "kernel": "7.0.0-1014-aws", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "d1027f6a455284b6a4b626d4f6de15f1771cd2f8", + "github_head_ref": "feature/RG-004-peer-authorization", + "github_ref": "refs/pull/11/merge", + "github_sha": "d1027f6a455284b6a4b626d4f6de15f1771cd2f8", + "run_id": "44022842950", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "nlohmann_json_dev": "3.11.3-1", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.1", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-004-B2/manifest-44023785687.json b/docs/evidence/RG-004-B2/manifest-44023785687.json new file mode 100644 index 0000000..a719bdd --- /dev/null +++ b/docs/evidence/RG-004-B2/manifest-44023785687.json @@ -0,0 +1,135 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 53, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "nlohmann-json3-dev": "3.11.3-1", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "validated", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "7640975031aee2af2ee7ae855ce88b76115f1569", + "observed_run": 43353832066, + "scope": "Primary Ubuntu x86_64 foundation toolchain/package snapshot; generated C++20 contracts, policy/crypto and arithmetic component checks, two clean builds and code-generation repeat verified", + "tested_merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "validated": true + } + }, + "captured_at_utc": "2026-11-17T05:28:19.032407+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "validated", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261111.370.1", + "kernel": "7.0.0-1017-azure", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "31084e66433126412a5e22457c13fde1f34350b1", + "github_head_ref": "feature/RG-004-peer-authorization", + "github_ref": "refs/pull/11/merge", + "github_sha": "31084e66433126412a5e22457c13fde1f34350b1", + "run_id": "44023785687", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "nlohmann_json_dev": "3.11.3-1", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.1", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-004-B2/native-time-44022842950.json b/docs/evidence/RG-004-B2/native-time-44022842950.json new file mode 100644 index 0000000..5892ef1 --- /dev/null +++ b/docs/evidence/RG-004-B2/native-time-44022842950.json @@ -0,0 +1,13 @@ +{ + "scope": "GitHub hosted Linux only; Docker/target deployment gate remains separate", + "exit_code": 0, + "observation": { + "platform": "linux", + "sync_state": 0, + "status_flags": 0, + "trusted": true, + "failure_reason": null, + "unix_seconds": 1794892795, + "nanoseconds": 711171874 + } +} diff --git a/docs/evidence/RG-004-B2/native-time-44023785687.json b/docs/evidence/RG-004-B2/native-time-44023785687.json new file mode 100644 index 0000000..ecb9f24 --- /dev/null +++ b/docs/evidence/RG-004-B2/native-time-44023785687.json @@ -0,0 +1,13 @@ +{ + "scope": "GitHub hosted Linux only; Docker/target deployment gate remains separate", + "exit_code": 0, + "observation": { + "platform": "linux", + "sync_state": 0, + "status_flags": 0, + "trusted": true, + "failure_reason": null, + "unix_seconds": 1794893294, + "nanoseconds": 920443083 + } +} diff --git a/docs/evidence/RG-004-B3.md b/docs/evidence/RG-004-B3.md new file mode 100644 index 0000000..b28a06d --- /dev/null +++ b/docs/evidence/RG-004-B3.md @@ -0,0 +1,31 @@ +# RG-004-B3 — pinned client guards + +**Status:** Scoped component verified; ready for review, unmerged. **Scope:** client certificate/time validation and sealed typed RPC calls only. **Source contracts:** PRD8 / SRD5 / HLD4 / LLD5; [B3 contract](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-004-client-guards/docs/contracts/pinned-client-v1.md). **PR:** [#12](https://github.com/kshiteesh28/DistributedRateGuard/pull/12). **Implementation head:** `0a1b37b6147adb39c885459253d59c8561c9c5cc`. + +## Behavior reviewed + +Fresh trusted UTC guards the root, own client leaf and exact expected server leaf on every outbound call. Before-forward validation repeats certificate/time checks against the same immutable proof; it does not validate application ALLOW, deadline or active epoch. Credentials, channel and stubs are private; channel retries, hedging and session caching are disabled. NotSent applies only to the current local attempt; Invoked preserves raw transport/response without claiming remote commitment. + +The factory bounds/validates PEM, DER pins, role/URI binding and matching noninteractive private keys. RPC messages/metadata are bounded at 16 KiB, credentials at 64 KiB each, target at 256 ASCII bytes, authority calls at min(caller deadline, now+20 ms). No performance guarantee is inferred. + +## Verification and provenance + +[Run 44128491936](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44128491936), tested merge `1fe328849653f92486fa69695e649a6049e961b0`, passed: + +- 29/29 CTest groups in each of two clean builds. +- 12/12 security and 3/3 clock address/undefined sanitizer checks. +- 16 Python verifier methods (13 manifest +3 policy), 12 generated files identical, 65 C++20 compilation commands and exact build-lock verification. + +[Build manifest](RG-004-B3/build-manifest-44128491936.json), [native UTC](RG-004-B3/native-trusted-time-44128491936.json), and [Docker observation](RG-004-B3/docker-time-44128491936.json) are archived here. Native UTC was trusted; Docker returned OBSERVATIONS_MATCHED as capability-only evidence. The original [Actions artifact](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/44128491936/artifacts/14349980152) has SHA-256 `ac97f3125f79540def8fc6b5031f71eaeb02759ec59e916c55da563fe9be9281` and a 30-day expiry. + +Developer guard/wrapper tests, independent actual-mTLS fixture and isolated preflight-bypass mutant are separate checks. Unsafe variant must fail the exact per-call expiry assertion after the normal suite succeeds. The fake clock separates test cases; it does not establish supported clock recovery or epoch reset. + +Senior Dev independently reviewed exact source head and found no material scoped production blocker. Tester independently fetched exact-head source/logs and accepted the scoped RPC, mutation, sanitizer and qualification evidence. Compiler/runtime rework and individual contributions are retained in [live log](../SCRUM-WORK-LOG.md), LOG-038 onward. + +## Session qualification + +The separate [SDK qualification record](RG-004-B3/session-qualification-44128491936.json) reports **qualified** on gRPC 1.51.1 with an explicit test-only LRU cache of capacity 1: actual reuse on a new transport, exact client/server leaf pins, one fresh verifier call on each side, two cache attempts and successful uncached reconnect controls. Fresh uncached reconnect and actual cache-enabled reuse are distinct. Production caching remains disabled; this observation is limited to the pinned SDK fixture and is not a provisioning, rotation, TLS ticket lifecycle or broader deployment qualification. + +## Exclusions + +No quota transition, grant/debit, actual backend forwarding, epoch fencing/rotation, full RG-004 AC01–03, production certificate provisioning, Docker service deployment, numerical release gate or formal proof is accepted by this slice. No implementation merge to main. diff --git a/docs/evidence/RG-004-B3/build-manifest-44128491936.json b/docs/evidence/RG-004-B3/build-manifest-44128491936.json new file mode 100644 index 0000000..a522c04 --- /dev/null +++ b/docs/evidence/RG-004-B3/build-manifest-44128491936.json @@ -0,0 +1,135 @@ +{ + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 65, + "project_cxx_standard_flags": [ + "-std=c++20" + ] + }, + "build_result": "passed", + "candidate_lock": { + "dependencies": { + "package_versions": { + "libgrpc++-dev": "1.51.1-4.1build5", + "libgrpc-dev": "1.51.1-4.1build5", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.4", + "libssl-dev": "3.0.13-0ubuntu3.16", + "nlohmann-json3-dev": "3.11.3-1", + "protobuf-compiler": "3.21.12-8.2ubuntu0.4", + "protobuf-compiler-grpc": "1.51.1-4.1build5", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "version_policy": "Install these exact primary package versions and fail on toolchain drift; do not silently update dependencies." + }, + "github_actions": { + "actions/checkout": "11bd71901bbe5b1630ceea73d27597364c9af683", + "actions/upload-artifact": "ea165f8d65b6e75b540449e92b4886f43607fa02", + "lukka/get-cmake": "56d043d188c3612951d8755da8f4b709ec951ad6" + }, + "limitations": [ + "Not a hermetic or bit-for-bit binary reproducibility claim: runner image and transitive system packages are not fully pinned.", + "Does not verify Docker enforcement topology, clock provenance, mTLS, quotas or performance.", + "Unavailable exact package versions or observed toolchain drift must fail CI and require an explicit lock refresh." + ], + "lock_status": "validated", + "optional_source_build": { + "grpc_ref": "v1.85.0", + "validation": "unverified; separate opt-in compatibility lane; not the dependency mode tested by this lock" + }, + "schema_version": 1, + "target": { + "architecture": "x86_64", + "dependency_mode": "ubuntu-packages", + "language_standard": "C++20", + "os_id": "ubuntu", + "os_version_id": "24.04", + "runner_label": "ubuntu-24.04" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12" + }, + "validation": { + "clean_rebuild_and_codegen_match": true, + "observed_commit": "7640975031aee2af2ee7ae855ce88b76115f1569", + "observed_run": 43353832066, + "scope": "Primary Ubuntu x86_64 foundation toolchain/package snapshot; generated C++20 contracts, policy/crypto and arithmetic component checks, two clean builds and code-generation repeat verified", + "tested_merge_ref": "9be7be9861ddc0f0bd04718e6d500781de5b18ca", + "validated": true + } + }, + "captured_at_utc": "2026-11-17T16:45:34.362932+00:00", + "claim_status": "observed_environment_only", + "dependency_commits": { + "abseil_submodule": null, + "cares_submodule": null, + "grpc": null, + "protobuf_submodule": null, + "re2_submodule": null + }, + "dependency_mode": "system_packages", + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred." + ], + "lock_status": "validated", + "manifest_schema_version": 1, + "runner": { + "image_digest": null, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + "image_os": "ubuntu24", + "image_version": "20261111.370.1", + "kernel": "7.0.0-1017-azure", + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": { + "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", + "HOME_URL": "https://www.ubuntu.com/", + "ID": "ubuntu", + "ID_LIKE": "debian", + "LOGO": "ubuntu-logo", + "NAME": "Ubuntu", + "PRETTY_NAME": "Ubuntu 24.04.5 LTS", + "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", + "SUPPORT_URL": "https://help.ubuntu.com/", + "UBUNTU_CODENAME": "noble", + "VERSION": "24.04.5 LTS (Noble Numbat)", + "VERSION_CODENAME": "noble", + "VERSION_ID": "24.04" + }, + "run_arch": "X64", + "run_os": "Linux" + }, + "source": { + "git_commit": "1fe328849653f92486fa69695e649a6049e961b0", + "github_head_ref": "feature/RG-004-client-guards", + "github_ref": "refs/pull/12/merge", + "github_sha": "1fe328849653f92486fa69695e649a6049e961b0", + "run_id": "44128491936", + "workflow": "contract-build" + }, + "system_packages": { + "libgrpc_dev": "1.51.1-4.1build5", + "libgrpcpp_dev": "1.51.1-4.1build5", + "libprotobuf_dev": "3.21.12-8.2ubuntu0.4", + "libssl_dev": "3.0.13-0ubuntu3.16", + "nlohmann_json_dev": "3.11.3-1", + "protobuf_compiler": "3.21.12-8.2ubuntu0.4", + "protobuf_compiler_grpc": "1.51.1-4.1build5", + "zlib1g_dev": "1:1.3.dfsg-3.1ubuntu2.3" + }, + "tools": { + "cmake": "cmake version 3.31.6\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0\nCopyright (C) 2023 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", + "git": "git version 2.56.1", + "grpc_cpp_plugin": null, + "grpc_cpp_plugin_path": "/usr/bin/grpc_cpp_plugin", + "ninja": "1.11.1", + "protoc": "libprotoc 3.21.12", + "protoc_path": "/usr/bin/protoc", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + } +} diff --git a/docs/evidence/RG-004-B3/docker-time-44128491936.json b/docs/evidence/RG-004-B3/docker-time-44128491936.json new file mode 100644 index 0000000..d8289e6 --- /dev/null +++ b/docs/evidence/RG-004-B3/docker-time-44128491936.json @@ -0,0 +1,155 @@ +{ + "container": { + "clock": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "765b016228c54828b9327e648acb53ab", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 613017714328 + } + }, + "wall": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 123355758, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794933934 + }, + "return_code": 0, + "valid_json": true + } + }, + "docker": { + "available": true, + "error": null, + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "image_metadata_result": { + "image_id": "sha256:7da97f743f397971f35dd21cd2d19a7da070a150e0cfa3eda559e71891ec7533", + "inspect_after": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "inspect_before": { + "error": null, + "return_code": 1, + "started": true, + "timed_out": false + }, + "pull": { + "error": null, + "return_code": 0, + "started": true, + "timed_out": false + }, + "repo_digests": [ + "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8" + ] + }, + "repo_digest": "ubuntu@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8", + "version": "28.0.4|28.0.4", + "version_result": { + "error": null, + "return_code": 0, + "stdout": "28.0.4|28.0.4" + } + }, + "host": { + "clock_after": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "765b016228c54828b9327e648acb53ab", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 613063604740 + } + }, + "clock_before": { + "error": null, + "return_code": 0, + "sample": { + "identity_fields": [ + "765b016228c54828b9327e648acb53ab", + "5", + "4026531834", + "0", + "0", + "0", + "0", + "1" + ], + "monotonic_ns": 611579462824 + } + }, + "wall_after": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 319650220, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794933934 + }, + "return_code": 0, + "valid_json": true + }, + "wall_before": { + "error": null, + "probe": { + "failure_reason": null, + "nanoseconds": 835468404, + "platform": "linux", + "status_flags": 0, + "sync_state": 0, + "trusted": true, + "unix_seconds": 1794933932 + }, + "return_code": 0, + "valid_json": true + } + }, + "limitations": [ + "A matched observation does not prove shared Docker deployment topology, epoch fencing, supervisor behavior, or a quota guarantee.", + "The image tag is mutable; the observed RepoDigest and image ID are recorded for this run.", + "No Docker permissions or capabilities are broadened to force a ready observation." + ], + "observed_at_utc": "2026-11-17T16:45:30.869352+00:00", + "readiness": { + "comparison": { + "container_ns": 613017714328, + "host_after_ns": 613063604740, + "host_before_ns": 611579462824, + "identity_fields_match": true, + "monotonic_samples_ordered": true + }, + "reason": null, + "state": "OBSERVATIONS_MATCHED" + }, + "requested_image_tag": "ubuntu:24.04", + "schema_version": 1, + "scope": "capability observation only, not full deployment/epoch supervision" +} diff --git a/docs/evidence/RG-004-B3/native-trusted-time-44128491936.json b/docs/evidence/RG-004-B3/native-trusted-time-44128491936.json new file mode 100644 index 0000000..15bf4c9 --- /dev/null +++ b/docs/evidence/RG-004-B3/native-trusted-time-44128491936.json @@ -0,0 +1,13 @@ +{ + "scope": "GitHub hosted Linux only; Docker/target deployment gate remains separate", + "exit_code": 0, + "observation": { + "platform": "linux", + "sync_state": 0, + "status_flags": 0, + "trusted": true, + "failure_reason": null, + "unix_seconds": 1794933930, + "nanoseconds": 808723839 + } +} diff --git a/docs/evidence/RG-004-B3/session-qualification-44128491936.json b/docs/evidence/RG-004-B3/session-qualification-44128491936.json new file mode 100644 index 0000000..ee24b51 --- /dev/null +++ b/docs/evidence/RG-004-B3/session-qualification-44128491936.json @@ -0,0 +1,19 @@ +{ + "exit_code": 0, + "observation": { + "actual_resumed": true, + "cache_attempts": 2, + "cache_capacity": 1, + "client_leaf_pin": true, + "client_verifier_calls": 4, + "client_verifier_delta": 1, + "new_transport": true, + "server_leaf_pin": true, + "server_verifier_calls": 4, + "server_verifier_delta": 1, + "status": "qualified", + "uncached_reconnects_passed": true + }, + "schema_version": 1, + "scope": "SDK qualification only; production cache disabled" +} diff --git a/docs/evidence/RG-005-inspector.md b/docs/evidence/RG-005-inspector.md new file mode 100644 index 0000000..20759c5 --- /dev/null +++ b/docs/evidence/RG-005-inspector.md @@ -0,0 +1,25 @@ +# RG-005 history inspector evidence + +This component extends [RG-005](RG-005.md) with an offline inspection command. PR #15 targets the integration feature. Full RG-005 runtime acceptance remains open. + +## Behavior + +Build target `rateguard_history_inspect` accepts `PLAN.json HISTORY.bin`. The independently supplied plan has the [versioned contract](../contracts/history-inspector.md). Parsing rejects duplicate or unknown keys, unsupported schema, floating-point integers, invalid decimal-string uint64 fields, bad identifiers, duplicate producers and checked-size overflow. The 1 MiB plan-input limit is CLI-specific. + +The command reuses the existing binary reader and structural validator. Success reports structural completeness and a safety verdict of UNKNOWN. Error output uses bounded error codes; it does not echo input contents. Exit status is nonzero on invalid evidence. + +## Verification + +Junior developer built the CLI with strict C++20 Clang warnings and wrote a Python end-to-end fixture that independently encodes event, seal and run checksums. The driver exercises a valid multi-producer history, roster-order differences, malformed/duplicate/unknown JSON, floats, oversized plans, missing/corrupt/truncated/trailing history and aggregate extent overflow. + +Root independently built the current source with ASan/UBSan and ran the driver successfully. Root also checked an independently constructed empty sealed history. Tester independently rebuilt and ran the driver, then verified escaped duplicate JSON keys and diagnostic redaction using sentinel input. No findings remain from these component checks. + +Root review corrected owned diagnostic lifetimes, checked aggregate arithmetic, the `producer_owner` field and failed-output handling before publication. Source implementation and tests are separate GitHub commits. + +## Remaining scope + +The inspector does not supply actual clock/commit provenance or semantic quota validation. Those remain RG-011A work. Service recording, stop propagation, retention invocation and incomplete-run persistence still need runtime integration. + +## Linux CI + +[Linux run 45129476268](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45129476268) passed at `e0c9b5540349a166c5797e0a70c06a02b88290f9`. Both clean builds passed 37 CTest groups. Eight history sanitizer groups, three clock sanitizer groups and twelve security sanitizer groups passed; 17 Python tests and generated-file reproduction also passed. The subsequent evidence/invocation update changes documentation only. diff --git a/docs/evidence/RG-005.md b/docs/evidence/RG-005.md new file mode 100644 index 0000000..170af8c --- /dev/null +++ b/docs/evidence/RG-005.md @@ -0,0 +1,46 @@ +# RG-005 component verification + +Recorded 2026-11-23 UTC. Release A component increment, PR #14 targeting `feature/distributed-rateguard`. Product sources remain PRD 8, SRD 5, HLD 4 and LLD 5. + +## Implemented components + +- A fixed-partition, thread-safe recorder reserves slots before an owning transition, publishes once, and seals each registered producer. Abandoned reservations, exhaustion and missing seals keep incomplete evidence visible. +- An independent structural validator checks an externally supplied run plan, canonical roster, sequences, byte accounting and checksums. +- Streaming export and offline binary reading use the documented version-1 layout. The reader rejects truncation, trailing bytes and corrupted records. +- A POSIX file publisher writes a managed partial file, syncs it, publishes by a no-overwrite hard link, removes the partial name and syncs the directory. Results expose visible publication and durability separately. +- Fixed aggregate counters omit tenant and attempt identifiers. Overflow saturates and makes the totals inexact. +- Offline reconciliation joins exact attempt IDs to externally supplied deadlines. It reports duplicate stages, timestamp inversions, orphan events, late receipts, decision/response gaps, forwarding violations and committed ALLOW debits whose results were unanswered. +- Seven-day cleanup removes only managed final/partial regular files from a caller-serialized private output directory. + +The history plan stays strictly below 1 GiB as required by D6. An exact fit to a smaller test budget is accepted. Encoded size is `97 + 39P + 51S` bytes for P producers and S allocated slots. Memory also includes C++ objects and the final snapshot copy, so the encoded cap does not assert a 1 GiB resident-memory limit. + +## Verification performed + +Code through `071035459dbf5b7fd8c50ff6b0ea575c349092e8` has local C++20 component evidence. Root ran the recorder, validator, exporter, binary reader, counters, file publisher and reconciliation tests with strict Clang warnings plus ASan/UBSan. Retention's Python boundary/scope test passed. The local host supports these components; Linux build/runtime evidence is recorded separately below. + +| Test | Observable checks | +| --- | --- | +| event_recorder | Twelve-thread final-slot race, disjoint partitions, abandoned reservation, ownership, independent checksums, sealing and exclusive global ceiling before allocation | +| history_validator | Missing/unsealed/duplicate producers, reserved gaps, corruption, invalid enums, expected-plan mismatches, exact smaller budget | +| history_export | Fixed binary extent and bytes, damaged evidence rejected before writing, failed output stream | +| history_reader | Every truncation point, each single-byte corruption, trailing bytes and wrong caller plan | +| aggregate_metrics | Eight-thread updates, fixed dimensions, owner/stage validation, saturation | +| history_file_publisher | Final/partial collision preservation, modes, managed names, valid file bytes, incomplete evidence and invalid directory rejection | +| strict_reconciliation | Timely/late/equal-deadline receipts, lost responses, no-response LIMITED, duplicate stages/deadlines, ordering, forwarding and terminal errors | +| test_history_retention | Seven-day boundary, managed partial files, recent files, unrelated files, directories and symlinks | + +## Corrections during review + +The first Linux run exposed a malformed CMake helper declaration, corrected in `0e5ff3f`. Subsequent Linux compilation exposed platform-dependent literal inference in the independent checksum fixture, corrected in `122a17d`. A workflow-generation string replacement duplicated YAML content, corrected in `a67e47e`. The reconciliation fixture's temporary include path was corrected in `39224fc`. These failed runs cannot count as acceptance evidence. + +## Remaining acceptance + +RG-005 remains in progress. Actual generator, service and supervisor wiring must bind event owners, stop traffic on evidence loss across processes and run cleanup at the output-directory lifecycle boundary. The semantic quota oracle and real clock/commit provenance gate belong to RG-011A with runtime integration. Fault-injected disk-sync/crash behavior and Linux filesystem crash durability remain unverified. Incomplete snapshot diagnostics remain in memory; the binary publisher currently accepts only complete evidence. A persisted incomplete-run summary and operational export/inspection command remain integration tasks. + +Structural completion and stage reconciliation never produce quota safety PASS. Release benchmarks and model checking have not run. + +## GitHub verification + +[Linux run 45126587562](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45126587562) passed on `da19ea21800c303acae4646d6159f67a1607a3b1`. Results include 17 Python tests, 36 CTest groups in each of two clean builds, matching reproduction of 12 generated files, three clock sanitizer groups, seven history sanitizer groups and twelve security sanitizer groups. Build-lock verification and the hosted-environment observation steps also passed. Those observations retain their stated capability-only scope. + +The test-only GCC indentation correction in `da19ea2` followed the initial local checkpoint. Subsequent changes to this evidence and the story board affect documentation only. diff --git a/docs/evidence/RG-006-A.md b/docs/evidence/RG-006-A.md new file mode 100644 index 0000000..7e9c195 --- /dev/null +++ b/docs/evidence/RG-006-A.md @@ -0,0 +1,41 @@ +# RG-006 local lifecycle component + +PR #16 implements a local gate for one immutable epoch. Sources are PRD 8, SRD 5 D5/FR-008/FR-022 and LLD 5 A-03/LLD-08. Full RG-006 acceptance remains open. + +## State and ownership + +The gate starts in PreActivation. Exact inventory observations must report every participant running before ACTIVE. It issues local RAII permits only while ACTIVE. BeginDrain blocks new permits; existing permits must be released before closure. Cleanup can also drain a failed startup. CLOSED is terminal, and repeating the same stop operation returns the existing result. + +The immutable inventory supports authority, witness, replica and adapter roles. One authority and one witness, at least one replica and adapter, distinct host process/container identities, and one through eight replica entries are required. Replica slot IDs retain policy-v1 uint32 semantics, including zero; eight limits the entry count. Multiple adapters use unique role-local participant identifiers. + +Controller observations are compared against the full participant identity, including container ID, host PID, PID-start identity, incarnation and clock identity. Stop requests go to all adapters/replicas before their exit inspections. Authority and witness shutdown follows only after that group is confirmed exited. Unknown, mismatched, failed or thrown observations leave DRAINING. + +The 1,024-participant cap and role-local identifier limit of 64 lowercase ASCII letters/digits/dashes/underscores are explicit component resource choices. They add no product scale claim. The fixed input is validated before the gate allocates its internal state; caller-owned configuration has its own lifetime. + +## Trusted integration boundary + +An exclusive trusted supervisor must validate policy/provenance, bind the controller to real OS/runtime evidence and establish durable predecessor fencing before constructing any successor gate. Separate gate instances do not coordinate epochs. A controller must outlive its gate and use finite implementation-controlled I/O waits. Controller methods run outside the gate mutex. + +The gate does not launch containers, persist inventory, acquire supervisor ownership, prevent runtime automatic restart, prove host-reboot fencing or authorize successor epochs. These are remaining RG-006 integration tasks. The future authority must still enforce its own actual commit/deadline semantics; a local permit is not a quota ALLOW. + +## Developer verification + +Strict local C++20 Clang and ASan/UBSan runs passed. Developer tests cover candidate rejection, multiple adapters, local phases, exact-identity mismatch, lost/failed stop evidence, startup cleanup, same-operation stop replay, and permit lifetime after gate destruction. Root separately reran the developer suite with sanitizers. + +Review fixed duplicate inventory handling, preactivation permit rejection, startup cleanup, lease-owned state lifetime, ordered stop groups and idempotent CLOSED replay before publication. + +## Independent verification and Linux CI + +Tester independently implemented adversarial and concurrency fixtures; strict local Clang and ASan/UBSan runs passed. Root repeated that independent suite successfully. Coverage includes arbitrary uint32 slot IDs, zero/nine replicas, 1,024-participant overflow, duplicate container/host PID, boot/start identity mismatch, controller exceptions, unknown exits, stop ordering, same-operation retry, permit lifetime and concurrent/reentrant activation. The initial QA fixture retained an injected stop exception during its retry and expected no exit inspections on preactivation cleanup; these fixture assumptions were corrected before publication. The Linux result is recorded below. No actual Docker/OS fencing or Release A acceptance is established by these fake-controller tests. + +## Review dispositions + +The 1,024-participant and 64-character identifier ceilings are enforced internal component limits with explicit InvalidInventory/TooManyParticipants results. They are not added to SRD D6 by this PR. The durable supervisor/manifest integration must reconcile supported configuration and deployment topology before full RG-006 acceptance. This component assumes a distinct container and host PID per registered participant; co-locating multiple participant roles in one container needs an explicit controller/topology design. + +Linux's release-mode build exposed developer test assertions disabled by NDEBUG. Root changed them to always-on checks and reran the fixture locally with NDEBUG and sanitizers. An intermediate diagnostic formatting error was corrected before the final verification run. The independent suite already used always-on checks. The final Linux run passed as recorded below. + +## Passing combined Linux verification + +[Run 45130958093](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45130958093) passed on `6da5d90ce70be41cf9780a64b7bc360492a8d4ab`, including the already merged inspector. Both clean builds passed 39 CTest groups. Seventeen Python tests, two lifecycle sanitizer groups, three clock sanitizer groups, eight history sanitizer groups and twelve security sanitizer groups passed. Twelve generated files reproduced identically. Hosted-environment observations retain their capability-only scope. + +The subsequent evidence/status update changes documentation only. All fake-controller, durable-supervisor and cross-epoch limitations above remain applicable. diff --git a/docs/evidence/RG-006-B.md b/docs/evidence/RG-006-B.md new file mode 100644 index 0000000..7f1d553 --- /dev/null +++ b/docs/evidence/RG-006-B.md @@ -0,0 +1,46 @@ +# RG-006 durable manifest component evidence + +Sources are PRD 8, SRD 5 (FR-008/022, D5), HLD 4 and LLD 5 §8/A-03. PR #17 targets the integration feature. Full RG-006 and Release A acceptance remain open. + +## Implemented behavior + +- Shared pure gate-inventory validation and exact candidate equality preserve existing gate checks. +- A versioned canonical JSON manifest binds immutable epoch, authority, policy and process/clock inventory to phase, generation and operation ID. SHA-256 detects corruption. Inputs reject duplicate/unknown keys, invalid numeric encodings, noncanonical bytes and files exceeding 4 MiB. +- CreateNew requires a new private directory and a nonzero creation operation ID. It persists PREPARED generation 1; an existing path is never reinitialized. +- Exclusive nonblocking locking is scoped to that store directory. Missing/replaced locks, symlinks, wrong owner/mode and extra hard links fail validation. +- Transitions use expected generation/digest CAS and a fixed phase graph. Caller validation/Busy/stale-CAS failures preserve a healthy writer; attempted storage/integrity failures and uncertain publication disable further writes. +- Writes sync a bounded temporary file before close/rename and sync the containing directory afterward. New-directory creation also syncs its parent. Metadata-only results distinguish NotVisible, Durable and VisibleDurabilityUnknown. +- OpenExisting reads preserved state for recovery and remains read-only, including when the file says ACTIVE. It cannot restore serving or authorize a successor epoch. Snapshots expose the last completed in-memory result while a competing write is Busy. + +## Review and verification + +Root extracted validation without changing gate behavior and reran existing gate tests locally with NDEBUG and ASan/UBSan. Junior implemented the codec and always-on tests, including a SHA-256 fixture derived independently with Python hashlib. [Codec Linux run 45133952802](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45133952802) passed at 779184ff with real OpenSSL. + +Senior implemented the POSIX store; Tester independently authored filesystem/fault/concurrency tests. Root syntax-checked store and both test suites with strict C++20 warnings and NDEBUG. Local OpenSSL development files are unavailable. Senior's local test-only digest-stub smoke is excluded from real SHA-256 acceptance. Final store runtime evidence must come from Linux CI. + +Review corrected creation operation identity, canonical roster ordering, explicit success/error results, metadata-only return values, exception-safe descriptor ownership, writer reservation cleanup, nonblocking snapshots, parent-directory sync, checked temporary close and allocation before initial manifest publication. Root aligned the independent post-rename sync-failure fixture with the explicit DurabilityUncertain result. + +## Required test evidence + +| Area | Observable evidence | +| --- | --- | +| Canonical codec | Round trip, independent golden SHA-256, strict fields/integers/clock data, altered valid inventory and digest semantics | +| Creation and ownership | New-only creation, nonzero operation ID, private modes, parent sync, same-directory contention, separate-directory scope | +| Update and recovery | Exact CAS, legal phases, overflow checks, unsorted input, ACTIVE reopen read-only | +| Filesystem failures | Missing/corrupt/oversized/replaced files, symlinks, stale temporary file, failure before/after rename, latched writer | +| Crash observations | Child exits before/after rename; recovery sees the last visible complete record, never auto-initializes | +| Concurrency | Snapshot remains responsive during paused I/O; competing update returns Busy | + +## Limits and remaining work + +The 4 MiB encoded-file cap is an internal resource choice. It does not amend SRD D6 or assert a 4 MiB resident-memory limit. Owner locks apply per configured directory; they do not supply global supervisor exclusion. A digest authenticates neither the writer nor historical freshness, and reopened records cannot establish absence of rollback. + +See the [storage contract](../contracts/manifest-store.md) for the PID-start-before-launch integration gap. Global runtime ownership, durable launch intents/non-serving bootstrap, real OS/Docker evidence, no-restart enforcement, channel closure, fenced recovery and successor activation remain future supervisor work. Ordinary fsync/crash-process tests do not prove every storage device's power-loss behavior. + +## Final Linux result + +[Linux run 45207019201](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45207019201) passed on `ba2d14731b3f2e9e996049e67b9e4d702a2218d8`. Both clean builds passed 42 CTest groups. Seventeen Python tests, three manifest sanitizer groups, two lifecycle sanitizer groups, three clock sanitizer groups, eight history sanitizer groups and twelve security sanitizer groups passed. Twelve generated files reproduced identically. + +Linux compilation first exposed unchecked subprocess-pipe writes in the independent harness; Root added result checks. Final review also identified FIFO manifest opens blocking before regular-file validation. Root added nonblocking opens and a regression rejecting a FIFO without a writer. Those corrections are included in the passing head. Failed earlier runs are excluded. + +The following evidence/status update changes documentation only. Local digest-stub results remain excluded; the passing Linux run uses the real pinned OpenSSL dependency. All global-lock, bootstrap, rollback-authentication and process-fencing limitations above remain open. diff --git a/docs/evidence/RG-006-C.md b/docs/evidence/RG-006-C.md new file mode 100644 index 0000000..a7cca12 --- /dev/null +++ b/docs/evidence/RG-006-C.md @@ -0,0 +1,35 @@ +# RG-006 runtime ownership evidence + +Source contracts are PRD 8, SRD 5 and the clarified HLD 5 / LLD 6 A-03. PR #18 targets the integration feature. + +## Component behavior + +RuntimeOwner owns one deployment-configured canonical runtime root across epoch directories. New initialization requires a new private directory and nonzero domain ID. Its immutable anchor binds schema, domain and canonical root path with SHA-256. Existing acquisition validates the anchor and enters RecoveryRequired; it cannot issue an initial claim or restore serving state. + +A Fresh owner issues one move-only InitialEpochClaim. It is never reissued after use or token destruction. The claim binds domain/epoch, retains the shared root lock and supplies validated CLOEXEC root-directory duplicates for durable bootstrap storage. A second claim returns AlreadyUsed or transient Busy, preserving the legitimate token. + +Owner PID, root/parent path identity, lock identity and anchor identity/content are checked. Ownership-validation failure irreversibly taints the owner and all shared claims. Forked use is rejected before mutex access. The anchor parser is bounded before DOM construction, and file opens reject FIFO/symlink substitutions. Canonical anchor bytes have a 4 MiB limit and root paths have a 4096-byte bound; these are internal implementation limits. + +## Review dispositions + +Root review required sticky invalidation, source-identity checks, nonblocking file opens, bounded anchor parsing, realpath RAII, and a fresh directory open-file description for enumeration. Fresh-claim issuance uses a short logical reservation; filesystem work runs outside the claim mutex. Reclaim checks occur before empty-root scanning so a legitimate epoch child never poisons the first token. Shared descriptor and read/write helpers were extracted from ManifestStore without changing its intended behavior. + +The HLD/LLD startup clarification records stopped-container intents before OS start, then non-serving bootstrap and durable observed process identity before activation. PRD/SRD behavior and release gates are unchanged. + +## Verification scope + +Senior developer and Tester supplied separate always-on NDEBUG fixtures. Root performed strict local C++20 syntax checks. Local executable/sanitizer checks used test-only EVP shims and are excluded from real cryptographic acceptance. Linux CI must execute the real OpenSSL build. + +Required evidence includes same-root lock contention, different-root scope, token-retained lock, existing-root recovery-only behavior, missing/replaced root/lock/anchor, domain/path checks, sticky failure after restoration, inherited PID rejection, initialization/crash boundaries, FIFO rejection and concurrent one-use claim issuance. + +## Remaining work + +Ownership is global only within the deployment's one trusted configured runtime root. Misconfigured alternate roots are outside that exclusion guarantee. Initial claims authorize bootstrap storage, not process launch, activation or proof of fencing. + +A verified-fencing successor-epoch claim under the same root is not implemented. Recreating the root is not a recovery procedure. Actual Docker/OS control, authenticated bootstrap acknowledgement, positive cessation of all prior participants, no-restart enforcement, witness/trust readiness and serving activation remain RG-006 integration gates. + +## Linux result + +Linux [run 45286150998](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45286150998) passed for source head `abd4a1bb30eecbc3d8eae3f5f582e5c5660d6780`, tested as PR merge ref `79eb61fd0b5e9dd322a97eea0ee7ccd45375f22e` against integration `c65780d5265cf6e4fbcd6cb3a92d2b6e3a80c82a`. Evidence: 44 CTest groups in each of two clean builds; 17 Python tests; 12 identical generated files; three manifest, two runtime-owner, two lifecycle, three clock, eight history and twelve security sanitizer groups. Real pinned OpenSSL was used. These are component checks, not deployment, fencing or release-benchmark acceptance. + +The child-process fixture was updated to expect the explicit OwnerProcessChanged result after fork, matching rejection before mutex access. Earlier failed runs are excluded. Following changes to evidence/tracking are documentation only. diff --git a/docs/evidence/RG-006-D.md b/docs/evidence/RG-006-D.md new file mode 100644 index 0000000..4bd8c5a --- /dev/null +++ b/docs/evidence/RG-006-D.md @@ -0,0 +1,39 @@ +# RG-006 bootstrap intent and identity evidence + +Source contracts: PRD 8, SRD 5, HLD 5 and LLD 7 A-03/§21. PR #19 targets the integration feature and depends on PR #18's runtime ownership. + +## Component contract + +`BootstrapInventory` is an immutable value model. A revision-1 plan binds domain, epoch, authority incarnation, policy digest, expected common clock provenance and an exact roster of stopped-container intents. Initial process identities are explicitly absent; a zero PID is never exit evidence. Identity observations must match the planned role, slot, participant, incarnation and container, with nonzero PID/start and matching boot/time-namespace/clock identity. + +Exact duplicate observations are idempotent. Unknown, changed or colliding identities produce a recovery-required successor value; recovery is irreversible. Revisions never wrap. The model supports arbitrary uint32 slot IDs and the existing maximum of eight replica entries, rather than restricting slot numbers to 1–8. + +`BootstrapStore` consumes one move-only initial-epoch claim on success or failure. It creates a new private `epoch-<32 lowercase hex digits>` child beneath the validated runtime root. An existing child is never reused. A complete canonical `intent.json` is persisted before the caller may act on the plan. Each observed identity is a revision/digest CAS update and must be fully durable before an identity acknowledgement or subsequent launch action. + +The store does not observe or start containers itself. Inputs are trusted controller observations, not proof generated by this library. `ReadyCandidate()` returns candidate data only after complete, matching identity registration and ownership/on-disk validation. It is not a serving permission. + +## Publication and concurrency + +Canonical schema-1 JSON uses decimal-string uint64 values, bounded duplicate/unknown-key rejection and SHA-256. The 4 MiB artifact cap is an internal limit. Digests detect corruption; they do not authenticate a writer or establish rollback freshness. + +Initial publication uses POSIX no-replace `linkat`, then removes the temporary link and syncs the child directory. Updates sync a private temporary file, revalidate the current bytes and inode, atomically rename, sync the directory and read back. File opens reject symlinks, FIFOs, hard-link substitutions and invalid ownership/modes. Runtime-root ownership covers cooperative participants under the one trusted configured root; it does not protect against a malicious same-UID concurrent writer. + +Results distinguish `NotVisible`, `Durable` and `VisibleDurabilityUnknown`. Publication visibility, storage error and model-transition status are separate fields. A durably persisted recovery-required transition still blocks readiness. After uncertain storage, the store remains unready and its snapshot remains the last fully durable in-memory value; disk may be ahead. Bounded orphan temporary files require recovery diagnosis, never automatic reuse. + +A short mutex reserves one mutation/readiness operation; filesystem work runs outside it. Competing operations return Busy, stale CAS returns Conflict without poisoning a healthy store, and Snapshot returns an immutable shared value without filesystem I/O. No existing-store serving reopen or fenced successor claim is provided. + +## Verification and review + +Developer and Tester fixtures are separate, always-on under NDEBUG. They cover immutable transitions, canonical golden digests, malformed/tampered envelopes, independent clock/process collisions, exact duplicates, revision exhaustion, consumed claims, CAS conflicts, file tampering and replacement, pre/post-publication failures, crash boundaries, concurrent Busy and snapshot behavior, and readiness rejection after recovery or storage uncertainty. + +Root review corrected allocation/exception boundaries, revision exhaustion, explicit success versus error fields and pre-publication allocations. Senior review identified revalidation between temporary-file sync and replacement; the update path now checks immediately before publication. Initial publication also uses no-replace semantics. Linux exposed an invalid race-test setup that pre-created the epoch directory before the injection point; that fixture was corrected while preserving the separate pre-existing-child test. + +Local syntax and shim-linked smoke runs are not real cryptographic acceptance. Linux [run 45287922499](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45287922499) passed source `03e618b311056227fe6bccb4b9143ced00d2f28c`, tested as PR merge ref `be6acc0697bca17f70803009327289de19c2abd0` against the merged ownership feature `90399f64eb9bd2b6aef81384a9144bcff79f78af`. It passed 48 CTest groups in each of two clean builds, 17 Python tests and reproduction of 12 generated files. Sanitizer suites passed: four bootstrap, three manifest, two runtime-owner, two lifecycle, three clock, eight history and twelve security groups, all with real pinned OpenSSL. Retained CI artifacts include clean-build and sanitizer logs. The following evidence/design/tracking delta is documentation only; no end-to-end release metric is claimed. + +## Remaining integration + +The EpochSupervisor-owned existing-intent recovery reader is also unimplemented; RuntimeOwner::OpenExisting does not read or restore a BootstrapStore. Actual stopped-container creation, Docker/OS process control, independently observed host process identity, authenticated bootstrap acknowledgements, policy/trust/witness gates and participant activation remain unimplemented. Existing roots remain RecoveryRequired. Positive termination of every old participant and a verified successor-epoch claim under the same root remain required; deleting or recreating the runtime root is not recovery. Full RG-006 acceptance remains open. + +## Subsequent component delivery + +[RG-006-E](RG-006-E.md) supplies the diagnostic existing-intent reader after this PR19 source snapshot. Full artifact/runtime reconciliation, process control and verified successor fencing remain pending; the original Linux evidence above retains its stated scope. diff --git a/docs/evidence/RG-006-E.md b/docs/evidence/RG-006-E.md new file mode 100644 index 0000000..070f53c --- /dev/null +++ b/docs/evidence/RG-006-E.md @@ -0,0 +1,35 @@ +# RG-006 bootstrap recovery reader evidence + +**Scope:** PR #20, component RG-006-E. Sources: PRD 8 / SRD 5, HLD 5 and LLD 8 §21; [reader contract v1](../contracts/bootstrap-recovery-v1.md). Full RG-006 remains In progress. + +## Implemented component + +BootstrapRecoveryReader accepts validated recovery-mode RuntimeOwner ownership and reads existing bootstrap intents without changing them. It returns immutable diagnostic inventories, canonical digests, bounded file/directory identity observations and typed issues. Pending process identities and historical boot/clock provenance remain visible. A structurally complete scan is not past durability, process-exit, serving, reset or successor-epoch proof. + +Initial mode/ownership/descriptor failures return typed fatal outcomes; later uncertainty returns an incomplete diagnostic snapshot where allocation permits. Unknown/missing/temporary/invalid artifacts, detected mutation, identity collisions, latched recovery or any resource/truncation condition prevent a complete scan. Safely decoded known records remain available when other records are uncertain. + +The reader uses fresh directory open-file descriptions, sorted entry comparisons, RAII descriptors, no-follow/nonblocking opens, private-mode/single-link checks, bounded canonical decoding, owner/domain/epoch binding and repeated UID/link/mode/size/time/inode checks. It revalidates root ownership and metadata after scanning. This is detected-change evidence, not an atomic filesystem snapshot, authentication or rollback freshness. + +## Resource and failure review + +Fixed reader-only limits are 1,024 epoch directories, 4,096 all root entries, 16 all child entries, 64 MiB conservatively reserved attempted input, 16,384 retained participants, 256 global issues and 16 issues per epoch. Each intent retains the 4 MiB codec cap. Failed reads/decodes do not refund the input budget. Issue saturation flags truncation while allowing a safe known intent to be read within remaining work budgets. No cap authorizes reset. + +Root review required exception-safe directory ownership, correct fdopendir failure cleanup, fresh enumeration offsets, hard issue caps even during final error reporting, sorted listings, preservation of valid siblings, full metadata comparisons and conservative byte charging. The independent audit corrected misleading LLD arrows and clarified pre-scan fatal versus post-scan incomplete ownership failure. + +## Verification + +Separate developer and independent tester suites use always-on checks under NDEBUG. Cases cover pending/complete/empty inventories, repeated read-only scans, unknown/temporary/missing/corrupt/binding-mismatched artifacts, FIFO/symlink/hard-link rejection, cross-epoch collisions, replacement/mode/root mutation, every injection hook and each finite limit. A truncated root enumeration is not required to contain a particular directory because filesystem enumeration order varies. + +The developer's wrong-mode/read-failure fixture initially reused an already-created root. Linux run 45292023290 passed the independent suite and 49 of 50 total groups but correctly rejected reinitialization in that fixture. Root separated its temporary roots without relaxing ownership checks or deleting/recreating a recovery root. That failed run is excluded from acceptance. + +Tester also executed the corrected developer suite under local ASan/UBSan. All local EVP-shim runs are fixture/behavior smoke only and excluded from cryptographic or Linux durability acceptance. + +Linux [run 45292546023](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45292546023) passed source `87c784b25d47dd97527709756fd63673671af470`, tested as merge ref `0784213de9ec24bf7e111224363f04a56909f4cb` against feature `cb98d7851fdac6f4eedab0d5f55a88a7fd98a798`: 50 CTest groups in each of two clean builds, 17 Python tests and 12 matching generated files. Real pinned OpenSSL sanitizer checks passed: six bootstrap/reader, three manifest, two runtime-owner, two lifecycle, three clock, eight history and twelve security groups. No sanitizer errors were reported. Subsequent evidence/design/tracking changes are documentation only. These are component results, not recovery fencing, deployment or numerical release-gate acceptance. + +## Remaining integration + +The reader does not launch, inspect, stop or fence processes; restore a store; acknowledge activation; or issue any epoch capability. EpochSupervisor must still reconcile the full artifact/runtime inventory, use a real controller to positively confirm cessation, satisfy all policy/trust/clock/witness gates and obtain a verified successor authorization. Unknown or untrusted inventory blocks reset. Artifact layout/controller integration, authenticated participant activation, witness and full lifecycle acceptance remain open. + +## Later format extension + +[RG-006-F](RG-006-F.md) adds optional-manifest diagnostics under [artifact layout v1](../contracts/epoch-artifact-layout-v1.md). This evidence retains the original bootstrap-only source/run scope; neither version authorizes serving, stop or reset. diff --git a/docs/evidence/RG-006-F.md b/docs/evidence/RG-006-F.md new file mode 100644 index 0000000..efb38c1 --- /dev/null +++ b/docs/evidence/RG-006-F.md @@ -0,0 +1,41 @@ +# RG-006 artifact layout and manifest diagnostics evidence + +**Scope:** PR #21 / RG-006-F. Sources: PRD 8 / SRD 5, HLD 5, LLD 9 and [layout v1](../contracts/epoch-artifact-layout-v1.md). Full RG-006 remains In progress. + +## Implemented component + +The pure epoch_layout_v1 helper supplies exact canonical names and nonzero lowercase-hex epoch parse/format. BootstrapStore and ManifestStore reuse these definitions while preserving prior validation ordering, private new-only creation and publication semantics. + +The diagnostic reader recognizes an optional epoch/manifest-store directory containing an empty owner.lock and a canonical manifest.json. It validates ownership, permissions, single links, bounded file types/contents and before/after identity/entry metadata. Unknown, temporary, missing or changed artifacts make the scan incomplete while safely decoded known data remains available. + +Intent and manifest are scanned independently. A valid manifest remains diagnostic data when the intent is missing or corrupt. Candidate comparison occurs only after BootstrapInventory ReadyCandidate succeeds; unavailable comparison is ManifestBootstrapNotReady, while unequal complete candidates yield ManifestCandidateMismatch. Prepared/Active/Draining/Closed are retained phases, never exit or reset proof. + +Nested directory entries are capped at 16. Both representations share the existing 64 MiB attempted-byte budget and 16,384 retained-record budget. Matching participants in the two artifacts consume two memory records but are not cross-epoch identity collisions. Across-epoch container/process collisions remain incomplete. + +## Review and independent checks + +- Junior developer supplied shared names/grammar and store reuse patches. Master preserved original claim/domain/epoch/model validation priority before formatting. +- Senior developer added independent manifest scanning and typed diagnostics. Tester caught comparison of unavailable bootstrap data being reported as a mismatch, and a phase-fixture predicate that advanced past the target phase; both were corrected before publication. +- Scrum/Master review made baseline-absent to later-present manifest-directory changes explicit, independent of metadata timestamp granularity. Known data is retained, with an incomplete scan. +- Independent tests cover all phases, field mismatches, missing/corrupt/pending bootstrap, unsafe nested file types/modes/links, missing/nonempty lock, unknown/temp files, mutation/appearance races, nested-entry overflow and shared byte/record limits. The record-boundary fixture retains exactly 16,384 records across 32 paired epochs, then rejects the next over-budget inventory. +- Pure grammar, extended developer, new independent and legacy reader checks passed locally under strict NDEBUG Clang; applicable behavior suites passed ASan/UBSan with a deterministic EVP shim. Shim checks do not establish real cryptographic acceptance. + +## Linux verification + +Run 45328285923 passed all 52 CTest groups in both clean builds, 17 Python tests and 12 generated-file reproduction, but the sanitizer command failed because Master's JavaScript workflow replacement dropped its closing shell quote. The sanitizer binaries built; their tests were not executed. The overall failed run is excluded from acceptance. Master fixed only the selector line with literal mapping and checked its Bash syntax; C++ source did not change. + +Run 45330502633 then passed both 52-group clean suites, Python/reproduction checks and every selected sanitizer suite, but failed at a duplicate artifact upload. The same original replacement had also duplicated the workflow tail. This failed run is also excluded from overall acceptance. Master rebuilt the workflow from the verified feature baseline, preserved the two new targets and manifest sanitizer configuration, checked all 21 unique named steps and 18 Bash blocks, and scoped artifact names by run attempt. Commit 7fc9895e changes only the workflow; production C++ is unchanged. + +[Run 45332588272](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45332588272) **passed** on source `7fc9895e5f928ad1576d5b2119b79f4a717151e9`, tested as merge ref `a93680850e190bb7e4d6a3c11f3dc4bb46a8051f` against feature base `9d9074601859c67541cd73343249ea11e8e09a95` with real Linux/OpenSSL: +- 52 CTest groups passed in each of two clean builds. +- 17 Python tests passed; all 12 generated files matched. +- Sanitizer selections passed: bootstrap/layout 8, manifest 3, runtime ownership 2, local lifecycle 2, clock 3, history 8 and security 12 groups. +- Frozen toolchain verification and artifact upload passed. Artifact `14893310876` (`rg001-build-manifest-45332588272-1`) has SHA-256 `55e4f28c6a639bd8a09711b9842f3f40d8eca2cc7c144afe9f70721b951a188d`. + +Only documentation follows this tested source. Hosted component checks and Docker clock observations do not satisfy the target deployment or complete fencing gates. + +## Remaining integration + +ManifestStore still receives a generic caller-supplied directory. Full EpochSupervisor composition must bind it to the validated runtime root/epoch/manifest-store while holding global ownership. Neither a path string, valid manifest nor scan_complete is an epoch capability. + +Docker/OS control, pending-identity stop targets, authenticated participant activation, durable recovery/orphan reconciliation, witness validators and verified successor authorization remain pending. Witness/recovery-operation names are not accepted until their own bounded validators are integrated. No release benchmark, quota safety, full fencing or production-readiness claim is made. diff --git a/docs/evidence/RG-006-G.md b/docs/evidence/RG-006-G.md new file mode 100644 index 0000000..c104dc0 --- /dev/null +++ b/docs/evidence/RG-006-G.md @@ -0,0 +1,36 @@ +# RG-006 Unix HTTP transport evidence + +**Scope:** PR #22 / RG-006-G; PRD 8 / SRD 5, HLD 5, LLD 10 and [transport v1](../contracts/docker-engine-unix-http-v1.md). Full RG-006 remains In progress. + +## Implemented boundary + +Internal IUnixHttpTransport and its private native implementation provide one bounded GET/empty-body POST over a pinned local Unix socket. Immutable path/device/inode/owner checks, peer credentials, per-call descriptors, four-call admission, absolute monotonic deadlines and typed uncertainty protect the exchange. The pure parser handles the selected bounded Content-Length/chunked/EOF profile. + +Clock dependency exceptions become ClockFailure. The final clock/deadline/cancellation gate precedes an allocation-free response move. A failure is known-unsent only before a positive write; no automatic retry or redirect occurs. Valid HTTP statuses remain data for the future controller. + +## Independent review and corrections + +Junior supplied source/developer fixtures. Master reviewed EOF/deadline completion, connect EAGAIN, allocation classification, exception safety, response ownership and bounded fixture teardown. Tester independently supplied parser boundaries, allocation failure, exact request/UID/socket replacement, cancellation/deadline, concurrency and throwing-clock fixtures. + +The GNU-wrapped fixture forces zero-byte versus one-byte EPIPE, connect EAGAIN without retry, fragmented sends with EINTR/EAGAIN, and poll interruptions consuming the original 80/50/20 ms budget before/after request bytes. These are controlled OS-boundary faults, not claims of spontaneous kernel backlog/signal behavior. + +Initial [run45335005143](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45335005143) passed 57 groups twice and all selected checks at e785bc1, before the added fault fixture. [Run45557524588](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45557524588) passed 58 groups twice but failed the new sanitizer-only poll injection; downstream checks were skipped. It is excluded from acceptance. + +Standalone [diagnostic45558599588](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45558599588) confirmed ordinary linkage references poll while sanitizer linkage references fortified __poll_chk. Tester added the correctly typed checked-call wrapper; Master added its target-only linker flag and removed the temporary workflow. Exact assertions, fortification and ASan/UBSan remain enabled. No production decision function changed. Scrum Master independently caught stale pending/failure status; the PR and per-agent log were corrected. + +## Verified Linux source + +[Run45558880696](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45558880696) **passed** source `195ed15d2535ff6b599412f009cfb897d2c971d4`, tested as merge ref `0df8f68b7770196f0a7e2546b495697993227fc2` against feature base `e2d6aeaef0b9ac4e595eb6c50e26afda3e6ee314`: + +- 58 CTest groups passed in each of two clean builds. +- 17 Python tests passed; all 12 generated files matched. +- All 44 selected sanitizer groups passed: transport 6, bootstrap/layout 8, manifest 3, ownership 2, local lifecycle 2, clock 3, history 8 and security 12. +- Frozen toolchain verification and artifact upload passed with real Linux/OpenSSL. Artifact 14997099492 has SHA-256 `8c7e98465d00e0f03f54dfdc690a28c3b11bd5bfebe0a4e4db923a23ce92f595`. + +Only documentation follows this source. Local portable checks and Linux evidence are kept distinct; Darwin fallback compilation is not native Linux fixture evidence. + +## Limits and next integration + +Fake peers verify current-UID credential behavior; actual rootful Docker/API/host placement is a separate qualification. The exact post-EOF scheduling race was reviewed in source without a public test-only hook. This evidence does not establish container stop, process exit, epoch fencing, serving authorization, quota safety, latency/throughput or formal release gates. + +[PR #23](https://github.com/kshiteesh28/DistributedRateGuard/pull/23) separately reviews the inspect/stop controller, recorded-process probe and real Docker qualification. Durable recovery/orphan reconciliation, an old-start barrier, authenticated activation, witness and verified successor authorization remain open. Main promotion remains PR #13. diff --git a/docs/reviews/RG-004-B1-acceptance-matrix.md b/docs/reviews/RG-004-B1-acceptance-matrix.md new file mode 100644 index 0000000..0b9aa95 --- /dev/null +++ b/docs/reviews/RG-004-B1-acceptance-matrix.md @@ -0,0 +1,32 @@ +# RG004-B1 Independent Acceptance Matrix (draft) + +Scope: bounded, immutable certificate registry construction only. The production registry is exercised through its real C++ API/driver and OpenSSL; tests must not call production validation helpers as their oracle. This slice does not prove manifest authenticity, request authorization, epoch readiness/fencing, deployed TLS channel behavior, or service admission behavior. + +## Positive cases + +- Valid self-signed P-256/SHA-256 trust root and registered direct leaf chain for adapter, replica and authority roles; root fingerprint is SHA-256 over DER bytes, not PEM text. +- Exact supplied policy digest, epoch, authority identity, URI principal and role bindings accepted; registry metadata immutable after successful load. +- `notBefore == trusted_now` accepted, `notAfter > trusted_now` accepted; ensure interval comparison uses UTC seconds+nanos consistently. +- Multiple principal inputs accepted up to documented cap with stable lookup results independent of input ordering if ordering is not part of contract. +- Trust chain accepted only when root is the supplied root and all cert/profile requirements pass. +- Exact-cap root and leaf PEMs accepted with surrounding whitespace; one-byte-over is rejected before certificate parsing. Aggregate size exactly 64 MiB reaches later validation; one byte over returns ResourceLimit. A 10,001-leaf input is rejected before parsing. +- Successful load leaves only immutable metadata: root/policy digests, epoch/authority identity, principals/roles/leaf pins, validity and `validated_at`. Destroy caller-owned PEM strings, fixture PKI and policy references; the registry remains usable. + +## Negative cases + +- Wrong root DER fingerprint; root not self-signed; root CA=false; pathLen != 0; missing keyCertSign; wrong key type/signature algorithm. +- Missing, duplicate, multiple, or extra URI SAN; unknown URI; principal not bound by supplied policy; role EKU mismatch or extra EKUs if exact-role-only. +- Leaf CA=true; key usage missing digitalSignature; wrong curve or signature digest. +- notBefore > now; now == notAfter; malformed/invalid validity; clock failure/unknown time. +- Unknown issuer, wrong chain root, chain-depth/path violations, malformed PEM/DER, trailing unrelated PEM blocks. +- Wrong EKU for role; adapter clientAuth only, authority serverAuth only, replica both; no extra EKUs. +- Wrong key/curve/signature profile, non-CA root, non-CA constraints/pathLen/keyCertSign mismatch, CA=true or missing digitalSignature on leaf where independent fixture variants are available. +- Per-certificate PEM >64 KiB; aggregate PEM >64 MiB; more than 10,000 leaf inputs. Check exact-at-cap behavior and one-over behavior wherever contract specifies cap representation. +- Empty, duplicated, missing, or extra leaf inputs relative to policy principals. Ensure failed load returns no partial/published snapshot. +- Safe bounded error code only; diagnostics must not leak raw OpenSSL errors, certificate text, keys, or SAN contents. + +## Evidence required + +- Production compiled integration test against real OpenSSL and parser; no local-toolchain substitute is acceptance evidence. +- Independent fixture construction and expected-case map. Include a test-only mutation that skips at least one material check and confirm the independent suite rejects it. +- Exact output for success/failure status, stable error class, root fingerprint and principal count only; no PEM/key output. diff --git a/docs/reviews/RG-004-B2-acceptance-matrix.md b/docs/reviews/RG-004-B2-acceptance-matrix.md new file mode 100644 index 0000000..b7f37b7 --- /dev/null +++ b/docs/reviews/RG-004-B2-acceptance-matrix.md @@ -0,0 +1,62 @@ +# RG004-B2 independent QA matrix (pre-implementation) + +## Scope and evidence boundary + +Exercise the production `PeerAuthenticator` and `AuthorizationResolver` from a real gRPC C++ server handler using the pinned gRPC/OpenSSL toolchain, a real TLS `grpc::AuthContext`, the verified B1 immutable registry, the frozen policy snapshot, and an injectable trusted UTC source. The handler fixture may use a spy state port, but must call the production security components first. This proves only the authenticated identity and authorization component path; it does not prove the complete admission/authority, epoch fencing, supervisor, resumption, or performance path. + +Transport failures during TLS handshake are not expected to produce a structured application gRPC status. Assert they do not invoke the handler or state port. For calls that reach the handler, assert precise gRPC status and zero state-port calls on auth/policy errors. Never print PEM, keys, URI identities, raw OpenSSL errors, or tenant values. + +Pinned AuthContext properties for the gRPC 1.51.1 TLS connector: `IsPeerAuthenticated()==true`, transport security type `tls`, URI property `peer_uri` (`GRPC_PEER_URI_PROPERTY_NAME`), and actual presented leaf property `x509_pem_cert` (`GRPC_X509_PEM_CERT_PROPERTY_NAME`). Require exactly one value for each property. Inspect values in memory only. Do not depend on full-chain PEM or use request selectors as caller identity. `PeerAuthenticator::Authenticate(const grpc::AuthContext&)` should return an opaque token that owns `shared_ptr`; it independently checks URI and DER leaf pin against that registry and fresh trusted UTC. `AuthorizationResolver::Resolve` must recheck root+selected leaf validity using fresh trusted UTC, so a cached token cannot outlive notAfter. + +## Real gRPC identity/authentication cases + +| Case | Expected result | Handler/state evidence | +| --- | --- | --- | +| Registered adapter leaf, exact SAN and DER pin, valid time | Authenticated token for exact URI/adapter role | One handler call; policy resolution allowed only configured pair | +| Missing AuthContext, missing peer URI, missing leaf PEM, duplicate peer URI, malformed or embedded-NUL property | UNAUTHENTICATED | No state-port invocation | +| Registered URI with alternate leaf DER, unknown URI, unregistered valid-CA leaf, wrong role/EKU | TLS rejection before handler where verifier rejects it; otherwise UNAUTHENTICATED | Handler count and state-port count remain zero | +| `peer_uri` differs from URI SAN in the actual leaf | UNAUTHENTICATED | Confirms authenticator binds context properties together rather than trusting either property alone | +| Non-TLS transport or wrong transport-security property | UNAUTHENTICATED | No state-port invocation | +| Valid adapter certificate on the same established channel: first call before expiration, advance injected trusted UTC to notAfter, call again | First succeeds; second UNAUTHENTICATED | Second call is rejected before state port; proves per-call expiry and does not infer it from TLS handshake/reconnect | +| Authenticate while valid, retain token, advance injected clock to notAfter, call AuthorizationResolver with cached token | typed Expired/NotAuthenticated failure | Authorized operation not produced; spy remains zero for this call | +| Clock becomes untrusted between calls | application `UNAVAILABLE` over gRPC OK | No state-port invocation on second call; no quota outcome of LIMITED and no raw transport UNAVAILABLE | + +For the same-channel expiry case, record server-side TLS verifier invocation count after the first RPC and assert it remains unchanged for the expired second RPC. Also compare `ServerContext::peer()` and retain the first shared `AuthContext` plus its backing for pointer/property comparison. The fake trusted UTC changes; OS/TLS wall time remains valid. This demonstrates the application guard, not TLS handshake expiry or session resumption. + +Also retain a positive authority/replica-authentication fixture for the internal role path where implemented. A replica uses the B1 leaf's exact registered URI, role, DER pin, slot and incarnation; adapter credentials cannot authenticate as replica and vice versa. Use a separate policy fixture that grants one replica a test pair; the unchanged policy-v1 golden fixture has no replica permissions. + +## Policy authorization cases + +Using `tests/fixtures/policy_v1.json`, whose adapter `spiffe://rateguard.local/adapter/ingress1` permits `(zeta,list)` at cost 2 and `(alpha,read)` at cost 1: + +- Both allowed pairs resolve to the policy-owned operation and exact cost, independent of any request-supplied value. +- `(zeta,delete)`, `(alpha,write)`, unknown tenant, unknown operation, and cross-tenant pair attempts cannot call the state port or mutate/create tenant state. +- Adapter used for a replica/authority operation and replica used for adapter admission fail role authorization. +- Attempted client cost field (unknown protobuf field 6) cannot change resolved cost; wire field table currently has no request cost, mode, time, or caller URI. Omitted cost is derived; mismatching internal supplied cost (if resolver API exposes it) is rejected. +- Wrong request epoch/digest, malformed ID width/payload, wrong method/mode, and `AcquireCredit` slot/incarnation/trigger-cost/sequence mismatch return `INVALID_ARGUMENT` before state access. A token from a different registry instance returns `UNAUTHENTICATED`. Record zero state-port calls. +- A decoded protobuf over 16 KiB returns `INVALID_ARGUMENT` in the resolver. Do not claim the future transport receive limit or predecode `RESOURCE_EXHAUSTED` from a direct-handler fixture. +- Resolver tokens are opaque: external caller cannot construct or mutate `AuthenticatedPeer`/`AuthorizedOperation`; token retains the registry/policy snapshot for its lifetime. Drop original owners and confirm token remains valid only for its captured epoch/digest. +- AuthenticatedPeer/AuthorizedOperation/AuthorizedGrant copies and rvalue-expression copies retain the same registry instance. A token created under registry A cannot resolve under byte-identical independent registry B (UNAUTHENTICATED). Resolver derives policy only from its B1 registry; no cross-snapshot policy constructor exists. + +For every case, assert outcome/status, commitment `NotCommitted`, no resolver/authority state mutation, and bounded diagnostic category. Successful authorization returns trusted tenant, operation and configured cost exactly; no request-controlled field becomes a trusted identity or cost. + +## Required mutant/fault controls + +- A test-only mutant that accepts AuthContext URI without checking the actual leaf DER pin must be detected by the same-URI/alternate-leaf case. +- A test-only mutant that skips exact role/pair authorization must be detected by an unauthorized-pair request before state port invocation. +- If a mutant cannot be built without production test hooks, retain direct independent expected-map tests and state the gap; do not call the test result a mutation kill. + +## Open behavior decisions to settle before implementation + +The frozen contract `docs/contracts/peer-authorization-v1.md` revision 1 selects mappings: unknown tenant/operation, malformed fields/widths, stale request epoch/digest, AcquireCredit slot/incarnation/cost/zero sequence, and method/mode mismatch → `INVALID_ARGUMENT`; configured unauthorized pair/wrong role → `PERMISSION_DENIED`; missing/untrusted context, wrong pin, expiry and mixed-registry token → `UNAUTHENTICATED`; clock/config/crypto/resource dependency → application `UNAVAILABLE` over gRPC OK. CheckAdmission accepts either mode; StrictCheck is STRICT-only; AcquireCredit is CREDIT-only. The RPC receives a protobuf already decoded, so B2 tests only the 16 KiB defense-in-depth `ByteSizeLong` invalid-argument check, not future transport predecode `RESOURCE_EXHAUSTED`. + +Replica-to-authority authorization requires a per-replica allowed pair. Use a separate policy fixture granting one registered slot a pair; do not change the policy-v1 golden fixture. The real TLS expiry test and cached-token Resolve test both recheck time; neither proves a quota commit/pre-forward guard or resumed-channel behavior. + +## Deferred evidence + +No B2 test here proves manifest serialization/authenticity, process fencing, service readiness, real quota commit behavior, client wrapper leaf-expiry checks, reconnect/session-resumption, live revocation/rotation, adapter forwarding-expiry integration, or full RG004 AC01–03. TLS two-RPC reuse is only a prerequisite for the per-call expiry test, not expiry proof by itself. + +The independent RPC fixture uses a mutable fake trusted clock to move between +valid, expired, and unhealthy subcases. This is test injection only; resetting +that fake does not model recovery from the production clock's sticky trust +failure and is not evidence of epoch recovery, readiness, or process fencing. diff --git a/docs/reviews/RG-004-B3-acceptance-matrix.md b/docs/reviews/RG-004-B3-acceptance-matrix.md new file mode 100644 index 0000000..4d96a87 --- /dev/null +++ b/docs/reviews/RG-004-B3-acceptance-matrix.md @@ -0,0 +1,46 @@ +# RG004-B3 independent QA plan + +## Scope and binding decisions + +Sources reviewed: PRD 8, SRD 5, LLD 5 on `main`; SEC-01–11 revision 2 and the published B2 contract at `20210d`. This QA slice covers only the outgoing-client trust guard and reusable pre-forward guard. It does not claim quota/credit behavior, adapter forwarding integration, epoch fencing, or product release gates. + +Binding client requirements: + +- Pin the endpoint from immutable registry metadata (expected URI, role/incarnation, leaf DER digest); configuration never comes from the request. +- Preserve ordinary TLS chain validation and enforce the exact endpoint pin during the TLS handshake, including reconnects. +- On every outbound call, sample fresh trusted UTC and verify clock health, trust-root validity, the client's own leaf validity, and the expected server leaf validity. Validity is `notBefore <= now < notAfter`. +- A guard failure before dispatch is a local `NotSent` result with a bounded reason/disposition, not a fabricated gRPC status. Credential/expiry failures classify as `CredentialInvalid`; clock/dependency loss classifies as `ApplicationUnavailable`. The caller may map either local dependency failure to an application `UNAVAILABLE` response, never `LIMITED`; no RPC dispatch and no guard-inferred commitment. +- A reusable pre-forward guard must recheck trusted UTC and root/own-leaf/server-leaf validity for a timely received ALLOW before allowing the caller to proceed. This test seam is not a quota implementation or complete forwarding integration. +- Disable gRPC retries and hedging on enforcement channels. The tests verify the configured channel factory and count dispatches; they do not claim exactly-once network delivery. +- Test TLS verification on fresh and forced reconnect channels separately from session resumption. Same-channel RPC reuse is not a reconnect or resumption test. A resumed session counts as evidence only when the pinned gRPC SDK exposes and the test observes `GRPC_SSL_SESSION_REUSED=true`; if the fixture cannot establish a resumed session, label that evidence NOT QUALIFIED rather than passed. + +## Planned fixture and evidence + +Use real gRPC C++ mTLS with ephemeral in-memory certificates, actual B1 registry metadata, actual pinned server verifier, a fake trusted UTC clock, and a server handler counter. Avoid writing/logging PEM or private keys. Use a replica leaf for the server endpoint and adapter leaf for the client endpoint. Assert exact URI/DER pin is selected from the registry. Keep message responses as test sentinels; never return ALLOW as a test quota result. + +| Case | Required check | Dispatch / result evidence | +| --- | --- | --- | +| Valid outbound call on warm TLS channel | Fresh time sample validates root, adapter leaf and expected replica leaf; endpoint pin remains exact. | Exactly one RPC dispatch; test sentinel response; no quota claim. | +| Root expires before a later call | Keep channel established and OS TLS time valid; move only injected trusted UTC to root `notAfter`. | Wrapper returns `NotSent` + `CredentialInvalid`; dispatch count unchanged. | +| Client's own leaf expires before a later call | Root and server leaf remain valid; fake UTC reaches client leaf `notAfter`. | Wrapper returns `NotSent` + `CredentialInvalid`; dispatch count unchanged; no retry. | +| Expected server leaf expires before a later call | Root and client leaf remain valid; fake UTC reaches server leaf `notAfter`. | Wrapper returns `NotSent` + `CredentialInvalid`; dispatch count unchanged; cached TLS channel does not bypass client guard. | +| Trusted clock becomes unhealthy | Existing warm channel remains otherwise valid. | Wrapper returns `NotSent` + `ApplicationUnavailable`; no RPC dispatch. No commitment phase is invented by the primitive; caller explicitly supplies pre-dispatch phase. | +| Pre-forward guard expiry | First obtain a raw response fixture while time is valid, then advance fake UTC to each root/client/server boundary before guard use. | Guard returns `CredentialInvalid`; backend spy remains unchanged. The guard does not validate ALLOW/deadline/epoch and no actual backend request is sent. | +| Invalid/unregistered endpoint pin | Configure wrong registered server leaf or same URI with alternate DER; ordinary chain may still validate. | TLS verifier rejects before handler. This complements, but does not replace, the warm-channel date checks. | +| Forced reconnect, cache disabled | Create a new channel with an isolated subchannel pool and connect to a distinct server TCP endpoint; count verifier calls and endpoint. | New handshake is observed; exact pin is rechecked. Do not call this session resumption. | +| TLS session resumption, if supported by frozen gRPC API | Share explicit bounded SSL session cache across credentials/channels; force a new transport and inspect actual `GRPC_SSL_SESSION_REUSED` property from AuthContext. | Require true for a qualified resumption case and still prove pin/validity policy. If the runtime does not resume, record NOT QUALIFIED; never use same-channel reuse as substitute. | +| Retry / hedge suppression | Inspect the exact factory-produced channel args and use server dispatch counters under a transport retryable failure. | No hidden second RPC; application retries remain caller-controlled. | + +## Ownership and status table + +The test fixture should call the production client guard before invoking the generated stub and call the reusable pre-forward guard on the returned synthetic response. Client-side pre-call failure should leave handler and state-spy counters at zero. A direct TLS handshake rejection may produce no structured RPC status; assert only transport failure and zero handler calls. Clock loss uses the frozen application-unavailable mapping, not a fabricated transport error or quota outcome. + +The fake clock is mutable only to stage cases; that does not model production sticky clock failure recovery, participant readiness, epoch fencing, or participant-wide stop. Restore it only between isolated test subcases and label this clearly. + +## Evidence limits / not acceptance + +- A warm channel proves per-call guard behavior only for that fixture; it does not prove forwarding, deadline races, quota commit, or the global epoch response. +- A new TCP connection proves reconnect pin validation only. It does not prove resumption. +- `GRPC_SSL_SESSION_REUSED=true` proves a resumed transport occurred in this pinned test environment; it does not by itself establish all TLS 1.3 ticket, cache eviction, process restart, or production deployment behavior. +- No backend invocation or quota authority is part of this fixture. No PRD/SRD numerical gate is measured. +- Do not accept a test that checks only the TLS verifier while ignoring fresh UTC on a reused connection; do not accept one that checks only the pre-forward guard while omitting the per-outbound-call guard. diff --git a/docs/reviews/RG-004-acceptance-matrix.md b/docs/reviews/RG-004-acceptance-matrix.md new file mode 100644 index 0000000..41d9016 --- /dev/null +++ b/docs/reviews/RG-004-acceptance-matrix.md @@ -0,0 +1,32 @@ +# RG-004 Independent Acceptance Matrix + +This is a test plan for SEC-01–SEC-11 in `docs/decisions/RG-004-security-v1.md` revision 1. It is not evidence that TLS, PKI, authorization or service integration exists. Tests must call the implementation's production TLS verifier and channel/server configuration; a parallel QA verifier alone is not acceptable evidence. + +| Case | Input / fault | Required observable result | Evidence boundary | +| --- | --- | --- | --- | +| Valid leaf | Directly signed registered leaf; correct exact URI, role EKU, time window and DER hash | TLS success and exactly one expected RPC dispatch | Proves a generated probe profile only | +| Wrong URI | CA-valid certificate with unregistered or different URI SAN | TLS verification failure; handler count remains zero | Include server pin and client principal paths if driver supports both | +| Wrong leaf pin | Same CA and same URI but a different leaf DER/hash | TLS verification failure; handler count zero | Confirms SEC-01/03/05 pinning, not URI alone | +| SAN ambiguity | No URI SAN, two URI SANs, unknown URI, malformed URI; NUL SAN if constructible | Reject; no fallback to CN or another SAN; handler count zero | State if certificate encoding makes a malformed fixture unrepresentable | +| Wrong EKU/role | CA-valid adapter with serverAuth only; server without serverAuth; replica lacking a required role | Rejection at the relevant handshake/authorization boundary | Keep peer-role checks distinct from TLS protocol identity | +| Unknown CA / malformed chain | Leaf signed by unrelated CA; altered/intermediate chain where applicable | TLS failure and no handler dispatch | Only one root/direct leaf is in v1; do not imply intermediate support | +| Missing client cert | Client connects to REQUIRE_AND_VERIFY server without a certificate | Handshake fails and handler count remains zero | Verify actual configured server credential options | +| Expiry boundaries | notBefore > trusted time; now == notAfter; valid just before notAfter; expired root and expired leaf | Reject invalid cases, accept valid in-window cases | Test injected trusted wall clock; UTC accuracy is not established by fakes | +| Reused channel | Advance fake trusted time past leaf/root validity after channel establishment, then make RPC | Per SEC-07, dispatch/commit revalidation denies expired identity; no quota debit | A handshake-only verifier is insufficient | +| Reconnect / resumption | Force reconnect and, if enabled, TLS session resumption; remove peer leaf metadata or substitute another pin | Exact pin revalidated, or path fails closed; no URI-only/cached fallback | Do not claim session-resumption support from a new full handshake | +| Epoch/slot binding | Valid CA leaf with stale epoch/slot/incarnation registry entry | Startup/readiness rejection or request authorization denial as contract specifies | Requires registry implementation; not proven by certificate SAN alone | +| Registry integrity | Change registered URI/role/hash or policy/manifest digest | Startup refuses readiness | Requires supervisor manifest binding; integration gate | +| Wall-clock trust loss | TIME_ERROR, STA_UNSYNC, STA_CLOCKERR, read failure, observed backward time | Trust-loss latches; service unavailable; no quota `LIMITED` | Junior owns real adjtimex implementation; unit tests do not prove actual VM preflight | +| Secret/log review | Capture verifier, server, client and test logs across success/failure cases | No private keys, credentials, full certificate PEM/DER, or secret file contents appear | Public fingerprints may be logged only if contract explicitly allows | + +## Required harness evidence + +1. Include a handler invocation counter. For all handshake failures (wrong pin/URI, unknown CA, missing client certificate, wrong cryptographic certificate), it must remain zero. A server-side RPC permission denial can enter the handler and must be reported separately. +2. Record the tested certificate properties independently from the production verifier: DER SHA-256, CA identity, URI SAN set, EKUs, validity interval, and whether the chain is direct. Do not call the production verification function to compute expected results. +3. Capture test logs and assert forbidden PEM markers/private key material are absent. Do not include keys, full certs or credentials in expected-output fixtures. +4. Exercise both client and server custom-verifier paths. A single valid handshake does not verify reconnect, reused-channel expiry, TLS resumption, cache pinning, or adapter revalidation before forwarding. +5. Preserve an explicit pass/unsupported/fail result. An unsupported namespace, clock capability or TLS resumption path is not a pass; for SEC-11 it must reject resumption closed if leaf metadata cannot be validated. + +## Scope decision + +Component acceptance may cover leaf parsing/pinning, URI, EKU, CA, missing-certificate and initial handshake behavior. Full RG-004 acceptance also requires SEC-04/07 live service authorization and expiry-before-commit/forward, SEC-06 actual Linux VM wall-clock preflight, SEC-01 registry/epoch binding through RG-006, and SEC-11 reused/reconnect/resumption behavior. Never label the security component complete based only on fake-clock TLS unit tests or an in-process successful handshake. diff --git a/docs/reviews/RG-004-senior-preparation.md b/docs/reviews/RG-004-senior-preparation.md new file mode 100644 index 0000000..af1cd06 --- /dev/null +++ b/docs/reviews/RG-004-senior-preparation.md @@ -0,0 +1,157 @@ +# Senior Dev preparation — historical review input + +**Status:** Requirements/source research only. Open questions in this handoff are superseded where resolved by [Master security decisions revision 1](../decisions/RG-004-security-v1.md). No security implementation or test result is claimed. + +# RG-004 pre-implementation contract extraction + +## Sources inspected + +- PRD revision 8, main, blob 32dbcaad040f7170afdd6a3538430d5b07d05e46 +- SRD revision 5, main, blob 74a60f3a010edffbb883302a05b0e8d41c263ea +- LLD revision 5, main, blob a6236628f34b4c6e21aa56cf3fcbcf2cdde3e9db +- Frozen policy-v1 revision 1, feature/RG-002-policy-arithmetic, blob 3ea68e606ea563eef08d50d73d933a88529b8e6a + +No code or tests were run for RG-004, and no GitHub writes were made. + +## Binding identity and authorization contract + +### Identity and epoch trust + +- Each epoch has immutable policy, one authority incarnation, a trust-root fingerprint, and registered replica identities. The policy binds SHA-256 of the CA root certificate’s DER bytes, not PEM formatting or private material. RG-004 must compare the actual configured CA DER fingerprint with the manifest/policy fingerprint before readiness. +- D9 requires gRPC mTLS for registered adapter URI SAN principals. LLD A-02 selects a local epoch-scoped CA and a separate leaf/key per process. The leaf chain, exact expected server URI SAN, client role, validity, and immutable epoch allowlist are checked. +- Accepted principal URI templates: + - adapter: spiffe://rateguard.local/adapter/ + - replica: spiffe://rateguard.local/replica// + - authority: spiffe://rateguard.local/authority/ +- Policy identities are unique and compare exactly. Replica URI, configured uint32 slot and incarnation must agree; authority URI must match authority incarnation. +- Policy requires at least one adapter, exactly one authority, and exactly one replica principal per registered slot. Slot IDs are unique uint32 values, up to eight, need not be contiguous or zero-based. +- Adapter and replica permission entries reference existing tenant/operation pairs and can be empty (deny all). Authority permissions must be empty. Every tenant has at least one operation. Unknown identities/pairs never create state. +- Mode/policy/trust root and slot membership are immutable within an epoch. Trust rotation or revocation closes old channels and requires a fully fenced new epoch with a rebuilt registry. No online revocation or live rotation is claimed. +- Wall time is for certificate validity only, never refill. The LLD says loss of trusted wall-time validity rejects calls; it does not define a detector or the trust source for wall time. + +### Role / operation matrix + +| Caller | Transport role and registered identity | Permitted operation | Authorization source | +|---|---|---|---| +| Adapter to admission replica | mTLS client; registered adapter URI SAN | CheckAdmission only; requested tenant/operation pair must be in that principal’s permissions | Immutable policy; adapter derives context from trusted upstream/test configuration, ignores client override headers | +| Admission replica to authority | mTLS client; registered replica URI SAN bound to slot/incarnation | Internal strict check and/or AcquireCredit for a configured tenant/operation pair; registered slot/incarnation, epoch and digest must match | Immutable policy and fixed epoch slot registry | +| Admission replica serving adapter | mTLS server; registered replica URI SAN | Serve CheckAdmission | Caller pins/accepts exact registered server identity | +| Authority serving replicas | mTLS server; exact authority URI SAN/incarnation | Strict/grant RPCs from registered replica role only; adapter role cannot acquire credits | Trust registry + role/slot/policy | +| Authority to witness | Local Unix socket, not another mTLS role | Witness protocol from the inventoried authority process | Supervisor-owned OS peer credentials, bound to authority inventory identity; never a caller-supplied PID | + +### Certificate and request processing + +1. Before readiness, load immutable policy and trust registry; parse the configured root certificate, compute SHA-256 over DER, compare with policy fingerprint, reject mismatch. +2. At TLS peer establishment and every RPC, validate the presented leaf chain to the expected epoch root, leaf role/EKU, URI SAN registration, certificate validity, and role/permission binding. Reused channels do not bypass application-level expiry checks. +3. Client verification includes clientAuth; server verification includes serverAuth; client-side channel validates the exact expected server URI SAN. +4. Resolve peer URI exactly from the registered principal table. Resolve requested tenant/operation against immutable permission pairs and derive cost only from policy. Client-supplied cost/time/identity overrides never raise allowance. +5. Any authentication/authorization/validation error is rejected before quota state or grant sequence mutation. No private key, full credential, raw sensitive payload, or full certificate may enter logs or exported artifacts. +6. Local keys are provisioned outside the repository with owner-only permissions and read-only process mounts. The documents do not claim secure provisioning/PKI is already available. +7. Failure after a valid request proceeds into a state transition may have Possible or Committed commitment. Raw transport loss never authorizes forwarding or refunds. Pre-state authentication/authorization/validation failures have NotCommitted. D1/D2 mappings: malformed input -> INVALID_ARGUMENT; absent/untrusted identity -> UNAUTHENTICATED; authenticated but wrong role/permission -> PERMISSION_DENIED; all do not charge. + +## Proposed internal API surface + +These signatures are proposed shape only; concrete types should follow LLD section 17 and RG-001 C++20 error contract. + + Result + PeerAuthenticator::Authenticate(const TransportPeer&, TrustedWallTime); + + Result + PeerAuthenticator::AuthorizeRpc(const AuthenticatedPeer&, RpcKind, + EpochId, PolicyDigest, TrustedWallTime); + + Result + AuthorizationResolver::Resolve(const AuthenticatedPeer&, + TenantId, OperationId, + RequestOrigin); + + Result + PeerAuthenticator::Create(const PolicySnapshot&, const EpochManifest&, + const RootCertificateDer&, TrustedWallClock&); + +- AuthenticatedPeer should contain a non-secret immutable principal URI, role, certificate validity bounds/fingerprint needed for per-RPC revalidation, and verified epoch trust identity; never retain/log the full DER chain unnecessarily. +- AuthorizationResolver is the sole constructor of trusted tenant/operation/cost context. Its input must distinguish adapter-originated server context from internal replica calls so an adapter identity cannot invoke authority-only methods. +- Expected server identity is a channel/config input from the trusted registry, never request data. For replica-to-authority it is the one authority URI bound to this epoch. Adapter-to-replica should pin the actual selected registered replica URI for that channel. +- If a cert has multiple URI SAN entries, the implementation must avoid selecting an arbitrary one; a safe default is require exactly one accepted RateGuard URI SAN and reject duplicates/ambiguous identities. + +## Behavior-changing gaps to resolve before code + +1. Replica EKU: a replica is both a gRPC server for adapters and a gRPC client to the authority. One per-process leaf therefore needs both serverAuth and clientAuth, or the process needs separate role-bound certificates. LLD says separate leaf/key per process and that server leaves require serverAuth and clients require clientAuth, but does not decide the dual-EKU/dual-leaf construction. Choose one before certificate fixtures and config generation. +2. Trusted wall-time source/failure detector: LLD requires per-RPC certificate expiry validation and rejects loss of trusted wall-time validity, but does not define what marks wall time trusted. Decide the v1 source/assumption and fail-closed behavior; do not use monotonic time for X.509 validity. +3. Expiry timing under queueing: specify whether certificate validity is checked once at RPC dispatch or again at the quota transition. Since every RPC is checked and handlers may queue, checking at dispatch and immediately before commit is the conservative behavior; this must be explicit for expiry-during-queue tests. +4. URI SAN cardinality: documents require registered URI SANs and exact URI identity, but do not say how to handle a leaf with multiple URI SANs. Require one recognized RateGuard URI SAN, or define deterministic rejection of multiple recognized identities before implementation. +5. Unknown principal classification: D2 clearly maps missing identity to UNAUTHENTICATED and wrong permission to PERMISSION_DENIED, but exact treatment of a chain-valid CA-signed URI SAN absent from registry should be frozen (recommended UNAUTHENTICATED as unregistered identity). All choices remain no-mutation. +6. Replica permission semantics: frozen policy permits replica permission pairs but does not state whether an internal strict/grant call must satisfy the replica’s own tenant/operation pair as well as the adapter’s original authorization. Recommended yes: authority authorizes the registered replica slot and requested pair; the replica separately authorizes the adapter principal. This preserves checks at both trust boundaries and prevents a compromised/buggy replica from widening its scope. +7. Server identity set for adapters: LLD requires an exact expected server SAN, but no explicit channel-selection rule says which registered replica SAN an adapter expects when replicas are load-balanced. Pin the selected replica identity per channel; never accept an arbitrary URI SAN from the request. +8. Certificate chain/leaf shape: LLD chooses local epoch CA, role-specific EKU and URI SAN, but does not enumerate whether intermediates are supported, required CA basic constraints/key usage, or the exact SAN extension policy. Default to a simple one-root/one-leaf chain with strict X.509 verification unless there is an explicit requirement for intermediates; serialize this in test fixtures so identities cannot be ambiguous. + +Items 1–6 affect eligibility, failure status, or admission timing and should be resolved before enabling RG-004. Items 7–8 can be fixed as safe implementation defaults with independent fixtures if the owner confirms they do not add PKI scope. No dependency or online revocation mechanism is proposed. + + +9. TLS handshake failure versus structured gRPC outcome: absent/untrusted client certs may fail the TLS handshake before an RPC handler can return UNAUTHENTICATED. Define that this is a transport-establishment rejection with no quota/grant mutation, and define which auth failures discovered by an interceptor map to UNAUTHENTICATED or PERMISSION_DENIED. Do not promise a gRPC status when no RPC exists. +10. Reused-channel checks apply on both sides: server interceptors must revalidate client certificate validity/authorization, and outgoing clients must revalidate the cached server peer certificate/expected SAN before each RPC, not only during initial TLS handshake. State whether validity is checked for the leaf only or every presented chain certificate, and what happens if any validity check fails. + + +## Pinned dependency research and proposed defaults (not yet accepted) + +### gRPC C++ v1.51.1 API findings + +Inspected the upstream v1.51.1 source files: +- [tls_credentials_options.h](https://github.com/grpc/grpc/blob/v1.51.1/include/grpcpp/security/tls_credentials_options.h) +- [tls_certificate_verifier.h](https://github.com/grpc/grpc/blob/v1.51.1/include/grpcpp/security/tls_certificate_verifier.h) +- [grpc_security.h](https://github.com/grpc/grpc/blob/v1.51.1/include/grpc/grpc_security.h) +- [grpc_security_constants.h](https://github.com/grpc/grpc/blob/v1.51.1/include/grpc/grpc_security_constants.h) +- [client_interceptor.h](https://github.com/grpc/grpc/blob/v1.51.1/include/grpcpp/support/client_interceptor.h) +- [server_context.h](https://github.com/grpc/grpc/blob/v1.51.1/include/grpcpp/server_context.h) +- [auth_context.h](https://github.com/grpc/grpc/blob/v1.51.1/include/grpcpp/security/auth_context.h) + +The pinned release contains the experimental C++ ExternalCertificateVerifier / CertificateVerifier and TlsChannelCredentialsOptions::set_certificate_verifier APIs. TlsCustomVerificationCheckRequest exposes target_name(), peer leaf PEM, URI SAN names, and peer_cert_full_chain(); the full chain is explicitly not guaranteed to be present. The upstream implementation invokes custom verification after the TLS handshake and before peer-check completion, so a failed verifier prevents the channel/RPC from proceeding. This is suitable for exact URI-SAN pinning before request dispatch. The request's target name is not the RateGuard identity; compare the URI SAN against a preconfigured exact expected identity. Use synchronous local checks, no filesystem/network calls in the verifier. + +Keep normal cryptographic peer verification enabled: explicitly set client-side verify_server_certs=true; on server credentials require a client certificate using GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY. The custom verifier adds the RateGuard URI/role allowlist check. Disable default per-call hostname matching only when URI SAN comparison is configured instead; do not disable chain validation. One channel should be bound to one expected authority URI or one selected registered replica URI. No caller-supplied expected SAN or dynamic arbitrary identity list. + +The same external verifier can inspect client URI SANs at the server handshake. ServerContext::auth_context() exposes per-call AuthContext; the gRPC constants identify the peer leaf PEM property. A client interceptor can access ClientRpcInfo::client_context() and ClientContext::auth_context() during an RPC; however, this review has not validated that the peer certificate property is populated at the PRE_SEND_INITIAL_METADATA hook on both fresh and reused channels. Make that a required integration probe before relying on the client-side per-RPC expiry check. TLS verifier is experimental in gRPC 1.51.1, so pin this dependency and test channel handshakes/failure-before-dispatch. + +### Proposed decisions for the ten gaps + +These are defaults for the technical lead to accept or replace; they are not yet product decisions. + +1. Replica EKU: issue one replica leaf with both clientAuth and serverAuth EKUs. The replica is both an admission gRPC server and authority gRPC client; the LLD already calls for one leaf/key per process and policy has one URI principal per replica. Adapter leaf is clientAuth; authority leaf is serverAuth. +2. Wall-time source and loss: use the Linux VM's CLOCK_REALTIME/system UTC, which is also what the pinned gRPC TLS stack uses for normal certificate validity verification. Treat accuracy/synchronization as an explicit VM deployment precondition; v1 adds no NTP/chrony/systemd dependency because Docker Desktop's time-sync mechanism is host-managed and not a portable in-container API. A syscall failure or observed backwards step marks local certificate authentication unavailable and fails closed (no quota or sequence mutation) until supervisor-controlled trust revalidation; an arbitrary inaccurate but monotonic UTC source cannot be detected by this library. If the product requires machine-detectable synchronization loss, this remains a deployment blocker requiring an explicit trusted health signal. +3. Expiry timing: check certificate validity at RPC dispatch and again immediately before the quota/grant commit after queueing. Expiry before commit rejects with no debit or grant-sequence consumption. A late response remains subject to normal D1/D2 uncertainty and forwarding rules. +4. URI SAN cardinality: require exactly one URI SAN total in the leaf, and require it to equal the registered RateGuard URI. Reject missing, duplicate, multiple, malformed, or unregistered URI SANs. Do not select the first matching identity. +5. Unknown identity/status: invalid chain, absent client certificate, expired/not-yet-valid certificate, or chain-valid but unregistered URI principal yields UNAUTHENTICATED where an application response is possible; a registered principal with wrong role/RPC/pair yields PERMISSION_DENIED. All are precommit/NotCommitted. A TLS handshake rejected before an RPC exists produces a connection/transport failure, not a fabricated structured gRPC status. +6. Replica permissions: enforce both boundaries. The replica authenticates and authorizes the adapter principal's tenant/operation pair; authority independently authorizes the replica principal's same requested pair and fixed slot/incarnation. Empty permissions deny. This makes policy replica permission entries operational and prevents a replica from widening an adapter's authorized pair. +7. Expected server SAN: authority clients pin the epoch's sole authority URI; adapters pin the selected registered replica URI per channel. Resolve the selected replica from trusted endpoint configuration and verify exact SAN on handshake. A load balancer that may switch among replica certificates must use per-replica channels or a design decision accepting a registered set before code; never infer identity from host/DNS/SNI alone. +8. Chain profile: v1 uses one epoch CA trust anchor and one leaf, no intermediate CAs. Require a CA:TRUE root with keyCertSign, CA:FALSE leaf with role-appropriate EKU, and exactly the configured principal URI SAN; retain default strict chain verification. No OCSP/CRL or online revocation; trust-root/leaf rotation is a fenced new epoch. +9. Reused-connection validity: TLS verifies chain validity at handshake. Additionally, each server RPC rechecks peer leaf notBefore/notAfter from that call's gRPC AuthContext against CLOCK_REALTIME before dispatch and commit. Each client RPC should do the analogous server-leaf check in a PRE_SEND_INITIAL_METADATA interceptor using ClientContext::auth_context; the fresh/reused-channel availability probe is a blocking acceptance test. If the peer leaf is absent/ambiguous at that point, do not dispatch; rely on TLS handshake only for the initial connection once a test proves verifier gating. Revalidate URI/role against immutable registry on each call; full chain path is validated by gRPC TLS at handshake. +10. Secret/role lifecycle: keep private keys outside version control and artifacts, restrict file/mount access, log only bounded failure class and pseudonymous principal, and disable session-key logging. Expired certs reject per call; CA or principal membership change requires closed channels and fenced fresh epoch. No live trust changes. + +### Trusted-time evidence and scope + +OpenSSL 3 documentation confirms X509_verify_cert validates certificate chain and validity periods; X509_STORE_CTX_set_time / X509_VERIFY_PARAM_set_time can supply an explicit verification time to OpenSSL contexts. The gRPC 1.51.1 C++ TLS credential options expose no wall-time provider or verification-time setter, so the default TLS handshake validation uses the TLS stack/system wall clock. An application-level X509 recheck can compare leaf validity to a sampled time, but cannot retroactively change the time used by the already-completed gRPC handshake. Therefore keep one system CLOCK_REALTIME source for v1; do not claim independent trusted-time assurance. + +Official OpenSSL references: +- [X509_verify_cert (OpenSSL 3.0)](https://docs.openssl.org/3.0/man3/X509_verify_cert/) +- [X509_VERIFY_PARAM_set_time (OpenSSL 3.0)](https://docs.openssl.org/3.0/man3/X509_VERIFY_PARAM_set_flags/) +- [X509_cmp_time (OpenSSL 3.0)](https://docs.openssl.org/3.0/man3/X509_cmp_time/) + +Research was source inspection only; no API compile probe or certificate integration test was run. The exact SAN verifier is library-supported in the pinned gRPC headers. Per-RPC expiry on reused channels is not yet proven in a running v1.51.1 client/server and remains a story acceptance test. Accurate wall-time synchronization is a deployment precondition, not something the library can independently establish. No implementation has started. + +## Root-ready status summary + +### Source-verified API answer + +For exact server URI verification before any request is dispatched, gRPC C++ v1.51.1 has a source-compatible (experimental) route: configure TlsChannelCredentialsOptions / TlsServerCredentialsOptions with an ExternalCertificateVerifier; its post-handshake request exposes the peer leaf URI SAN values. A verifier that rejects the exact expected registered URI prevents connection peer-check completion, so RPC dispatch cannot succeed first. Compare the SAN to a trusted channel identity; do not rely on target_name, DNS hostnames, or request metadata. Keep client verify_server_certs enabled and require/verify client certificates on server credentials. Do not depend on peer_cert_full_chain because upstream marks it not always available. This is API/source verified, but a compile/handshake integration test is still required. + +### One blocking decision: wall-time trust + +The gRPC credential API has no trusted wall-time provider/verification-time argument. OpenSSL supports an explicit verification time in X509_STORE_CTX, but gRPC TLS options do not expose it and normal handshake checks use the process/system wall clock. Proposed default: use CLOCK_REALTIME/system UTC for TLS validity, declare host/VM time synchronization a deployment precondition, reject certificates outside their validity window, and fail closed with no mutation if the realtime syscall fails or an observed backward step occurs. The library cannot detect a wrong-but-monotonic UTC source. If an active detector for synchronization loss is required by “trusted wall time”, that detector/source is a deployment blocker before RG-004 code; do not claim it is supplied by gRPC/OpenSSL. + +### Remaining verification boundary + +Server-side per-RPC leaf expiry can be checked from ServerContext::auth_context() before request admission and before commit. ClientContext::auth_context() and ClientRpcInfo::client_context() exist in gRPC 1.51.1, but this research did not establish that a remote server leaf is always available at PRE_SEND_INITIAL_METADATA across fresh/reused channels. Keep that as an explicit integration acceptance gate; do not make an unsupported per-RPC client-side expiry claim. Root received this distinction. + +No implementation/API compilation was run. The detailed source links are above in this note.EOF +cat >> /tmp/rateguard-senior-worklog.md <<'EOF' + +- Root-ready RG-004 research status: exact URI SAN verification before dispatch is source-verified through gRPC v1.51.1 experimental post-handshake CertificateVerifier; compile/integration evidence remains pending. One blocking wall-time decision is whether CLOCK_REALTIME with VM synchronization as a deployment precondition is accepted, or active synchronization-loss detection is required (no detector/source exists in current gRPC/OpenSSL contracts). Client-side per-RPC server-leaf expiry remains a runtime API acceptance probe, not a claim. diff --git a/include/rateguard/security/authorization_resolver.h b/include/rateguard/security/authorization_resolver.h new file mode 100644 index 0000000..08eb587 --- /dev/null +++ b/include/rateguard/security/authorization_resolver.h @@ -0,0 +1,178 @@ +#pragma once + +#include "proto/rateguard/v1/admission.pb.h" +#include "proto/rateguard/v1/authority.pb.h" +#include "rateguard/security/peer_authenticator.h" + +#include +#include +#include +#include +#include +#include + +namespace rateguard::security { + +enum class AuthorizationFailureReason : std::uint8_t { + NullRegistry, + PolicyBindingMismatch, + MixedRegistry, + ClockUntrusted, + CertificateNotYetValid, + CertificateExpired, + InvalidRequest, + UnknownTenant, + UnknownOperation, + MethodRoleMismatch, + ModeMismatch, + UnauthorizedPair, + ReplicaSlotMismatch, + ReplicaIncarnationMismatch, + TriggerCostMismatch, +}; + +enum class AuthorizationDisposition : std::uint8_t { + Unauthenticated, + InvalidArgument, + PermissionDenied, + ApplicationUnavailable, +}; + +// Bounded reason only. The RPC handler maps disposition and supplies the +// operation's actual commitment phase when constructing a ServiceError. +struct AuthorizationFailure final { + AuthorizationFailureReason reason; + AuthorizationDisposition disposition; +}; + +class AuthorizationResolver; + +class AuthorizedOperation final { + public: + AuthorizedOperation(const AuthorizedOperation&) = default; + AuthorizedOperation& operator=(const AuthorizedOperation&) = default; + [[nodiscard]] const std::string& tenant_id() const noexcept { return data_->tenant_id; } + [[nodiscard]] const std::string& operation_id() const noexcept { return data_->operation_id; } + [[nodiscard]] std::uint64_t cost_units() const noexcept { return data_->cost_units; } + [[nodiscard]] policy::Mode mode() const noexcept { return data_->mode; } + [[nodiscard]] const std::string& attempt_id() const noexcept { return data_->attempt_id; } + [[nodiscard]] const policy::Id16& epoch_id() const noexcept { return data_->epoch_id; } + [[nodiscard]] const policy::Digest32& policy_digest() const noexcept { return data_->policy_digest; } + [[nodiscard]] const AuthenticatedPeer& peer() const noexcept { return data_->peer; } + [[nodiscard]] RpcMethod method() const noexcept { return data_->method; } + [[nodiscard]] const std::optional& replica_slot() const noexcept { + return data_->replica_slot; + } + [[nodiscard]] const std::optional& replica_incarnation() const noexcept { + return data_->replica_incarnation; + } + [[nodiscard]] const std::shared_ptr& registry() const noexcept { + return data_->peer.registry(); + } + + private: + friend class AuthorizationResolver; + struct Payload final { + Payload(const AuthenticatedPeer& peer_arg, RpcMethod method_arg, + std::string tenant_arg, std::string operation_arg, + std::uint64_t cost_arg, policy::Mode mode_arg, + std::string attempt_arg, policy::Id16 epoch_arg, + policy::Digest32 digest_arg, + std::optional slot_arg, + std::optional incarnation_arg) + : peer(peer_arg), method(method_arg), tenant_id(std::move(tenant_arg)), + operation_id(std::move(operation_arg)), cost_units(cost_arg), mode(mode_arg), + attempt_id(std::move(attempt_arg)), epoch_id(epoch_arg), + policy_digest(digest_arg), replica_slot(slot_arg), + replica_incarnation(incarnation_arg) {} + AuthenticatedPeer peer; + RpcMethod method; + std::string tenant_id; + std::string operation_id; + std::uint64_t cost_units; + policy::Mode mode; + std::string attempt_id; + policy::Id16 epoch_id; + policy::Digest32 policy_digest; + std::optional replica_slot; + std::optional replica_incarnation; + }; + explicit AuthorizedOperation(std::shared_ptr data) noexcept + : data_(std::move(data)) {} + std::shared_ptr data_; +}; + +class AuthorizedGrant final { + public: + AuthorizedGrant(const AuthorizedGrant&) = default; + AuthorizedGrant& operator=(const AuthorizedGrant&) = default; + // Authorizes the request only; it does not mean a debit or grant committed. + [[nodiscard]] const std::string& tenant_id() const noexcept { return data_->tenant_id; } + [[nodiscard]] const std::string& operation_id() const noexcept { return data_->operation_id; } + [[nodiscard]] std::uint64_t cost_units() const noexcept { return data_->cost_units; } + [[nodiscard]] std::uint32_t slot() const noexcept { return data_->slot; } + [[nodiscard]] const policy::Id16& incarnation_id() const noexcept { return data_->incarnation_id; } + [[nodiscard]] std::uint64_t sequence() const noexcept { return data_->sequence; } + [[nodiscard]] const policy::Id16& epoch_id() const noexcept { return data_->epoch_id; } + [[nodiscard]] const policy::Digest32& policy_digest() const noexcept { return data_->policy_digest; } + [[nodiscard]] const AuthenticatedPeer& peer() const noexcept { return data_->peer; } + [[nodiscard]] RpcMethod method() const noexcept { return data_->method; } + [[nodiscard]] const std::shared_ptr& registry() const noexcept { + return data_->peer.registry(); + } + + private: + friend class AuthorizationResolver; + struct Payload final { + Payload(const AuthenticatedPeer& peer_arg, RpcMethod method_arg, + std::string tenant_arg, std::string operation_arg, + std::uint64_t cost_arg, std::uint32_t slot_arg, + policy::Id16 incarnation_arg, std::uint64_t sequence_arg, + policy::Id16 epoch_arg, policy::Digest32 digest_arg) + : peer(peer_arg), method(method_arg), tenant_id(std::move(tenant_arg)), + operation_id(std::move(operation_arg)), cost_units(cost_arg), + slot(slot_arg), incarnation_id(incarnation_arg), sequence(sequence_arg), + epoch_id(epoch_arg), policy_digest(digest_arg) {} + AuthenticatedPeer peer; + RpcMethod method; + std::string tenant_id; + std::string operation_id; + std::uint64_t cost_units; + std::uint32_t slot; + policy::Id16 incarnation_id; + std::uint64_t sequence; + policy::Id16 epoch_id; + policy::Digest32 policy_digest; + }; + explicit AuthorizedGrant(std::shared_ptr data) noexcept + : data_(std::move(data)) {} + std::shared_ptr data_; +}; + +class AuthorizationResolver final { + public: + [[nodiscard]] static std::variant Create( + std::shared_ptr registry, + ITrustedWallClock& trusted_clock); + + [[nodiscard]] std::variant Resolve( + const AuthenticatedPeer& peer, RpcMethod method, + const rateguard::v1::CheckAdmissionRequest& request) const noexcept; + + [[nodiscard]] std::variant Resolve( + const AuthenticatedPeer& peer, RpcMethod method, + const rateguard::v1::AcquireCreditRequest& request) const noexcept; + + private: + AuthorizationResolver(std::shared_ptr registry, + ITrustedWallClock& trusted_clock) noexcept + : registry_(std::move(registry)), trusted_clock_(trusted_clock) {} + + [[nodiscard]] std::optional CheckPeerAndClock( + const AuthenticatedPeer& peer) const; + + std::shared_ptr registry_; + ITrustedWallClock& trusted_clock_; +}; + +} // namespace rateguard::security diff --git a/include/rateguard/security/certificate_registry.h b/include/rateguard/security/certificate_registry.h new file mode 100644 index 0000000..fb6e5ad --- /dev/null +++ b/include/rateguard/security/certificate_registry.h @@ -0,0 +1,119 @@ +#pragma once + +#include "rateguard/security/peer_identity.h" +#include "security/trusted_wall_clock.h" +#include "policy/canonical_codec.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::security { + +struct CertificateValidityWindow final { + WallTime not_before; + WallTime not_after; + [[nodiscard]] bool Contains(WallTime time) const noexcept { + if (time.unix_seconds < 0 || time.nanoseconds >= 1'000'000'000U) return false; + return !(time < not_before) && time < not_after; + } +}; + +struct RegisteredCertificate final { + RegisteredPeer peer; + CertificateValidityWindow validity; +}; + +enum class CertificateRegistryErrorCode : std::uint8_t { + NullPolicy, + ClockUntrusted, + ResourceLimit, + InvalidPem, + InvalidRootProfile, + RootFingerprintMismatch, + LeafCountMismatch, + DuplicateLeaf, + UnknownPrincipal, + MissingPrincipal, + IdentityMismatch, + InvalidLeafProfile, + InvalidChain, + CertificateNotYetValid, + CertificateExpired, + PolicyDigestFailure, + CryptoFailure, +}; + +// Intentionally contains only a bounded code, never parser input or OpenSSL text. +struct CertificateRegistryError final { + CertificateRegistryErrorCode code; +}; + +template +using CertificateRegistryResult = std::variant; + +class CertificateRegistry final { + public: + static constexpr std::size_t kMaxCertificatePemBytes = 64U * 1024U; + static constexpr std::size_t kMaxAggregatePemBytes = 64U * 1024U * 1024U; + static constexpr std::size_t kMaxPrincipalCount = 10'000; + + [[nodiscard]] const RegisteredCertificate* Find( + std::string_view exact_uri) const noexcept; + [[nodiscard]] const CertificateValidityWindow& root_validity() const noexcept { + return root_validity_; + } + [[nodiscard]] const policy::Digest32& root_der_sha256() const noexcept { + return root_der_sha256_; + } + [[nodiscard]] const policy::Digest32& policy_digest() const noexcept { + return policy_digest_; + } + [[nodiscard]] const policy::Id16& epoch_id() const noexcept; + [[nodiscard]] const policy::Id16& authority_incarnation() const noexcept; + [[nodiscard]] const policy::PolicySnapshot& policy() const noexcept; + [[nodiscard]] const std::vector& peers() const noexcept { + return peers_; + } + [[nodiscard]] std::shared_ptr peer_pins() const noexcept { + return peer_pins_; + } + [[nodiscard]] WallTime validated_at() const noexcept { return validated_at_; } + [[nodiscard]] bool AllValidAt(WallTime time) const noexcept; + + private: + friend class CertificateRegistryLoader; + CertificateRegistry(std::shared_ptr policy, + policy::Digest32 policy_digest, + policy::Digest32 root_der_sha256, + CertificateValidityWindow root_validity, + std::vector peers, + std::shared_ptr peer_pins, + WallTime validated_at); + + std::shared_ptr policy_; + policy::Digest32 policy_digest_{}; + policy::Digest32 root_der_sha256_{}; + CertificateValidityWindow root_validity_{}; + std::vector peers_; + std::shared_ptr peer_pins_; + WallTime validated_at_{}; +}; + +// Validates typed, already-owned public certificate material against the +// immutable policy. No manifest encoding, filesystem access, or private keys. +class CertificateRegistryLoader final { + public: + [[nodiscard]] static CertificateRegistryResult< + std::shared_ptr> + Load(std::shared_ptr policy, + std::string_view root_certificate_pem, + std::span leaf_certificate_pems, + ITrustedWallClock& trusted_clock); +}; + +} // namespace rateguard::security diff --git a/include/rateguard/security/client_call_guard.h b/include/rateguard/security/client_call_guard.h new file mode 100644 index 0000000..1e2afef --- /dev/null +++ b/include/rateguard/security/client_call_guard.h @@ -0,0 +1,124 @@ +#pragma once + +#include "rateguard/security/certificate_registry.h" +#include "security/trusted_wall_clock.h" + +#include +#include +#include +#include +#include +#include + +namespace rateguard::security { + +enum class ClientCallPurpose : std::uint8_t { + AdapterToReplicaAdmission, + ReplicaToAuthority, +}; + +enum class ClientGuardFailureReason : std::uint8_t { + NullRegistry, + PolicyBindingMismatch, + InvalidClientIdentity, + InvalidServerIdentity, + ClientRoleMismatch, + ServerRoleMismatch, + MissingClientCertificate, + MissingServerCertificate, + ClockUntrusted, + DependencyFailure, + InvalidWallTime, + RootNotYetValid, + RootExpired, + ClientNotYetValid, + ClientExpired, + ServerNotYetValid, + ServerExpired, + ForeignPreparedCall, +}; + +enum class ClientGuardDisposition : std::uint8_t { + // Local trust classification only; this is not a downstream RPC status. + CredentialInvalid, + ApplicationUnavailable, +}; + +struct ClientCallGuardFailure final { + ClientGuardFailureReason reason; + ClientGuardDisposition disposition; +}; + +namespace detail { +struct ClientCallBinding final { + std::shared_ptr registry; + policy::Id16 epoch_id{}; + policy::Digest32 policy_digest{}; + ClientCallPurpose purpose{}; + std::string local_uri; + std::string expected_server_uri; +}; + +struct ClientCallProofPayload final { + std::shared_ptr binding; + WallTime checked_at{}; +}; +} // namespace detail + +class ClientCallGuard; + +class PreparedClientCall final { + public: + PreparedClientCall(const PreparedClientCall&) = default; + PreparedClientCall& operator=(const PreparedClientCall&) = default; + + private: + friend class ClientCallGuard; + explicit PreparedClientCall( + std::shared_ptr payload) noexcept + : payload_(std::move(payload)) {} + std::shared_ptr payload_; +}; + +// A fresh time-validation proof only. It is not a downstream ALLOW, deadline +// result, epoch-active check, or forwarding permit. +class ClientCallGuardPassed final { + public: + ClientCallGuardPassed(const ClientCallGuardPassed&) = default; + ClientCallGuardPassed& operator=(const ClientCallGuardPassed&) = default; + + private: + friend class ClientCallGuard; + explicit ClientCallGuardPassed( + std::shared_ptr payload) noexcept + : payload_(std::move(payload)) {} + std::shared_ptr payload_; +}; + +class ClientCallGuard final { + public: + [[nodiscard]] static std::variant Create( + std::shared_ptr registry, + ITrustedWallClock& trusted_clock, ClientCallPurpose purpose, + std::string local_uri, std::string expected_server_uri); + + [[nodiscard]] std::variant + ValidateBeforeCall() const; + + [[nodiscard]] std::variant + ValidateBeforeForward(const PreparedClientCall& prepared) const; + + private: + // The injected clock is non-owning and must outlive this guard and calls. + ClientCallGuard(std::shared_ptr binding, + ITrustedWallClock& trusted_clock) noexcept + : binding_(std::move(binding)), trusted_clock_(trusted_clock) {} + + [[nodiscard]] std::variant + ValidateCurrentTime() const; + + std::shared_ptr binding_; + ITrustedWallClock& trusted_clock_; +}; + +} // namespace rateguard::security diff --git a/include/rateguard/security/peer_authenticator.h b/include/rateguard/security/peer_authenticator.h new file mode 100644 index 0000000..72537c6 --- /dev/null +++ b/include/rateguard/security/peer_authenticator.h @@ -0,0 +1,106 @@ +#pragma once + +#include "rateguard/security/certificate_registry.h" +#include "security/trusted_wall_clock.h" + +#include +#include + +#include +#include +#include +#include +#include + +namespace rateguard::security { + +enum class PeerAuthFailureReason : std::uint8_t { + NullRegistry, + UnauthenticatedContext, + MissingOrAmbiguousTransport, + UnsupportedTransport, + MissingOrAmbiguousUri, + InvalidUri, + MissingOrAmbiguousLeaf, + OversizedLeaf, + InvalidLeafPem, + UnregisteredUri, + LeafPinMismatch, + ClockUntrusted, + CertificateNotYetValid, + CertificateExpired, + CryptoFailure, +}; + +enum class PeerAuthDisposition : std::uint8_t { + Unauthenticated, + ApplicationUnavailable, +}; + +enum class RpcMethod : std::uint8_t { + AdapterCheckAdmission, + ReplicaStrictCheck, + ReplicaAcquireCredit, +}; + +// Bounded reason/disposition only. The RPC handler supplies commitment phase +// when translating failures; this type never guesses it. +struct PeerAuthFailure final { + PeerAuthFailureReason reason; + PeerAuthDisposition disposition; +}; + +class PeerAuthenticator; + +// An opaque, copyable identity proof. Its private constructor prevents callers +// from manufacturing a trusted principal; holding the registry pins its record +// and lifetime to the exact validated epoch snapshot. +class AuthenticatedPeer final { + public: + AuthenticatedPeer(const AuthenticatedPeer&) = default; + AuthenticatedPeer& operator=(const AuthenticatedPeer&) = default; + // Explicit copy operations suppress implicit move operations. Even an + // rvalue therefore copies the registry owner and remains a live proof. + [[nodiscard]] const std::string& uri() const noexcept { return payload_->uri; } + [[nodiscard]] PeerRole role() const noexcept { return payload_->role; } + [[nodiscard]] const RegisteredCertificate* certificate() const noexcept { + return payload_->registry->Find(payload_->uri); + } + [[nodiscard]] const std::shared_ptr& registry() const noexcept { + return payload_->registry; + } + + private: + struct Payload final { + std::shared_ptr registry; + std::string uri; + PeerRole role; + }; + + friend class PeerAuthenticator; + AuthenticatedPeer(std::shared_ptr registry, + const RegisteredCertificate* certificate) + : payload_(std::make_shared(Payload{ + std::move(registry), certificate == nullptr ? std::string{} : certificate->peer.uri, + certificate == nullptr ? PeerRole::kAdapter : certificate->peer.role})) {} + + // One immutable allocation makes copy assignment atomic with respect to all + // capability fields: allocation can fail only while constructing a new proof. + std::shared_ptr payload_; +}; + +class PeerAuthenticator final { + public: + PeerAuthenticator(std::shared_ptr registry, + ITrustedWallClock& trusted_clock) noexcept + : registry_(std::move(registry)), trusted_clock_(trusted_clock) {} + + [[nodiscard]] std::variant Authenticate( + const grpc::AuthContext& auth_context) const noexcept; + + private: + std::shared_ptr registry_; + ITrustedWallClock& trusted_clock_; +}; + +} // namespace rateguard::security diff --git a/include/rateguard/security/peer_identity.h b/include/rateguard/security/peer_identity.h new file mode 100644 index 0000000..3c72317 --- /dev/null +++ b/include/rateguard/security/peer_identity.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::security { + +enum class PeerRole : std::uint32_t { kAdapter = 1, kReplica = 2, kAuthority = 3 }; +using Sha256Digest = std::array; + +struct RegisteredPeer final { + std::string uri; + PeerRole role; + Sha256Digest leaf_der_sha256; +}; + +// Construct only from an already validated, immutable epoch manifest. URI +// values are exact byte strings; this class performs no URI normalization. +class PeerRegistry final { + public: + explicit PeerRegistry(std::vector records); + const RegisteredPeer* Find(std::string_view exact_uri) const noexcept; + bool valid() const noexcept { return valid_; } + + private: + std::map> records_; + bool valid_ = true; +}; + +struct ExpectedPeer final { + std::string exact_uri; + Sha256Digest leaf_der_sha256; + PeerRole role; +}; + +} // namespace rateguard::security diff --git a/include/rateguard/security/pinned_peer_rpc_client.h b/include/rateguard/security/pinned_peer_rpc_client.h new file mode 100644 index 0000000..fb48442 --- /dev/null +++ b/include/rateguard/security/pinned_peer_rpc_client.h @@ -0,0 +1,148 @@ +#pragma once + +#include "proto/rateguard/v1/admission.grpc.pb.h" +#include "proto/rateguard/v1/authority.grpc.pb.h" +#include "rateguard/security/client_call_guard.h" + +#include +#include +#include +#include +#include +#include + +#include + +namespace rateguard::security { + +// Secrets are accepted only as bounded in-memory inputs. The factory never +// reports their contents or OpenSSL parser diagnostics. +struct PinnedPeerClientConfig final { + ClientCallPurpose purpose{ClientCallPurpose::AdapterToReplicaAdmission}; + std::string target; + std::string local_uri; + std::string expected_server_uri; + std::string root_certificate_pem; + std::string local_certificate_pem; + std::string local_private_key_pem; +}; + +enum class PinnedClientFactoryFailureReason : std::uint8_t { + NullRegistry, + InvalidTarget, + OversizedCredential, + InvalidRootPem, + RootPinMismatch, + InvalidClientCertificatePem, + ClientPinMismatch, + InvalidPrivateKeyPem, + PrivateKeyMismatch, + InvalidEndpointBinding, + CredentialConstructionFailed, + ChannelConstructionFailed, + StubConstructionFailed, + DependencyFailure, +}; + +struct PinnedClientFactoryFailure final { + PinnedClientFactoryFailureReason reason; + ClientGuardDisposition disposition; +}; + +enum class PinnedClientCallFailureReason : std::uint8_t { + PurposeMethodMismatch, + PolicyModeMismatch, + InvalidDeadline, + OversizedRequest, + GuardRejected, + LocalAllocationFailure, +}; + +struct PinnedClientCallFailure final { + PinnedClientCallFailureReason reason; + std::optional guard_failure; +}; + +// This result means the generated stub was never invoked for this attempt. +// It carries no gRPC status and no application response. +struct NotSent final { + PinnedClientCallFailure failure; +}; + +// The stub was invoked exactly once. Status and response are raw transport +// data; they are not a trusted ALLOW, grant, or commitment proof. +template +class Invoked final { + public: + Invoked(const Invoked&) = default; + Invoked& operator=(const Invoked&) = default; + + [[nodiscard]] bool has_transport_status() const noexcept { + return payload_->transport_status.has_value(); + } + [[nodiscard]] const std::optional& transport_status() const noexcept { + return payload_->transport_status; + } + [[nodiscard]] const Response& raw_response() const noexcept { return payload_->response; } + + private: + friend class PinnedPeerRpcClient; + struct Payload final { + explicit Payload(const PreparedClientCall& prepared) : proof(prepared) {} + std::optional transport_status; + Response response; + PreparedClientCall proof; + }; + explicit Invoked(std::shared_ptr payload) noexcept + : payload_(std::move(payload)) {} + + std::shared_ptr payload_; +}; + +template +using PinnedClientCallResult = std::variant>; + +// Owns its credentials, channel, generated stub and immutable endpoint binding. +// No channel, credentials, or stub accessor is provided. +class PinnedPeerRpcClient final { + public: + PinnedPeerRpcClient(const PinnedPeerRpcClient&) = delete; + PinnedPeerRpcClient& operator=(const PinnedPeerRpcClient&) = delete; + PinnedPeerRpcClient(PinnedPeerRpcClient&&) noexcept; + PinnedPeerRpcClient& operator=(PinnedPeerRpcClient&&) noexcept; + ~PinnedPeerRpcClient(); + + [[nodiscard]] static std::variant + Create(PinnedPeerClientConfig config, + std::shared_ptr registry, + ITrustedWallClock& trusted_clock) noexcept; + + [[nodiscard]] PinnedClientCallResult + CheckAdmission(const rateguard::v1::CheckAdmissionRequest& request, + std::chrono::system_clock::time_point deadline) noexcept; + + [[nodiscard]] PinnedClientCallResult + StrictCheck(const rateguard::v1::CheckAdmissionRequest& request, + std::chrono::system_clock::time_point deadline) noexcept; + + [[nodiscard]] PinnedClientCallResult + AcquireCredit(const rateguard::v1::AcquireCreditRequest& request, + std::chrono::system_clock::time_point deadline) noexcept; + + // Revalidates only the certificate/time guard for an adapter response. + // The caller must separately require a timely application ALLOW and an + // active epoch before forwarding. This method never forwards or commits. + [[nodiscard]] std::variant + ValidateBeforeForward( + const Invoked& invocation) const noexcept; + + private: + struct Impl; + explicit PinnedPeerRpcClient(std::unique_ptr impl) noexcept; + template + PinnedClientCallResult InvokeOnce( + std::chrono::system_clock::time_point deadline, RpcCall&& rpc_call) noexcept; + std::unique_ptr impl_; +}; + +} // namespace rateguard::security diff --git a/include/rateguard/security/tls_certificate_verifier.h b/include/rateguard/security/tls_certificate_verifier.h new file mode 100644 index 0000000..cd4d1ab --- /dev/null +++ b/include/rateguard/security/tls_certificate_verifier.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include + +#include + +#include "rateguard/security/peer_identity.h" + +namespace rateguard::security { + +// Verifies the peer leaf identity after gRPC's normal TLS chain validation. +// With expected set, this is a channel-specific pin. Without it, the peer must +// match a registered epoch leaf (server-side client authentication). +class PinnedPeerVerifier final : public grpc::experimental::ExternalCertificateVerifier { + public: + PinnedPeerVerifier(std::shared_ptr registry, + std::optional expected = std::nullopt); + bool Verify(grpc::experimental::TlsCustomVerificationCheckRequest* request, + std::function callback, + grpc::Status* sync_status) override; + void Cancel(grpc::experimental::TlsCustomVerificationCheckRequest*) override {} + + private: + std::shared_ptr registry_; + std::optional expected_; +}; + +} // namespace rateguard::security diff --git a/include/rateguard/v1/channel_policy.h b/include/rateguard/v1/channel_policy.h new file mode 100644 index 0000000..fad1351 --- /dev/null +++ b/include/rateguard/v1/channel_policy.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace rateguard::v1::transport { + +// Enforcement RPCs are state-changing. All retries, including transparent +// retries, must be decided by application logic so that uncertain commitment +// is surfaced instead of replayed invisibly by the transport. +[[nodiscard]] inline grpc::ChannelArguments EnforcementChannelArguments() { + grpc::ChannelArguments args; + args.SetInt(GRPC_ARG_ENABLE_RETRIES, 0); +#if defined(GRPC_ARG_EXPERIMENTAL_ENABLE_HEDGING) + args.SetInt(GRPC_ARG_EXPERIMENTAL_ENABLE_HEDGING, 0); +#endif + return args; +} + +// The enforcement channel factory ensures callers do not accidentally omit +// the no-retry policy when creating an authority/admission client channel. +[[nodiscard]] inline std::shared_ptr CreateEnforcementChannel( + const std::string& target, + const std::shared_ptr& credentials) { + if (target.empty() || !credentials) return {}; + return grpc::CreateCustomChannel(target, credentials, + EnforcementChannelArguments()); +} + +} // namespace rateguard::v1::transport diff --git a/include/rateguard/v1/error_contract.h b/include/rateguard/v1/error_contract.h new file mode 100644 index 0000000..5fb36b5 --- /dev/null +++ b/include/rateguard/v1/error_contract.h @@ -0,0 +1,187 @@ +#pragma once + +#include +#include +#include +#include + +namespace rateguard::v1::contract { + +enum class Commitment : std::uint8_t { + NotCommitted, + Possible, + Committed, +}; + +enum class RetryDisposition : std::uint8_t { + Never, + NewAttempt, + SameGrantSequence, +}; + +enum class ErrorCategory : std::uint8_t { + Input, + Authentication, + Authorization, + Capacity, + Dependency, + Deadline, + Internal, +}; + +enum class ErrorCode : std::uint8_t { + InvalidArgument, + Unauthenticated, + PermissionDenied, + PayloadTooLarge, + Unavailable, + DeadlineExceeded, + Cancelled, + Internal, +}; + +struct ServiceError { + ErrorCategory category; + ErrorCode code; + RetryDisposition retry; + Commitment commitment; +}; + +enum class GrpcStatus : std::uint8_t { + Ok, + InvalidArgument, + Unauthenticated, + PermissionDenied, + ResourceExhausted, + Unavailable, + DeadlineExceeded, + Cancelled, + Internal, +}; + +// This maps structured input/authentication failures to gRPC status. Quota +// outcomes and structured UNAVAILABLE/OVERLOADED are application responses +// and must use gRPC OK; they are deliberately not mapped by this function. +[[nodiscard]] constexpr GrpcStatus StatusFor(ErrorCode code) noexcept { + switch (code) { + case ErrorCode::InvalidArgument: + return GrpcStatus::InvalidArgument; + case ErrorCode::Unauthenticated: + return GrpcStatus::Unauthenticated; + case ErrorCode::PermissionDenied: + return GrpcStatus::PermissionDenied; + case ErrorCode::PayloadTooLarge: + return GrpcStatus::ResourceExhausted; + case ErrorCode::Unavailable: + return GrpcStatus::Unavailable; + case ErrorCode::DeadlineExceeded: + return GrpcStatus::DeadlineExceeded; + case ErrorCode::Cancelled: + return GrpcStatus::Cancelled; + case ErrorCode::Internal: + return GrpcStatus::Internal; + } + return GrpcStatus::Internal; +} + + +// A complete structured decision/grant response uses gRPC OK, including +// application UNAVAILABLE/OVERLOADED. Invalid/unauthenticated outcomes are +// represented by their gRPC transport status instead. +[[nodiscard]] constexpr GrpcStatus StructuredDecisionStatus(std::uint32_t raw) noexcept { + switch (raw) { + case 1: case 2: case 5: case 6: return GrpcStatus::Ok; + default: return GrpcStatus::Internal; + } +} +[[nodiscard]] constexpr GrpcStatus StructuredGrantStatus(std::uint32_t raw) noexcept { + switch (raw) { + case 1: case 2: case 4: case 5: return GrpcStatus::Ok; + default: return GrpcStatus::Internal; + } +} + +enum class DispatchPhase : std::uint8_t { + BeforeDispatch, + Dispatched, +}; +enum class RpcOperation : std::uint8_t { StrictAdmission, AcquireCredit }; +// Advisory caller action only; channel-level automatic retries/hedging remain +// disabled. A strict retry is a fresh chargeable attempt; credit resolution +// must preserve the same sequence and semantic fingerprint. +[[nodiscard]] constexpr RetryDisposition RetryDispositionFor( + RpcOperation operation, DispatchPhase) noexcept { + return operation == RpcOperation::AcquireCredit + ? RetryDisposition::SameGrantSequence + : RetryDisposition::NewAttempt; +} + +[[nodiscard]] constexpr Commitment CommitmentForTransportFailure( + DispatchPhase phase) noexcept { + return phase == DispatchPhase::BeforeDispatch ? Commitment::NotCommitted + : Commitment::Possible; +} + +enum class DecisionOutcome : std::uint32_t { + Unspecified = 0, + Allow = 1, + Limited = 2, + Invalid = 3, + Unauthenticated = 4, + Unavailable = 5, + Overloaded = 6, +}; + +enum class GrantOutcome : std::uint32_t { + Unspecified = 0, + Granted = 1, + Limited = 2, + Invalid = 3, + Unavailable = 4, + Overloaded = 5, +}; + +enum class AdmissionMode : std::uint32_t { + Unspecified = 0, + Strict = 1, + Credit = 2, +}; + +[[nodiscard]] constexpr bool IsKnownDecisionOutcome(std::uint32_t raw) noexcept { + return raw >= static_cast(DecisionOutcome::Allow) && + raw <= static_cast(DecisionOutcome::Overloaded); +} + +[[nodiscard]] constexpr bool IsKnownGrantOutcome(std::uint32_t raw) noexcept { + return raw >= static_cast(GrantOutcome::Granted) && + raw <= static_cast(GrantOutcome::Overloaded); +} + +[[nodiscard]] constexpr bool IsKnownAdmissionMode(std::uint32_t raw) noexcept { + return raw >= static_cast(AdmissionMode::Strict) && + raw <= static_cast(AdmissionMode::Credit); +} + +// A transport success alone is insufficient; only a timely, epoch-validated +// ALLOW is a forwarding permit. This helper intentionally checks only outcome. +[[nodiscard]] constexpr bool IsAllowOutcome(DecisionOutcome outcome) noexcept { + return outcome == DecisionOutcome::Allow; +} + +[[nodiscard]] inline bool IsValidIdentifier(std::string_view value) noexcept { + if (value.empty() || value.size() > 128) return false; + for (const unsigned char c : value) { + const bool alpha_num = (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9'); + if (!alpha_num && c != '_' && c != '.' && c != '-') return false; + } + return true; +} + +[[nodiscard]] inline bool HasExactWidth(std::string_view bytes, + std::size_t expected) noexcept { + return bytes.size() == expected; +} + +} // namespace rateguard::v1::contract diff --git a/include/rateguard/v1/request_validation.h b/include/rateguard/v1/request_validation.h new file mode 100644 index 0000000..73c25ad --- /dev/null +++ b/include/rateguard/v1/request_validation.h @@ -0,0 +1,103 @@ +#pragma once + +#include "proto/rateguard/v1/admission.pb.h" +#include "proto/rateguard/v1/authority.pb.h" +#include "rateguard/v1/error_contract.h" + +#include +#include +#include +#include +#include +#include + +namespace rateguard::v1::validation { + +inline constexpr std::size_t kMaxRequestBytes = 16 * 1024; +inline constexpr std::size_t kMaxRegisteredReplicaSlots = 8; +inline constexpr std::uint64_t kMaxPolicyUnits = 1000000000ULL; + +struct RegisteredReplicaSlot { + std::uint32_t slot; + std::string_view incarnation_id; +}; + +[[nodiscard]] inline std::optional +InvalidInput() noexcept { + return contract::ServiceError{ + contract::ErrorCategory::Input, + contract::ErrorCode::InvalidArgument, + contract::RetryDisposition::Never, + contract::Commitment::NotCommitted}; +} + +[[nodiscard]] inline std::optional +ValidateCheckAdmissionRequest(const CheckAdmissionRequest& request, + std::string_view configured_tenant, + std::string_view configured_operation, + std::string_view active_epoch_id, + std::string_view active_policy_digest) noexcept { + if (!contract::IsValidIdentifier(request.tenant_id()) || + !contract::IsValidIdentifier(request.operation_id()) || + !contract::HasExactWidth(request.attempt_id(), 16) || + !contract::HasExactWidth(request.epoch_id(), 16) || + !contract::HasExactWidth(request.policy_digest(), 32) || + request.tenant_id() != configured_tenant || + request.operation_id() != configured_operation || + request.epoch_id() != active_epoch_id || + request.policy_digest() != active_policy_digest || + request.ByteSizeLong() > kMaxRequestBytes) + return InvalidInput(); + return std::nullopt; +} + +// Tenant, slot registry, active epoch/digest, and operation/cost values come +// from the immutable authenticated epoch policy. Authenticate the caller and +// enforce the transport message-size cap before parsing; this post-decode +// ByteSizeLong check is defense in depth. Do not mutate state on failure. +[[nodiscard]] inline std::optional +ValidateAcquireCreditRequest( + const AcquireCreditRequest& request, + std::span registered_slots, + std::string_view configured_tenant, + std::string_view configured_operation, + std::string_view active_epoch_id, + std::string_view active_policy_digest, + std::uint64_t configured_cost_units, + std::uint64_t tenant_capacity_units) noexcept { + const auto registered = std::find_if( + registered_slots.begin(), registered_slots.end(), + [&](const RegisteredReplicaSlot& slot) { return slot.slot == request.slot(); }); + if (registered_slots.size() > kMaxRegisteredReplicaSlots || + !contract::IsValidIdentifier(request.tenant_id()) || + !contract::IsValidIdentifier(request.trigger_operation_id()) || + request.tenant_id() != configured_tenant || + request.trigger_operation_id() != configured_operation || + registered == registered_slots.end() || + !contract::HasExactWidth(registered->incarnation_id, 16) || + !contract::HasExactWidth(request.incarnation_id(), 16) || + request.incarnation_id() != registered->incarnation_id || + !contract::HasExactWidth(request.epoch_id(), 16) || + !contract::HasExactWidth(request.policy_digest(), 32) || + request.epoch_id() != active_epoch_id || + request.policy_digest() != active_policy_digest || + request.sequence() == 0 || + tenant_capacity_units == 0 || tenant_capacity_units > kMaxPolicyUnits || + configured_cost_units == 0 || configured_cost_units > tenant_capacity_units || + request.trigger_cost_units() != configured_cost_units || + request.ByteSizeLong() > kMaxRequestBytes) + return InvalidInput(); + return std::nullopt; +} + +[[nodiscard]] constexpr bool IsKnownDecisionOutcome(std::uint32_t raw) noexcept { + return contract::IsKnownDecisionOutcome(raw); +} +[[nodiscard]] constexpr bool IsKnownGrantOutcome(std::uint32_t raw) noexcept { + return contract::IsKnownGrantOutcome(raw); +} +[[nodiscard]] constexpr bool IsKnownAdmissionMode(std::uint32_t raw) noexcept { + return contract::IsKnownAdmissionMode(raw); +} + +} // namespace rateguard::v1::validation diff --git a/proto/rateguard/v1/admission.proto b/proto/rateguard/v1/admission.proto new file mode 100644 index 0000000..3f41cda --- /dev/null +++ b/proto/rateguard/v1/admission.proto @@ -0,0 +1,50 @@ +syntax = "proto3"; + +package rateguard.v1; + +// Wire contract only. Implementations must validate byte widths, identifier +// syntax, active epoch/policy binding, and reject UNSPECIFIED/unknown values. +enum DecisionOutcome { + DECISION_OUTCOME_UNSPECIFIED = 0; + DECISION_OUTCOME_ALLOW = 1; + DECISION_OUTCOME_LIMITED = 2; + DECISION_OUTCOME_INVALID = 3; + DECISION_OUTCOME_UNAUTHENTICATED = 4; + DECISION_OUTCOME_UNAVAILABLE = 5; + DECISION_OUTCOME_OVERLOADED = 6; +} + +enum AdmissionMode { + ADMISSION_MODE_UNSPECIFIED = 0; + ADMISSION_MODE_STRICT = 1; + ADMISSION_MODE_CREDIT = 2; +} + +// Deadline is supplied by the gRPC call context, not a request timestamp. +// Tenant and operation are selectors only; identity authorization comes from +// the authenticated adapter URI SAN and immutable epoch policy. Cost, mode, +// time, and deadline are never trusted from request fields. +message CheckAdmissionRequest { + string tenant_id = 1; + string operation_id = 2; + bytes attempt_id = 3; // exactly 16 bytes + bytes epoch_id = 4; // exactly 16 bytes + bytes policy_digest = 5; // exactly 32 bytes +} + +message AdmissionDecision { + DecisionOutcome outcome = 1; + bytes epoch_id = 2; // exactly 16 bytes + bytes policy_digest = 3; // exactly 32 bytes + AdmissionMode mode = 4; + bytes attempt_id = 5; // exactly 16 bytes + optional uint64 retry_delay_ns = 6; +} + +// Structured application outcomes, including UNAVAILABLE and OVERLOADED, +// are returned with gRPC OK. INVALID, UNAUTHENTICATED and unauthorized +// requests use INVALID_ARGUMENT, UNAUTHENTICATED and PERMISSION_DENIED. +// A transport failure after dispatch leaves commitment uncertain. +service AdmissionService { + rpc CheckAdmission(CheckAdmissionRequest) returns (AdmissionDecision); +} diff --git a/proto/rateguard/v1/authority.proto b/proto/rateguard/v1/authority.proto new file mode 100644 index 0000000..ff93946 --- /dev/null +++ b/proto/rateguard/v1/authority.proto @@ -0,0 +1,52 @@ +syntax = "proto3"; + +package rateguard.v1; + +import "proto/rateguard/v1/admission.proto"; + +enum GrantOutcome { + GRANT_OUTCOME_UNSPECIFIED = 0; + GRANT_OUTCOME_GRANTED = 1; + GRANT_OUTCOME_LIMITED = 2; + GRANT_OUTCOME_INVALID = 3; + GRANT_OUTCOME_UNAVAILABLE = 4; + GRANT_OUTCOME_OVERLOADED = 5; +} + +message AcquireCreditRequest { + string tenant_id = 1; + uint32 slot = 2; + bytes incarnation_id = 3; // exactly 16 bytes + bytes epoch_id = 4; // exactly 16 bytes + bytes policy_digest = 5; // exactly 32 bytes + uint64 sequence = 6; // nonzero; never wraps + uint64 trigger_cost_units = 7; + string trigger_operation_id = 8; +} + +// Canonical composite identity for one allocation. This is not an admission +// ALLOW and cannot itself authorize forwarding. +message CompositeGrantId { + bytes epoch_id = 1; // exactly 16 bytes + string tenant_id = 2; + uint32 slot = 3; + bytes incarnation_id = 4; // exactly 16 bytes + uint64 sequence = 5; +} + +message AcquireCreditResponse { + GrantOutcome grant_outcome = 1; + uint64 sequence = 2; + CompositeGrantId composite_grant_id = 3; + optional uint64 grant_units = 4; + bytes epoch_id = 5; // exactly 16 bytes + bytes policy_digest = 6; // exactly 32 bytes +} + +// This internal service is authenticated as a registered replica. The +// authority derives the trigger cost from immutable policy and rejects a +// mismatch. Same-sequence retries must preserve the exact request fingerprint. +service AuthorityService { + rpc StrictCheck(CheckAdmissionRequest) returns (AdmissionDecision); + rpc AcquireCredit(AcquireCreditRequest) returns (AcquireCreditResponse); +} diff --git a/src/authority/bucket_math.h b/src/authority/bucket_math.h new file mode 100644 index 0000000..1eb532e --- /dev/null +++ b/src/authority/bucket_math.h @@ -0,0 +1,140 @@ +#pragma once + +#include "rateguard/v1/error_contract.h" + +#include +#include +#include +#include + +namespace rateguard::authority { + +using ServiceError = rateguard::v1::contract::ServiceError; +using DecisionOutcome = rateguard::v1::contract::DecisionOutcome; + +template +using MathResult = std::variant; + +struct BucketPolicy { + std::uint64_t capacity_units; + std::uint64_t rate_units_per_second; +}; + +struct BucketState { + std::uint64_t balance_subunits; + std::uint64_t last_refill_ns; +}; + +struct BucketDecision { + DecisionOutcome outcome; + BucketState next; + std::optional retry_delay_ns; +}; + +// Pure integer arithmetic for token-bucket transitions. Time is monotonic +// nanoseconds; balances/costs are represented in 10^9 subunits per unit. +class BucketMath final { + public: + static constexpr std::uint64_t kSubunitsPerUnit = 1'000'000'000ULL; + static constexpr std::uint64_t kMaxPolicyUnits = 1'000'000'000ULL; + + [[nodiscard]] static MathResult Refill( + const BucketPolicy& policy, const BucketState& state, + std::uint64_t now_ns) { + if (!ValidPolicy(policy)) return InvalidInput(); + const std::uint64_t capacity_subunits = + policy.capacity_units * kSubunitsPerUnit; + if (state.balance_subunits > capacity_subunits || + now_ns < state.last_refill_ns) + return InternalFailure(); + + const std::uint64_t elapsed_ns = now_ns - state.last_refill_ns; + // With S=T=10^9, r*elapsed_ns*S/T is exactly r*elapsed_ns + // subunits. Keep the checked wide multiply even though legal input bounds + // currently fit unsigned 128-bit. + const uint128_t max128 = ~static_cast(0); + if (elapsed_ns != 0 && + static_cast(policy.rate_units_per_second) > + max128 / elapsed_ns) + return InternalFailure(); + const uint128_t refill_subunits = + static_cast(policy.rate_units_per_second) * elapsed_ns; + + const uint128_t balance = state.balance_subunits; + if (balance > max128 - refill_subunits) return InternalFailure(); + const uint128_t refilled = balance + refill_subunits; + const std::uint64_t next_balance = + refilled >= static_cast(capacity_subunits) + ? capacity_subunits + : static_cast(refilled); + return BucketState{next_balance, now_ns}; + } + + [[nodiscard]] static MathResult Decide( + const BucketPolicy& policy, const BucketState& state, + std::uint64_t cost_units, std::uint64_t now_ns) { + if (!ValidPolicy(policy) || cost_units == 0 || + cost_units > policy.capacity_units) + return InvalidInput(); + + auto refill_result = Refill(policy, state, now_ns); + if (const auto* error = std::get_if(&refill_result)) + return *error; + const BucketState available = std::get(refill_result); + const std::uint64_t cost_subunits = cost_units * kSubunitsPerUnit; + if (available.balance_subunits >= cost_subunits) { + return BucketDecision{DecisionOutcome::Allow, + {available.balance_subunits - cost_subunits, + available.last_refill_ns}, + std::nullopt}; + } + + const std::uint64_t deficit = cost_subunits - available.balance_subunits; + auto retry = RetryDelay(deficit, policy.rate_units_per_second); + if (const auto* error = std::get_if(&retry)) return *error; + return BucketDecision{DecisionOutcome::Limited, available, + std::get(retry)}; + } + + [[nodiscard]] static MathResult RetryDelay( + std::uint64_t deficit_subunits, std::uint64_t rate_units_per_second) { + if (rate_units_per_second == 0 || + rate_units_per_second > kMaxPolicyUnits) + return InvalidInput(); + const std::uint64_t quotient = deficit_subunits / rate_units_per_second; + const std::uint64_t remainder = deficit_subunits % rate_units_per_second; + if (remainder == 0) return quotient; + if (quotient == std::numeric_limits::max()) + return InternalFailure(); + return quotient + 1; + } + + private: +#if defined(__SIZEOF_INT128__) + using uint128_t = __uint128_t; +#else +#error "BucketMath requires compiler support for checked 128-bit integer arithmetic" +#endif + + [[nodiscard]] static constexpr bool ValidPolicy( + const BucketPolicy& policy) noexcept { + return policy.capacity_units >= 1 && + policy.capacity_units <= kMaxPolicyUnits && + policy.rate_units_per_second >= 1 && + policy.rate_units_per_second <= kMaxPolicyUnits; + } + + [[nodiscard]] static constexpr ServiceError InvalidInput() noexcept { + using namespace rateguard::v1::contract; + return {ErrorCategory::Input, ErrorCode::InvalidArgument, + RetryDisposition::Never, Commitment::NotCommitted}; + } + + [[nodiscard]] static constexpr ServiceError InternalFailure() noexcept { + using namespace rateguard::v1::contract; + return {ErrorCategory::Internal, ErrorCode::Internal, + RetryDisposition::Never, Commitment::NotCommitted}; + } +}; + +} // namespace rateguard::authority diff --git a/src/events/aggregate_metrics.h b/src/events/aggregate_metrics.h new file mode 100644 index 0000000..053d852 --- /dev/null +++ b/src/events/aggregate_metrics.h @@ -0,0 +1,131 @@ +#pragma once + +// Fixed-size aggregate counters for performance runs when detailed history is +// disabled. A snapshot is intended to be taken after all writers are quiesced. + +#include "src/events/event_recorder.h" + +#include +#include +#include +#include + +namespace rateguard::events::metrics { + +inline constexpr std::uint32_t kAggregateMetricsSchemaVersion = 1; +inline constexpr std::size_t kOwnerCount = 5; +inline constexpr std::size_t kStageCount = 6; +inline constexpr std::size_t kOutcomeCount = 8; +inline constexpr std::size_t kCounterCount = kOwnerCount * kStageCount * kOutcomeCount; + +enum class RecordResult : std::uint8_t { + Counted = 0, + CounterOverflow, + InvalidOwner, + InvalidStage, + InvalidOwnerStagePair, + InvalidOutcome, +}; + +struct AggregateSnapshot final { + std::uint32_t schema_version{kAggregateMetricsSchemaVersion}; + // Fixed indexes are Owner 1..5, Stage 1..6, Outcome 0..7. There are no + // caller-controlled labels or identifiers in this export shape. + std::array counts{}; + bool counter_overflow{false}; + + [[nodiscard]] constexpr bool exact() const noexcept { + return schema_version == kAggregateMetricsSchemaVersion && !counter_overflow; + } +}; + +namespace detail { + +struct IncrementStep final { + std::uint64_t value; + bool saturated; +}; + +[[nodiscard]] constexpr IncrementStep NextCounterValue(std::uint64_t current) noexcept { + constexpr auto max = UINT64_MAX; + return current == max ? IncrementStep{max, true} + : IncrementStep{current + 1, false}; +} + +// Shared atomic helper; on saturation the count remains UINT64_MAX and the +// sticky overflow flag is set. Callers must treat such a run as inexact. +[[nodiscard]] inline bool SaturatingIncrement(std::atomic& counter, + std::atomic& overflow) noexcept { + auto current = counter.load(std::memory_order_relaxed); + for (;;) { + const auto step = NextCounterValue(current); + if (step.saturated) { + overflow.store(true, std::memory_order_release); + return false; + } + if (counter.compare_exchange_weak(current, step.value, + std::memory_order_relaxed, + std::memory_order_relaxed)) + return true; + } +} + +[[nodiscard]] constexpr bool ValidOwner(std::uint8_t owner) noexcept { + return owner >= 1 && owner <= kOwnerCount; +} +[[nodiscard]] constexpr bool ValidStage(std::uint8_t stage) noexcept { + return stage >= 1 && stage <= kStageCount; +} +[[nodiscard]] constexpr bool ValidOutcome(std::uint8_t outcome) noexcept { + return outcome < kOutcomeCount; +} + +[[nodiscard]] constexpr std::size_t CounterIndex(std::uint8_t owner, + std::uint8_t stage, + std::uint8_t outcome) noexcept { + return ((static_cast(owner) - 1) * kStageCount + + (static_cast(stage) - 1)) * kOutcomeCount + outcome; +} + +} // namespace detail + +class AggregateMetrics final { + public: + AggregateMetrics() = default; + AggregateMetrics(const AggregateMetrics&) = delete; + AggregateMetrics& operator=(const AggregateMetrics&) = delete; + + // One call records exactly one bounded aggregate. No event ID, tenant ID, + // grant ID, arbitrary string, or dynamically allocated label is accepted. + [[nodiscard]] RecordResult Record(ProducerOwner owner, Stage stage, + Outcome outcome) noexcept { + const auto owner_value = static_cast(owner); + const auto stage_value = static_cast(stage); + const auto outcome_value = static_cast(outcome); + if (!detail::ValidOwner(owner_value)) return RecordResult::InvalidOwner; + if (!detail::ValidStage(stage_value)) return RecordResult::InvalidStage; + if (!detail::ValidOutcome(outcome_value)) return RecordResult::InvalidOutcome; + if (!::rateguard::events::detail::StageOwnedBy(owner, stage)) + return RecordResult::InvalidOwnerStagePair; + const auto index = detail::CounterIndex(owner_value, stage_value, outcome_value); + return detail::SaturatingIncrement(counts_[index], overflow_) + ? RecordResult::Counted + : RecordResult::CounterOverflow; + } + + // Counts are individually atomic, but this is not a cross-counter snapshot + // while writers are active. Stop/join writers before exporting final totals. + [[nodiscard]] AggregateSnapshot Snapshot() const noexcept { + AggregateSnapshot result; + for (std::size_t i = 0; i < counts_.size(); ++i) + result.counts[i] = counts_[i].load(std::memory_order_relaxed); + result.counter_overflow = overflow_.load(std::memory_order_acquire); + return result; + } + + private: + std::array, kCounterCount> counts_{}; + std::atomic overflow_{false}; +}; + +} // namespace rateguard::events::metrics diff --git a/src/events/event_recorder.h b/src/events/event_recorder.h new file mode 100644 index 0000000..f85acfb --- /dev/null +++ b/src/events/event_recorder.h @@ -0,0 +1,579 @@ +#pragma once + +// RG-005 Release A in-memory correctness-event recorder. +// This header is self-contained C++20 and deliberately records no arbitrary payload. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::events { + +using AttemptId = std::array; +using EpochId = std::array; +using PolicyDigest = std::array; + +inline constexpr std::uint32_t kEventSchemaVersion = 1; +inline constexpr std::uint64_t kMaxRunBudgetBytes = 1ULL << 30; +inline constexpr std::uint64_t kFnv1a64OffsetBasis = 14695981039346656037ULL; +inline constexpr std::uint64_t kFnv1a64Prime = 1099511628211ULL; +inline constexpr std::uint64_t kRunMagicBytes = 8; + +// Canonical fixed-width big-endian encoded extents. Header = magic[8], version[4], +// epoch[16], policy digest[32], producer count[4], planned bytes[8], budget[8]. +// Producer envelope = owner[1], index[4], capacity[8]. Slot = status[1], sequence[8], +// stage[1], outcome[1], attempt[16], timestamp[8], cost[8], checksum[8]. Seal = +// sealed[1], incomplete[1], reserved[8], published[8], checksum[8]. Terminal = +// complete[1], encoded byte count[8], run checksum[8]. Unused slots are encoded too. +inline constexpr std::uint64_t kRunHeaderEncodedBytes = 80; +inline constexpr std::uint64_t kProducerEnvelopeEncodedBytes = 13; +inline constexpr std::uint64_t kEventSlotEncodedBytes = 51; +inline constexpr std::uint64_t kProducerSealEncodedBytes = 26; +inline constexpr std::uint64_t kRunTerminalEncodedBytes = 17; + +// Enum values are part of the version-1 history encoding. +enum class ProducerOwner : std::uint8_t { + WorkloadGenerator = 1, + Authority = 2, + Replica = 3, + Adapter = 4, + Backend = 5, +}; + +enum class Stage : std::uint8_t { + Offered = 1, // WorkloadGenerator + StrictDecision = 2, // Authority + Responded = 3, // Replica + Received = 4, // Adapter + Forwarded = 5, // Adapter + Completed = 6, // Backend +}; + +enum class Outcome : std::uint8_t { + None = 0, + Allow = 1, + Limited = 2, + Invalid = 3, + Unauthenticated = 4, + Unavailable = 5, + Overloaded = 6, + Error = 7, +}; + +enum class SlotStatus : std::uint8_t { + Unused = 0, + Reserved = 1, + Published = 2, + Incomplete = 3, +}; + +enum class RecorderError : std::uint8_t { + None = 0, + InvalidPlan, + DuplicateProducer, + ProducerNotFound, + ProducerAlreadyAttached, + ProducerSealed, + RunStopped, + ProducerPartitionExhausted, + ForeignReservation, + ReservationAlreadyConsumed, + InvalidEvent, + AllocationFailure, +}; + +template +using Result = std::variant; + +struct EventV1 final { + Stage stage{Stage::Offered}; + Outcome outcome{Outcome::None}; + AttemptId attempt_id{}; + // Monotonic nanoseconds supplied by the owning stage at its event point. + // The recorder does not impose cross-producer timestamp ordering. + std::uint64_t timestamp_ns{0}; + std::uint64_t cost_units{0}; +}; + +struct ProducerSpec final { + ProducerOwner owner{ProducerOwner::WorkloadGenerator}; + std::uint32_t producer_index{0}; + std::uint64_t event_capacity{0}; +}; + +struct RunPlan final { + EpochId epoch_id{}; + PolicyDigest policy_digest{}; + std::vector producers; + // An exact fit is valid for a smaller test budget. The 1 GiB ceiling is exclusive. + std::uint64_t budget_bytes{kMaxRunBudgetBytes}; +}; + +struct EventSlotV1 final { + SlotStatus status{SlotStatus::Unused}; + std::uint64_t producer_sequence{0}; + EventV1 event{}; + std::uint64_t checksum64{0}; +}; + +struct ProducerSnapshotV1 final { + ProducerOwner owner{ProducerOwner::WorkloadGenerator}; + std::uint32_t producer_index{0}; + std::uint64_t capacity{0}; + // Count of allocated sequences; valid sequence numbers are [1,reserved_count]. + std::uint64_t reserved_count{0}; + std::uint64_t published_count{0}; + bool sealed{false}; + bool incomplete{false}; + std::vector slots; + std::uint64_t seal_checksum64{0}; +}; + +struct EventSnapshotV1 final { + std::uint32_t schema_version{kEventSchemaVersion}; + EpochId epoch_id{}; + PolicyDigest policy_digest{}; + // Exact fixed-width encoded extent, including every unused allowance slot. + std::uint64_t planned_bytes{0}; + std::uint64_t budget_bytes{0}; + bool complete{false}; + std::vector producers; + std::uint64_t checksum64{0}; +}; + +namespace detail { + +inline void FnvByte(std::uint64_t& hash, std::uint8_t byte) noexcept { + hash ^= byte; + hash *= kFnv1a64Prime; +} +inline void FnvU32(std::uint64_t& hash, std::uint32_t value) noexcept { + for (int shift = 24; shift >= 0; shift -= 8) + FnvByte(hash, static_cast(value >> shift)); +} +inline void FnvU64(std::uint64_t& hash, std::uint64_t value) noexcept { + for (int shift = 56; shift >= 0; shift -= 8) + FnvByte(hash, static_cast(value >> shift)); +} +template +inline void FnvArray(std::uint64_t& hash, const std::array& value) noexcept { + for (const auto byte : value) FnvByte(hash, byte); +} +inline void FnvTag(std::uint64_t& hash, const char* tag, std::size_t size) noexcept { + for (std::size_t i = 0; i < size; ++i) + FnvByte(hash, static_cast(tag[i])); +} + +inline std::uint64_t EventChecksum(const EventV1& event) noexcept { + auto hash = kFnv1a64OffsetBasis; + FnvTag(hash, "RGEV1", 5); + FnvByte(hash, static_cast(event.stage)); + FnvByte(hash, static_cast(event.outcome)); + FnvArray(hash, event.attempt_id); + FnvU64(hash, event.timestamp_ns); + FnvU64(hash, event.cost_units); + return hash; +} + +inline std::uint64_t ProducerSealChecksum(ProducerOwner owner, std::uint32_t index, + std::uint64_t capacity, std::uint64_t reserved, std::uint64_t published, + bool sealed, bool incomplete, std::span slots) noexcept { + auto hash = kFnv1a64OffsetBasis; + FnvTag(hash, "RGPS1", 5); + FnvByte(hash, static_cast(owner)); + FnvU32(hash, index); + FnvU64(hash, capacity); + FnvU64(hash, reserved); + FnvU64(hash, published); + FnvByte(hash, sealed ? 1 : 0); + FnvByte(hash, incomplete ? 1 : 0); + for (const auto& slot : slots) { + FnvByte(hash, static_cast(slot.status)); + FnvU64(hash, slot.producer_sequence); + FnvU64(hash, slot.checksum64); + } + return hash; +} + +inline std::uint64_t SnapshotChecksum(const EventSnapshotV1& snapshot) noexcept { + auto hash = kFnv1a64OffsetBasis; + FnvTag(hash, "RGRN1", 5); + FnvU32(hash, snapshot.schema_version); + FnvArray(hash, snapshot.epoch_id); + FnvArray(hash, snapshot.policy_digest); + FnvU32(hash, static_cast(snapshot.producers.size())); + FnvU64(hash, snapshot.planned_bytes); + FnvU64(hash, snapshot.budget_bytes); + for (const auto& producer : snapshot.producers) { + FnvByte(hash, static_cast(producer.owner)); + FnvU32(hash, producer.producer_index); + FnvU64(hash, producer.capacity); + FnvU64(hash, producer.seal_checksum64); + } + FnvByte(hash, snapshot.complete ? 1 : 0); + return hash; +} + +inline bool StageOwnedBy(ProducerOwner owner, Stage stage) noexcept { + switch (stage) { + case Stage::Offered: return owner == ProducerOwner::WorkloadGenerator; + case Stage::StrictDecision: return owner == ProducerOwner::Authority; + case Stage::Responded: return owner == ProducerOwner::Replica; + case Stage::Received: + case Stage::Forwarded: return owner == ProducerOwner::Adapter; + case Stage::Completed: return owner == ProducerOwner::Backend; + } + return false; +} + +inline bool ValidOutcome(Outcome outcome) noexcept { + return static_cast(outcome) <= static_cast(Outcome::Error); +} + +inline bool CheckedAdd(std::uint64_t& value, std::uint64_t addend) noexcept { + if (addend > std::numeric_limits::max() - value) return false; + value += addend; + return true; +} +inline bool CheckedMultiplyAdd(std::uint64_t& total, std::uint64_t count, + std::uint64_t extent) noexcept { + if (count != 0 && extent > std::numeric_limits::max() / count) return false; + return CheckedAdd(total, count * extent); +} + +struct ProducerState final { + explicit ProducerState(const ProducerSpec& spec) + : owner(spec.owner), producer_index(spec.producer_index), capacity(spec.event_capacity), + slots(static_cast(spec.event_capacity)) {} + + mutable std::mutex mutex; + ProducerOwner owner; + std::uint32_t producer_index; + std::uint64_t capacity; + std::uint64_t reserved_count{0}; + std::uint64_t published_count{0}; + bool attached{false}; + bool ever_attached{false}; + bool sealed{false}; + bool incomplete{false}; + std::vector slots; + std::uint64_t seal_checksum64{0}; +}; + +struct RunState final { + EpochId epoch_id{}; + PolicyDigest policy_digest{}; + std::uint64_t planned_bytes{0}; + std::uint64_t budget_bytes{0}; + std::atomic stopped{false}; + std::mutex attach_mutex; + std::vector> producers; +}; + +inline bool IsKnownOwner(ProducerOwner owner) noexcept { + return owner >= ProducerOwner::WorkloadGenerator && owner <= ProducerOwner::Backend; +} +inline bool ValidatePlan(const RunPlan& plan, std::uint64_t& planned_bytes) noexcept { + if (plan.producers.empty() || plan.producers.size() > std::numeric_limits::max() || + plan.budget_bytes > kMaxRunBudgetBytes || plan.budget_bytes < + kRunHeaderEncodedBytes + kRunTerminalEncodedBytes) return false; + planned_bytes = kRunHeaderEncodedBytes; + if (!CheckedAdd(planned_bytes, kRunTerminalEncodedBytes)) return false; + const auto producer_min = kProducerEnvelopeEncodedBytes + kProducerSealEncodedBytes + + kEventSlotEncodedBytes; + if (plan.producers.size() > (plan.budget_bytes - planned_bytes) / producer_min) return false; + for (std::size_t i = 0; i < plan.producers.size(); ++i) { + const auto& spec = plan.producers[i]; + if (!IsKnownOwner(spec.owner) || spec.event_capacity == 0 || + spec.event_capacity > static_cast(std::numeric_limits::max())) return false; + if (i != 0 && plan.producers[i - 1].owner == spec.owner && + plan.producers[i - 1].producer_index == spec.producer_index) return false; + if (!CheckedAdd(planned_bytes, kProducerEnvelopeEncodedBytes) || + !CheckedMultiplyAdd(planned_bytes, spec.event_capacity, kEventSlotEncodedBytes) || + !CheckedAdd(planned_bytes, kProducerSealEncodedBytes)) return false; + } + return planned_bytes <= plan.budget_bytes && planned_bytes < kMaxRunBudgetBytes; +} + +} // namespace detail + +class EventRecorder final { + public: + class ProducerHandle; + + class EventReservation final { + public: + EventReservation(const EventReservation&) = delete; + EventReservation& operator=(const EventReservation&) = delete; + EventReservation(EventReservation&& other) noexcept + : run_(std::move(other.run_)), producer_(std::move(other.producer_)), + sequence_(std::exchange(other.sequence_, 0)), consumed_(std::exchange(other.consumed_, true)) {} + EventReservation& operator=(EventReservation&& other) noexcept { + if (this == &other) return *this; + Abandon(); + run_ = std::move(other.run_); + producer_ = std::move(other.producer_); + sequence_ = std::exchange(other.sequence_, 0); + consumed_ = std::exchange(other.consumed_, true); + return *this; + } + ~EventReservation() { Abandon(); } + [[nodiscard]] std::uint64_t producer_sequence() const noexcept { return sequence_; } + + private: + friend class ProducerHandle; + EventReservation(std::shared_ptr run, + std::shared_ptr producer, + std::uint64_t sequence) noexcept + : run_(std::move(run)), producer_(std::move(producer)), sequence_(sequence) {} + void Abandon() noexcept { + if (consumed_ || !producer_ || sequence_ == 0) return; + std::lock_guard lock(producer_->mutex); + if (producer_->sealed) { consumed_ = true; return; } + auto& slot = producer_->slots[static_cast(sequence_ - 1)]; + if (slot.status == SlotStatus::Reserved && slot.producer_sequence == sequence_) { + slot.status = SlotStatus::Incomplete; + producer_->incomplete = true; + if (run_) run_->stopped.store(true, std::memory_order_release); + } + consumed_ = true; + } + std::shared_ptr run_; + std::shared_ptr producer_; + std::uint64_t sequence_{0}; + bool consumed_{false}; + }; + + class ProducerHandle final { + public: + ProducerHandle(const ProducerHandle&) = delete; + ProducerHandle& operator=(const ProducerHandle&) = delete; + ProducerHandle(ProducerHandle&& other) noexcept + : run_(std::move(other.run_)), producer_(std::move(other.producer_)), + detached_(std::exchange(other.detached_, true)) {} + ProducerHandle& operator=(ProducerHandle&& other) noexcept { + if (this == &other) return *this; + Detach(); + run_ = std::move(other.run_); + producer_ = std::move(other.producer_); + detached_ = std::exchange(other.detached_, true); + return *this; + } + ~ProducerHandle() { Detach(); } + + [[nodiscard]] Result Reserve() noexcept { + if (!run_ || !producer_) return RecorderError::ProducerNotFound; + std::lock_guard lock(producer_->mutex); + if (producer_->sealed) return RecorderError::ProducerSealed; + if (run_->stopped.load(std::memory_order_acquire)) return RecorderError::RunStopped; + if (producer_->reserved_count >= producer_->capacity) { + producer_->incomplete = true; + run_->stopped.store(true, std::memory_order_release); + return RecorderError::ProducerPartitionExhausted; + } + const auto sequence = ++producer_->reserved_count; + auto& slot = producer_->slots[static_cast(sequence - 1)]; + slot.status = SlotStatus::Reserved; + slot.producer_sequence = sequence; + return EventReservation(run_, producer_, sequence); + } + + [[nodiscard]] RecorderError Publish(EventReservation&& reservation, + const EventV1& event) noexcept { + if (!run_ || !producer_ || reservation.run_.get() != run_.get() || + reservation.producer_.get() != producer_.get()) return RecorderError::ForeignReservation; + if (reservation.consumed_ || reservation.sequence_ == 0) + return RecorderError::ReservationAlreadyConsumed; + std::lock_guard lock(producer_->mutex); + if (reservation.sequence_ > producer_->reserved_count || + reservation.sequence_ > producer_->slots.size()) { + reservation.consumed_ = true; + return RecorderError::ForeignReservation; + } + auto& slot = producer_->slots[static_cast(reservation.sequence_ - 1)]; + if (slot.status != SlotStatus::Reserved || + slot.producer_sequence != reservation.sequence_) { + reservation.consumed_ = true; + producer_->incomplete = true; + run_->stopped.store(true, std::memory_order_release); + return RecorderError::ReservationAlreadyConsumed; + } + if (producer_->sealed) { + reservation.consumed_ = true; + return RecorderError::ProducerSealed; + } + if (!detail::StageOwnedBy(producer_->owner, event.stage) || + !detail::ValidOutcome(event.outcome)) { + slot.status = SlotStatus::Incomplete; + producer_->incomplete = true; + run_->stopped.store(true, std::memory_order_release); + reservation.consumed_ = true; + return RecorderError::InvalidEvent; + } + slot.event = event; + slot.checksum64 = detail::EventChecksum(event); + slot.status = SlotStatus::Published; + ++producer_->published_count; + reservation.consumed_ = true; + return RecorderError::None; + } + + [[nodiscard]] RecorderError Seal() noexcept { return SealImpl(false); } + [[nodiscard]] RecorderError SealIncomplete() noexcept { return SealImpl(true); } + [[nodiscard]] ProducerOwner owner() const noexcept { + return producer_ ? producer_->owner : ProducerOwner::WorkloadGenerator; + } + [[nodiscard]] std::uint32_t producer_index() const noexcept { + return producer_ ? producer_->producer_index : 0; + } + + private: + friend class EventRecorder; + ProducerHandle(std::shared_ptr run, + std::shared_ptr producer) noexcept + : run_(std::move(run)), producer_(std::move(producer)) {} + RecorderError SealImpl(bool incomplete) noexcept { + if (!run_ || !producer_) return RecorderError::ProducerNotFound; + std::lock_guard lock(producer_->mutex); + if (producer_->sealed) return RecorderError::ProducerSealed; + if (incomplete || producer_->published_count != producer_->reserved_count) { + producer_->incomplete = true; + run_->stopped.store(true, std::memory_order_release); + } + producer_->sealed = true; + producer_->seal_checksum64 = detail::ProducerSealChecksum( + producer_->owner, producer_->producer_index, producer_->capacity, + producer_->reserved_count, producer_->published_count, producer_->sealed, + producer_->incomplete, producer_->slots); + return RecorderError::None; + } + void Detach() noexcept { + if (detached_ || !producer_) return; + std::lock_guard lock(producer_->mutex); + if (!producer_->sealed) { + producer_->incomplete = true; + if (run_) run_->stopped.store(true, std::memory_order_release); + } + producer_->attached = false; + detached_ = true; + } + std::shared_ptr run_; + std::shared_ptr producer_; + bool detached_{false}; + }; + + [[nodiscard]] static Result Create(RunPlan plan) noexcept { + std::uint64_t planned_bytes = 0; + std::sort(plan.producers.begin(), plan.producers.end(), [](const auto& a, const auto& b) { + return a.owner < b.owner || (a.owner == b.owner && a.producer_index < b.producer_index); + }); + if (!detail::ValidatePlan(plan, planned_bytes)) return RecorderError::InvalidPlan; + try { + auto run = std::make_shared(); + run->epoch_id = plan.epoch_id; + run->policy_digest = plan.policy_digest; + run->planned_bytes = planned_bytes; + run->budget_bytes = plan.budget_bytes; + run->producers.reserve(plan.producers.size()); + for (const auto& spec : plan.producers) + run->producers.push_back(std::make_shared(spec)); + return EventRecorder(std::move(run)); + } catch (...) { + return RecorderError::AllocationFailure; + } + } + + EventRecorder(const EventRecorder&) = delete; + EventRecorder& operator=(const EventRecorder&) = delete; + EventRecorder(EventRecorder&&) noexcept = default; + EventRecorder& operator=(EventRecorder&&) noexcept = default; + + [[nodiscard]] Result AttachProducer(ProducerOwner owner, + std::uint32_t index) noexcept { + if (!run_) return RecorderError::RunStopped; + std::lock_guard lock(run_->attach_mutex); + if (run_->stopped.load(std::memory_order_acquire)) return RecorderError::RunStopped; + for (const auto& producer : run_->producers) { + if (producer->owner != owner || producer->producer_index != index) continue; + std::lock_guard producer_lock(producer->mutex); + if (producer->attached || producer->ever_attached) return RecorderError::ProducerAlreadyAttached; + // Attachment is one-shot. A detached producer is never reusable. + producer->attached = true; + producer->ever_attached = true; + return ProducerHandle(run_, producer); + } + return RecorderError::ProducerNotFound; + } + + // Caller must quiesce all owners before export. An unsealed/missing producer, + // reserved gap, checksum inconsistency or stopped run is exported incomplete. + [[nodiscard]] Result ExportSnapshotV1() const noexcept { + if (!run_) return RecorderError::RunStopped; + try { + EventSnapshotV1 snapshot; + snapshot.epoch_id = run_->epoch_id; + snapshot.policy_digest = run_->policy_digest; + snapshot.planned_bytes = run_->planned_bytes; + snapshot.budget_bytes = run_->budget_bytes; + snapshot.producers.reserve(run_->producers.size()); + bool complete = !run_->stopped.load(std::memory_order_acquire); + for (const auto& producer : run_->producers) { + std::lock_guard lock(producer->mutex); + ProducerSnapshotV1 item; + item.owner = producer->owner; + item.producer_index = producer->producer_index; + item.capacity = producer->capacity; + item.reserved_count = producer->reserved_count; + item.published_count = producer->published_count; + item.sealed = producer->sealed; + item.incomplete = producer->incomplete; + item.slots = producer->slots; + item.seal_checksum64 = producer->seal_checksum64; + if (!item.sealed || item.incomplete || item.reserved_count != item.published_count || + item.seal_checksum64 != detail::ProducerSealChecksum( + item.owner, item.producer_index, item.capacity, item.reserved_count, + item.published_count, item.sealed, item.incomplete, item.slots)) complete = false; + for (std::size_t i = 0; i < item.slots.size(); ++i) { + const auto& slot = item.slots[i]; + if (i < item.reserved_count) { + if (slot.status != SlotStatus::Published || slot.producer_sequence != i + 1 || + slot.checksum64 != detail::EventChecksum(slot.event)) complete = false; + } else if (slot.status != SlotStatus::Unused || slot.producer_sequence != 0) { + complete = false; + } + } + snapshot.producers.push_back(std::move(item)); + } + snapshot.complete = complete; + snapshot.checksum64 = detail::SnapshotChecksum(snapshot); + return snapshot; + } catch (...) { + return RecorderError::AllocationFailure; + } + } + + [[nodiscard]] bool stopped() const noexcept { + return !run_ || run_->stopped.load(std::memory_order_acquire); + } + [[nodiscard]] std::uint64_t planned_bytes() const noexcept { + return run_ ? run_->planned_bytes : 0; + } + + private: + explicit EventRecorder(std::shared_ptr run) noexcept + : run_(std::move(run)) {} + std::shared_ptr run_; +}; + +} // namespace rateguard::events diff --git a/src/events/file_publisher.h b/src/events/file_publisher.h new file mode 100644 index 0000000..9642a7a --- /dev/null +++ b/src/events/file_publisher.h @@ -0,0 +1,292 @@ +#pragma once + +// POSIX durable publication for a validated strict-history snapshot. +// The caller must serialize all operations in the supplied private directory. + +#include "src/events/history_exporter.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace rateguard::events { + +using HistoryRunId = std::array; + +inline constexpr std::size_t kHistoryFileNameCapacity = 80; +inline constexpr std::string_view kHistoryFilePrefix = "rg-history-v1-"; +inline constexpr std::string_view kHistoryFileSuffix = ".bin"; +inline constexpr std::string_view kHistoryPartialSuffix = ".partial"; + +enum class FilePublishStatus : std::uint8_t { + Published, + IncompleteHistory, + InvalidCreationSecond, + InvalidDirectory, + TemporaryNameExists, + TemporaryOpenFailed, + TemporaryMetadataFailed, + WriteFailed, + FileSyncFailed, + FileCloseFailed, + FinalNameExists, + LinkFailed, + TemporaryUnlinkFailed, + DirectorySyncUncertain, +}; + +struct FilePublishResult final { + FilePublishStatus status{FilePublishStatus::WriteFailed}; + bool final_published{false}; + bool file_synced{false}; + bool temporary_removed{false}; + bool directory_synced{false}; + std::array final_name{}; + std::uint8_t final_name_size{0}; + + [[nodiscard]] std::string_view filename() const noexcept { + return {final_name.data(), final_name_size}; + } +}; + +namespace file_detail { + +inline constexpr char kHex[] = "0123456789abcdef"; + +class FixedName final { + public: + [[nodiscard]] bool Append(std::string_view value) noexcept { + if (value.size() > bytes_.size() - size_) return false; + for (char ch : value) bytes_[size_++] = ch; + return true; + } + [[nodiscard]] bool Append(char ch) noexcept { + if (size_ == bytes_.size()) return false; + bytes_[size_++] = ch; + return true; + } + [[nodiscard]] bool AppendDecimal(std::uint64_t value) noexcept { + std::array digits{}; + std::size_t count = 0; + do { + digits[count++] = static_cast('0' + (value % 10)); + value /= 10; + } while (value != 0 && count < digits.size()); + if (value != 0 || count > 12 || count > bytes_.size() - size_) return false; + while (count != 0) bytes_[size_++] = digits[--count]; + return true; + } + [[nodiscard]] bool AppendHex(const HistoryRunId& run_id) noexcept { + if (run_id.size() * 2 > bytes_.size() - size_) return false; + for (std::uint8_t byte : run_id) { + bytes_[size_++] = kHex[byte >> 4]; + bytes_[size_++] = kHex[byte & 0x0f]; + } + return true; + } + [[nodiscard]] const char* data() const noexcept { return bytes_.data(); } + [[nodiscard]] std::size_t size() const noexcept { return size_; } + [[nodiscard]] std::string_view view() const noexcept { return {bytes_.data(), size_}; } + + private: + std::array bytes_{}; + std::size_t size_{0}; +}; + +inline bool BuildNames(std::uint64_t creation_second, const HistoryRunId& run_id, + FixedName& final_name, FixedName& temporary_name) noexcept { + if (creation_second > 999'999'999'999ULL) return false; + if (!final_name.Append(kHistoryFilePrefix) || !final_name.AppendDecimal(creation_second) || + !final_name.Append('-') || !final_name.AppendHex(run_id) || + !final_name.Append(kHistoryFileSuffix)) return false; + temporary_name = final_name; + return temporary_name.Append(kHistoryPartialSuffix); +} + +inline bool IsPrivateDirectory(int directory_fd) noexcept { + struct stat info {}; + if (::fstat(directory_fd, &info) != 0 || !S_ISDIR(info.st_mode)) return false; + if (info.st_uid != ::geteuid()) return false; + return (info.st_mode & 07777) == 0700; +} + +inline bool WriteAll(int fd, const char* data, std::size_t size) noexcept { + while (size != 0) { + const auto written = ::write(fd, data, size); + if (written < 0) { + if (errno == EINTR) continue; + return false; + } + if (written == 0) return false; + data += written; + size -= static_cast(written); + } + return true; +} + +class FdStreamBuffer final : public std::streambuf { + public: + explicit FdStreamBuffer(int fd, std::uint64_t limit) noexcept : fd_(fd), limit_(limit) {} + + protected: + std::streamsize xsputn(const char* data, std::streamsize count) override { + if (count <= 0 || failed_) return 0; + const auto size = static_cast(count); + if (size > std::numeric_limits::max() || + size > limit_ - bytes_written_ || + !WriteAll(fd_, data, static_cast(size))) { + failed_ = true; + return 0; + } + bytes_written_ += size; + return count; + } + int_type overflow(int_type ch) override { + if (traits_type::eq_int_type(ch, traits_type::eof())) + return failed_ ? traits_type::eof() : traits_type::not_eof(ch); + if (failed_ || bytes_written_ == limit_) return traits_type::eof(); + const char value = traits_type::to_char_type(ch); + if (!WriteAll(fd_, &value, 1)) { + failed_ = true; + return traits_type::eof(); + } + ++bytes_written_; + return ch; + } + int sync() override { return failed_ ? -1 : 0; } + + public: + [[nodiscard]] std::uint64_t bytes_written() const noexcept { return bytes_written_; } + + private: + int fd_; + const std::uint64_t limit_; + bool failed_{false}; + std::uint64_t bytes_written_{0}; +}; + +inline void CopyName(FilePublishResult& result, const FixedName& name) noexcept { + const auto count = name.size() < result.final_name.size() ? name.size() : result.final_name.size(); + for (std::size_t i = 0; i < count; ++i) result.final_name[i] = name.data()[i]; + result.final_name_size = static_cast(count); +} + +inline bool RemoveTemporary(int directory_fd, const FixedName& name) noexcept { + if (::unlinkat(directory_fd, name.data(), 0) == 0) return true; + return errno == ENOENT; +} + +inline int FsyncRetry(int fd) noexcept { + int result = 0; + do { result = ::fsync(fd); } while (result != 0 && errno == EINTR); + return result; +} + +} // namespace file_detail + +// Stream the encoded export directly to a 0600 O_EXCL temporary file in the +// caller's already-open private directory. Hard-link publication is atomic and +// no-overwrite; a final-name collision never truncates or replaces an artifact. +// The exporter flushes the stream before the file is fsynced. The file is then +// linked under its final managed name, the temporary name unlinked, and the +// directory fsynced. A failed directory fsync means the final name is visible +// but its post-crash durability is uncertain; the result keeps that explicit. +inline FilePublishResult PublishStrictHistoryFile( + int private_directory_fd, std::uint64_t creation_second, + const HistoryRunId& run_id, const RunPlan& expected, + const EventSnapshotV1& snapshot) noexcept { + FilePublishResult result; + file_detail::FixedName final_name; + file_detail::FixedName temporary_name; + if (!file_detail::BuildNames(creation_second, run_id, final_name, temporary_name)) { + result.status = FilePublishStatus::InvalidCreationSecond; + return result; + } + file_detail::CopyName(result, final_name); + if (!file_detail::IsPrivateDirectory(private_directory_fd)) { + result.status = FilePublishStatus::InvalidDirectory; + return result; + } + + const int fd = ::openat(private_directory_fd, temporary_name.data(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, S_IRUSR | S_IWUSR); + if (fd < 0) { + result.status = errno == EEXIST ? FilePublishStatus::TemporaryNameExists + : FilePublishStatus::TemporaryOpenFailed; + return result; + } + if (::fchmod(fd, S_IRUSR | S_IWUSR) != 0) { + (void)::close(fd); + result.temporary_removed = file_detail::RemoveTemporary(private_directory_fd, temporary_name); + result.status = FilePublishStatus::TemporaryMetadataFailed; + return result; + } + + ExportStatus export_status = ExportStatus::WriteFailed; + std::uint64_t bytes_written = 0; + try { + file_detail::FdStreamBuffer buffer(fd, snapshot.planned_bytes); + std::ostream output(&buffer); + export_status = ExportStrictHistory(expected, snapshot, output); + bytes_written = buffer.bytes_written(); + } catch (...) { + (void)::close(fd); + result.temporary_removed = file_detail::RemoveTemporary(private_directory_fd, temporary_name); + result.status = FilePublishStatus::WriteFailed; + return result; + } + if (export_status != ExportStatus::Complete || bytes_written != snapshot.planned_bytes) { + (void)::close(fd); + result.temporary_removed = file_detail::RemoveTemporary(private_directory_fd, temporary_name); + result.status = export_status == ExportStatus::IncompleteHistory + ? FilePublishStatus::IncompleteHistory + : FilePublishStatus::WriteFailed; + return result; + } + + if (file_detail::FsyncRetry(fd) != 0) { + (void)::close(fd); + result.temporary_removed = file_detail::RemoveTemporary(private_directory_fd, temporary_name); + result.status = FilePublishStatus::FileSyncFailed; + return result; + } + result.file_synced = true; + if (::close(fd) != 0) { + result.temporary_removed = file_detail::RemoveTemporary(private_directory_fd, temporary_name); + result.status = FilePublishStatus::FileCloseFailed; + return result; + } + + if (::linkat(private_directory_fd, temporary_name.data(), private_directory_fd, + final_name.data(), 0) != 0) { + const bool final_exists = errno == EEXIST; + result.temporary_removed = file_detail::RemoveTemporary(private_directory_fd, temporary_name); + result.status = final_exists ? FilePublishStatus::FinalNameExists + : FilePublishStatus::LinkFailed; + return result; + } + result.final_published = true; + + result.temporary_removed = file_detail::RemoveTemporary(private_directory_fd, temporary_name); + const int sync_result = file_detail::FsyncRetry(private_directory_fd); + result.directory_synced = sync_result == 0; + if (!result.directory_synced) { + result.status = FilePublishStatus::DirectorySyncUncertain; + return result; + } + result.status = result.temporary_removed ? FilePublishStatus::Published + : FilePublishStatus::TemporaryUnlinkFailed; + return result; +} + +} // namespace rateguard::events diff --git a/src/events/history_exporter.h b/src/events/history_exporter.h new file mode 100644 index 0000000..a2ef374 --- /dev/null +++ b/src/events/history_exporter.h @@ -0,0 +1,77 @@ +#pragma once + +#include "src/events/history_validator.h" + +#include +#include +#include +#include + +namespace rateguard::events { + +// The caller supplies an unpublished binary stream. Only a successful return +// permits it to finalize the file; disk durability is the file owner's job. +enum class ExportStatus { Complete, IncompleteHistory, WriteFailed }; + +namespace wire { +template +void Integer(std::ostream& stream, T value) { + std::array bytes{}; + for (std::size_t i = bytes.size(); i > 0; --i) { + bytes[i - 1] = static_cast(value & 0xffU); + value = static_cast(static_cast(value) >> 8); + } + stream.write(reinterpret_cast(bytes.data()), bytes.size()); +} +template +void Bytes(std::ostream& stream, const std::array& bytes) { + stream.write(reinterpret_cast(bytes.data()), N); +} +} // namespace wire + +inline ExportStatus ExportStrictHistory(const RunPlan& expected, + const EventSnapshotV1& snapshot, + std::ostream& output) { + if (!validation::ValidateHistorySnapshot(snapshot, expected).complete()) + return ExportStatus::IncompleteHistory; + + try { + output.write("RGHIST01", 8); + wire::Integer(output, snapshot.schema_version); + wire::Bytes(output, snapshot.epoch_id); + wire::Bytes(output, snapshot.policy_digest); + wire::Integer(output, static_cast(snapshot.producers.size())); + wire::Integer(output, snapshot.planned_bytes); + wire::Integer(output, snapshot.budget_bytes); + for (const auto& producer : snapshot.producers) { + wire::Integer(output, static_cast(producer.owner)); + wire::Integer(output, producer.producer_index); + wire::Integer(output, producer.capacity); + for (const auto& slot : producer.slots) { + wire::Integer(output, static_cast(slot.status)); + wire::Integer(output, slot.producer_sequence); + wire::Integer(output, static_cast(slot.event.stage)); + wire::Integer(output, static_cast(slot.event.outcome)); + wire::Bytes(output, slot.event.attempt_id); + wire::Integer(output, slot.event.timestamp_ns); + wire::Integer(output, slot.event.cost_units); + wire::Integer(output, slot.checksum64); + if (!output) return ExportStatus::WriteFailed; + } + wire::Integer(output, static_cast(producer.sealed)); + wire::Integer(output, static_cast(producer.incomplete)); + wire::Integer(output, producer.reserved_count); + wire::Integer(output, producer.published_count); + wire::Integer(output, producer.seal_checksum64); + } + wire::Integer(output, static_cast(snapshot.complete)); + wire::Integer(output, snapshot.planned_bytes); + wire::Integer(output, snapshot.checksum64); + output.flush(); + return output ? ExportStatus::Complete : ExportStatus::WriteFailed; + } catch (...) { + return ExportStatus::WriteFailed; + } +} + +} // namespace rateguard::events diff --git a/src/events/history_validator.h b/src/events/history_validator.h new file mode 100644 index 0000000..da0c71e --- /dev/null +++ b/src/events/history_validator.h @@ -0,0 +1,335 @@ +#pragma once + +// Independent, read-only validator for version-1 EventRecorder snapshots. +// This deliberately recomputes the +// canonical checksums instead of calling recorder/checker helpers. + +#include "src/events/event_recorder.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::events::validation { + +inline constexpr std::uint64_t kMaximumRunBytes = std::uint64_t{1} << 30; + +enum class Verdict : std::uint8_t { Complete = 1, Incomplete = 2, Invalid = 3 }; +enum class Reason : std::uint8_t { + None = 0, + SnapshotIncomplete, + ProducerMissing, + ProducerUnexpected, + ProducerOrderOrCapacityMismatch, + ProducerNotSealed, + ProducerMarkedIncomplete, + ReservationGap, + ReservedSlotUnpublished, + PublishedCountMismatch, + InvalidSlotState, + InvalidEventEnum, + StageOwnerMismatch, + EventChecksumMismatch, + ProducerChecksumMismatch, + SnapshotChecksumMismatch, + SchemaMismatch, + InvalidByteAccounting, + RunBudgetExceeded, + InvalidExpectedPlan, + ExpectedPlanMismatch, + ValidatorResourceFailure, +}; + +struct Report final { + Verdict verdict{Verdict::Invalid}; + Reason reason{Reason::None}; + std::uint64_t published_events{}; + std::uint64_t snapshot_bytes{}; + + [[nodiscard]] constexpr bool complete() const noexcept { + return verdict == Verdict::Complete; + } + // A complete artifact is not, by itself, a safety proof. The independent + // history/model checker must still validate its semantics. + [[nodiscard]] constexpr bool safety_pass_allowed() const noexcept { + return false; + } +}; + +namespace detail { + +class Fnv1a64 final { + public: + void Bytes(const char* data, std::size_t size) noexcept { + for (std::size_t i = 0; i < size; ++i) { + value_ ^= static_cast(data[i]); + value_ *= 1099511628211ULL; + } + } + void U8(std::uint8_t value) noexcept { + const char byte = static_cast(value); + Bytes(&byte, 1); + } + void U32(std::uint32_t value) noexcept { + U8(static_cast(value >> 24)); + U8(static_cast(value >> 16)); + U8(static_cast(value >> 8)); + U8(static_cast(value)); + } + void U64(std::uint64_t value) noexcept { + U8(static_cast(value >> 56)); + U8(static_cast(value >> 48)); + U8(static_cast(value >> 40)); + U8(static_cast(value >> 32)); + U8(static_cast(value >> 24)); + U8(static_cast(value >> 16)); + U8(static_cast(value >> 8)); + U8(static_cast(value)); + } + template + void Fixed(const std::array& value) noexcept { + for (const auto byte : value) U8(byte); + } + [[nodiscard]] std::uint64_t value() const noexcept { return value_; } + + private: + std::uint64_t value_{14695981039346656037ULL}; +}; + +template +constexpr std::uint8_t U8(T value) noexcept { + return static_cast(value); +} + +template +std::uint64_t EventChecksum(const Event& event) noexcept { + Fnv1a64 hash; + hash.Bytes("RGEV1", 5); + hash.U8(U8(event.stage)); + hash.U8(U8(event.outcome)); + hash.Fixed(event.attempt_id); + hash.U64(event.timestamp_ns); + hash.U64(event.cost_units); + return hash.value(); +} + +template +std::uint64_t ProducerChecksum(const Producer& producer) noexcept { + Fnv1a64 hash; + hash.Bytes("RGPS1", 5); + hash.U8(U8(producer.owner)); + hash.U32(producer.producer_index); + hash.U64(producer.capacity); + hash.U64(producer.reserved_count); + hash.U64(producer.published_count); + hash.U8(producer.sealed ? 1 : 0); + hash.U8(producer.incomplete ? 1 : 0); + for (const auto& slot : producer.slots) { + hash.U8(U8(slot.status)); + hash.U64(slot.producer_sequence); + hash.U64(slot.checksum64); + } + return hash.value(); +} + +template +std::uint64_t SnapshotChecksum(const Snapshot& snapshot) noexcept { + Fnv1a64 hash; + hash.Bytes("RGRN1", 5); + hash.U32(snapshot.schema_version); + hash.Fixed(snapshot.epoch_id); + hash.Fixed(snapshot.policy_digest); + hash.U32(static_cast(snapshot.producers.size())); + hash.U64(snapshot.planned_bytes); + hash.U64(snapshot.budget_bytes); + for (const auto& producer : snapshot.producers) { + hash.U8(U8(producer.owner)); + hash.U32(producer.producer_index); + hash.U64(producer.capacity); + hash.U64(producer.seal_checksum64); + } + hash.U8(snapshot.complete ? 1 : 0); + return hash.value(); +} + +inline bool ValidStage(std::uint8_t stage) noexcept { return stage >= 1 && stage <= 6; } +inline bool ValidOutcome(std::uint8_t outcome) noexcept { return outcome <= 7; } +inline bool ValidOwner(std::uint8_t owner) noexcept { return owner >= 1 && owner <= 5; } +inline bool ValidSlotStatus(std::uint8_t status) noexcept { return status <= 3; } + +inline std::uint8_t OwnerForStage(std::uint8_t stage) noexcept { + switch (stage) { + case 1: return 1; // Offered -> workload generator + case 2: return 2; // Strict decision -> authority + case 3: return 3; // Responded -> replica + case 4: return 4; // Received -> adapter + case 5: return 4; // Forwarded -> adapter + case 6: return 5; // Completed -> backend + default: return 0; + } +} + +inline bool AddChecked(std::uint64_t& total, std::uint64_t value) noexcept { + if (value > std::numeric_limits::max() - total) return false; + total += value; + return true; +} + +inline bool MultiplyAddChecked(std::uint64_t& total, std::uint64_t count, + std::uint64_t extent) noexcept { + if (count != 0 && extent > std::numeric_limits::max() / count) + return false; + return AddChecked(total, count * extent); +} + +inline bool ExpectedPlanBytes(std::span producers, + std::uint64_t& bytes) noexcept { + // Independently frozen canonical extents for schema v1. Keep these literals + // separate from recorder helpers so a changed encoder cannot self-validate. + constexpr std::uint64_t kHeader = 80; // RGHIST01 + fixed header fields + constexpr std::uint64_t kProducerEnvelope = 13; + constexpr std::uint64_t kSlot = 51; + constexpr std::uint64_t kProducerSeal = 26; + constexpr std::uint64_t kTerminal = 17; + bytes = kHeader + kTerminal; + for (const auto& producer : producers) { + if (!AddChecked(bytes, kProducerEnvelope) || + !MultiplyAddChecked(bytes, producer.event_capacity, kSlot) || + !AddChecked(bytes, kProducerSeal)) return false; + } + return true; +} + +inline bool ValidExpectedPlan(std::span producers, + std::uint64_t budget_bytes, + std::uint64_t& planned_bytes) noexcept { + if (producers.empty() || producers.size() > std::numeric_limits::max() || + budget_bytes < 97 || budget_bytes > kMaximumRunBytes) + return false; + for (std::size_t i = 0; i < producers.size(); ++i) { + const auto owner = U8(producers[i].owner); + if (!ValidOwner(owner) || producers[i].event_capacity == 0 || + producers[i].event_capacity > + static_cast(std::numeric_limits::max())) return false; + if (i != 0 && producers[i - 1].owner == producers[i].owner && + producers[i - 1].producer_index == producers[i].producer_index) return false; + } + return ExpectedPlanBytes(producers, planned_bytes) && planned_bytes <= budget_bytes && + planned_bytes < kMaximumRunBytes; +} + +template +bool IsDefaultUnpublishedEvent(const Event& event) noexcept { + if (U8(event.stage) != 1 || U8(event.outcome) != 0 || + event.timestamp_ns != 0 || event.cost_units != 0) return false; + for (const auto byte : event.attempt_id) if (byte != 0) return false; + return true; +} + +} // namespace detail + +// Snapshot must be the immutable EventSnapshotV1 value type from the recorder +// contract. The caller supplies an independent run plan. +inline Report ValidateHistorySnapshot(const EventSnapshotV1& snapshot, + const RunPlan& expected_plan) noexcept { + auto invalid = [](Reason reason) { return Report{Verdict::Invalid, reason}; }; + auto incomplete = [](Reason reason) { return Report{Verdict::Incomplete, reason}; }; + + try { + // The caller's RunPlan is not assumed to have been reordered in place by + // EventRecorder::Create. Sort a bounded copy, then compare against the + // canonical snapshot roster. This avoids quadratic roster matching. + if (expected_plan.budget_bytes < 97 || expected_plan.budget_bytes > kMaximumRunBytes || + expected_plan.producers.size() > (expected_plan.budget_bytes - 97) / 90) + return invalid(Reason::InvalidExpectedPlan); + std::vector sorted_plan = expected_plan.producers; + std::sort(sorted_plan.begin(), sorted_plan.end(), [](const auto& left, const auto& right) { + return left.owner < right.owner || + (left.owner == right.owner && left.producer_index < right.producer_index); + }); + std::uint64_t expected_planned = 0; + if (!detail::ValidExpectedPlan(std::span(sorted_plan), + expected_plan.budget_bytes, expected_planned)) + return invalid(Reason::InvalidExpectedPlan); + if (snapshot.schema_version != 1) return invalid(Reason::SchemaMismatch); + if (snapshot.epoch_id != expected_plan.epoch_id || + snapshot.policy_digest != expected_plan.policy_digest || + snapshot.budget_bytes != expected_plan.budget_bytes || + snapshot.planned_bytes != expected_planned) + return invalid(Reason::ExpectedPlanMismatch); + if (snapshot.budget_bytes == 0 || snapshot.budget_bytes > kMaximumRunBytes || + snapshot.planned_bytes > snapshot.budget_bytes) + return invalid(Reason::InvalidByteAccounting); + if (snapshot.producers.size() < sorted_plan.size()) + return incomplete(Reason::ProducerMissing); + if (snapshot.producers.size() > sorted_plan.size()) + return invalid(Reason::ProducerUnexpected); + + Report report{Verdict::Complete, Reason::None}; + for (std::size_t index = 0; index < sorted_plan.size(); ++index) { + const auto& expected = sorted_plan[index]; + const auto& producer = snapshot.producers[index]; + if (producer.owner != expected.owner || producer.producer_index != expected.producer_index) + return invalid(Reason::ProducerOrderOrCapacityMismatch); + if (producer.capacity != expected.event_capacity) + return invalid(Reason::ProducerOrderOrCapacityMismatch); + if (!detail::ValidOwner(detail::U8(producer.owner)) || + producer.capacity == 0 || producer.slots.size() != producer.capacity || + producer.reserved_count > producer.capacity || + producer.published_count > producer.reserved_count) + return invalid(Reason::InvalidByteAccounting); + + std::uint64_t published = 0; + for (std::size_t i = 0; i < producer.slots.size(); ++i) { + const auto& slot = producer.slots[i]; + const auto status = detail::U8(slot.status); + if (!detail::ValidSlotStatus(status)) return invalid(Reason::InvalidSlotState); + if (i < producer.reserved_count) { + if (slot.producer_sequence != static_cast(i) + 1) + return incomplete(Reason::ReservationGap); + if (status != 2) { + const auto why = status == 1 ? Reason::ReservedSlotUnpublished + : Reason::ReservationGap; + return incomplete(why); + } + const auto stage = detail::U8(slot.event.stage); + const auto outcome = detail::U8(slot.event.outcome); + if (!detail::ValidStage(stage) || !detail::ValidOutcome(outcome)) + return invalid(Reason::InvalidEventEnum); + if (detail::OwnerForStage(stage) != detail::U8(producer.owner)) + return invalid(Reason::StageOwnerMismatch); + const auto event_checksum = detail::EventChecksum(slot.event); + if (slot.checksum64 != event_checksum) + return incomplete(Reason::EventChecksumMismatch); + ++published; + } else { + if (status != 0 || slot.producer_sequence != 0 || slot.checksum64 != 0 || + !detail::IsDefaultUnpublishedEvent(slot.event)) + return invalid(Reason::InvalidSlotState); + } + } + if (published != producer.published_count) + return incomplete(Reason::PublishedCountMismatch); + if (!producer.sealed) return incomplete(Reason::ProducerNotSealed); + if (producer.incomplete) return incomplete(Reason::ProducerMarkedIncomplete); + if (producer.seal_checksum64 != detail::ProducerChecksum(producer)) + return incomplete(Reason::ProducerChecksumMismatch); + if (!detail::AddChecked(report.published_events, published)) + return invalid(Reason::InvalidByteAccounting); + } + + if (snapshot.checksum64 != detail::SnapshotChecksum(snapshot)) + return incomplete(Reason::SnapshotChecksumMismatch); + if (!snapshot.complete) return incomplete(Reason::SnapshotIncomplete); + report.snapshot_bytes = snapshot.planned_bytes; + return report; + } catch (...) { + return Report{Verdict::Incomplete, Reason::ValidatorResourceFailure}; + } +} + +} // namespace rateguard::events::validation diff --git a/src/platform/clock.h b/src/platform/clock.h new file mode 100644 index 0000000..295f353 --- /dev/null +++ b/src/platform/clock.h @@ -0,0 +1,61 @@ +#pragma once + +#include "rateguard/v1/error_contract.h" + +#include +#include +#include + +namespace rateguard::platform { + +struct MonoNanos { + std::uint64_t value; + friend constexpr bool operator==(MonoNanos, MonoNanos) = default; +}; + +struct ClockIdentity { + std::array boot_uuid; + std::uint64_t namespace_device; + std::uint64_t namespace_inode; + std::int64_t monotonic_offset_seconds; + std::uint32_t monotonic_offset_nanoseconds; + std::int64_t boottime_offset_seconds; + std::uint32_t boottime_offset_nanoseconds; + std::int32_t clock_id; + friend constexpr bool operator==(const ClockIdentity&, const ClockIdentity&) = default; +}; + +enum class ClockFailureReason : std::uint8_t { + PlatformRead, + MalformedBootUuid, + MalformedOffsets, + OffsetOutOfRange, + InputTooLong, + NotProcessLeader, + NamespaceStat, + NamespaceChanged, + ExpectedIdentityMismatch, + ClockSyscall, + InvalidTimespec, + NanosecondOverflow, + BackwardsSample, + LatchedFailure, +}; + +struct ClockFailure { + rateguard::v1::contract::ServiceError service_error; + ClockFailureReason reason; +}; + +template +using ClockResult = std::variant; + +class IClock { + public: + virtual ~IClock() = default; + [[nodiscard]] virtual ClockResult Now() = 0; + [[nodiscard]] virtual ClockResult Provenance() = 0; + [[nodiscard]] virtual bool Healthy() const = 0; +}; + +} // namespace rateguard::platform diff --git a/src/platform/clock_linux.cpp b/src/platform/clock_linux.cpp new file mode 100644 index 0000000..b75ad55 --- /dev/null +++ b/src/platform/clock_linux.cpp @@ -0,0 +1,410 @@ +#include "platform/clock_linux.h" + +#include "platform/clock_linux_detail.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__linux__) +#include +#include +#include +#endif +#include +#if defined(__linux__) +#include +#endif +#include +#include +#include + +namespace rateguard::platform { +namespace { +using rateguard::v1::contract::Commitment; +using rateguard::v1::contract::ErrorCategory; +using rateguard::v1::contract::ErrorCode; +using rateguard::v1::contract::RetryDisposition; + +ClockFailure Failure(ClockFailureReason reason) { + return {{ErrorCategory::Internal, ErrorCode::Internal, RetryDisposition::Never, + Commitment::NotCommitted}, + reason}; +} + +bool ParseSigned(std::string_view text, std::int64_t& output) { + if (text.empty() || text.front() == '+') return false; + const auto digits = text.front() == '-' ? text.substr(1) : text; + if (digits.empty() || (digits.size() > 1 && digits.front() == '0') || + (text.front() == '-' && digits == "0")) + return false; + for (char c : digits) + if (c < '0' || c > '9') return false; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), output, 10); + return parsed.ec == std::errc{} && parsed.ptr == text.data() + text.size(); +} + +bool ParseUnsigned(std::string_view text, std::uint32_t& output) { + if (text.empty() || (text.size() > 1 && text.front() == '0')) return false; + for (char c : text) + if (c < '0' || c > '9') return false; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), output, 10); + return parsed.ec == std::errc{} && parsed.ptr == text.data() + text.size(); +} + +bool IsSpace(char c) { + return c == ' ' || c == '\t'; +} + +ClockResult> ThreeFields(std::string_view line) { + std::array fields{}; + std::size_t count = 0; + std::size_t position = 0; + while (position < line.size()) { + while (position < line.size() && IsSpace(line[position])) ++position; + if (position == line.size()) break; + const std::size_t begin = position; + while (position < line.size() && !IsSpace(line[position])) ++position; + if (count == fields.size()) return Failure(ClockFailureReason::MalformedOffsets); + fields[count++] = line.substr(begin, position - begin); + } + if (count != fields.size()) return Failure(ClockFailureReason::MalformedOffsets); + return fields; +} + +#if defined(__linux__) +class ScopedFd final { + public: + explicit ScopedFd(int fd) : fd_(fd) {} + ~ScopedFd() { if (fd_ >= 0) ::close(fd_); } + ScopedFd(const ScopedFd&) = delete; + ScopedFd& operator=(const ScopedFd&) = delete; + [[nodiscard]] int get() const noexcept { return fd_; } + + private: + int fd_; +}; + +ClockResult ReadProcFile(const char* path, std::size_t maximum_bytes) { + if (maximum_bytes > 512) + return Failure(ClockFailureReason::InputTooLong); + const int fd = ::open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return Failure(ClockFailureReason::PlatformRead); + ScopedFd owned(fd); + struct statfs fs {}; + if (::fstatfs(fd, &fs) != 0 || + static_cast(fs.f_type) != + static_cast(PROC_SUPER_MAGIC)) + return Failure(ClockFailureReason::PlatformRead); + return detail::ReadBoundedFd(fd, maximum_bytes); +} + +class LinuxClockPlatform final : public IClockPlatform { + public: + ClockResult IsProcessLeader() override { + const auto tid = static_cast(::syscall(SYS_gettid)); + if (tid < 0) return Failure(ClockFailureReason::PlatformRead); + return tid == ::getpid(); + } + + ClockResult ReadBootUuidFile() override { + return ReadProcFile("/proc/sys/kernel/random/boot_id", 64); + } + + ClockResult StatTimeNamespace( + bool children) override { + return StatNamespace(children ? "/proc/self/ns/time_for_children" + : "/proc/self/ns/time"); + } + + ClockResult ReadTimeOffsetsFile() override { + return ReadProcFile("/proc/self/timens_offsets", 512); + } + + ClockResult MonotonicClockId() override { + return static_cast(CLOCK_MONOTONIC); + } + + ClockResult ReadMonotonic() override { + timespec value{}; + if (::clock_gettime(CLOCK_MONOTONIC, &value) != 0) + return Failure(ClockFailureReason::ClockSyscall); + return ClockReading{static_cast(value.tv_sec), + static_cast(value.tv_nsec)}; + } + + private: + static ClockResult StatNamespace( + const char* path) { + const int fd = ::open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return Failure(ClockFailureReason::NamespaceStat); + ScopedFd owned(fd); + struct stat status {}; + struct statfs fs {}; + if (::fstat(fd, &status) != 0 || ::fstatfs(fd, &fs) != 0 || + static_cast(fs.f_type) != + static_cast(NSFS_MAGIC) || status.st_ino == 0) + return Failure(ClockFailureReason::NamespaceStat); + return detail::NamespaceFileIdentity{ + static_cast(status.st_dev), + static_cast(status.st_ino)}; + } +}; +#else +class LinuxClockPlatform final : public IClockPlatform { + public: + ClockResult IsProcessLeader() override { + return Failure(ClockFailureReason::PlatformRead); + } + ClockResult ReadBootUuidFile() override { + return Failure(ClockFailureReason::PlatformRead); + } + ClockResult StatTimeNamespace(bool) override { + return Failure(ClockFailureReason::PlatformRead); + } + ClockResult ReadTimeOffsetsFile() override { + return Failure(ClockFailureReason::PlatformRead); + } + ClockResult MonotonicClockId() override { + return Failure(ClockFailureReason::PlatformRead); + } + ClockResult ReadMonotonic() override { + return Failure(ClockFailureReason::PlatformRead); + } +}; +#endif + +} // namespace + +namespace { +ClockResult ProbeIdentity(IClockPlatform& platform) { + auto leader = platform.IsProcessLeader(); + if (auto* error = std::get_if(&leader)) return *error; + if (!std::get(leader)) + return Failure(ClockFailureReason::NotProcessLeader); + + auto boot_file = platform.ReadBootUuidFile(); + if (auto* error = std::get_if(&boot_file)) return *error; + auto boot = detail::ParseBootUuid(std::get(boot_file)); + if (auto* error = std::get_if(&boot)) return *error; + + auto current_before = platform.StatTimeNamespace(false); + if (auto* error = std::get_if(¤t_before)) return *error; + auto children_before = platform.StatTimeNamespace(true); + if (auto* error = std::get_if(&children_before)) return *error; + const auto current_pre = std::get(current_before); + const auto children_pre = std::get(children_before); + + auto offsets_file = platform.ReadTimeOffsetsFile(); + if (auto* error = std::get_if(&offsets_file)) return *error; + auto offsets = detail::ParseTimeOffsets(std::get(offsets_file)); + if (auto* error = std::get_if(&offsets)) return *error; + + auto current_after = platform.StatTimeNamespace(false); + if (auto* error = std::get_if(¤t_after)) return *error; + auto children_after = platform.StatTimeNamespace(true); + if (auto* error = std::get_if(&children_after)) return *error; + const auto current_post = std::get(current_after); + const auto children_post = std::get(children_after); + if (current_pre.inode == 0 || current_pre != children_pre || + current_pre != current_post || current_pre != children_post) + return Failure(ClockFailureReason::NamespaceChanged); + + auto clock_id = platform.MonotonicClockId(); + if (auto* error = std::get_if(&clock_id)) return *error; + + const auto parsed_offsets = std::get(offsets); + return ClockIdentity{std::get>(boot), + current_pre.device, + current_pre.inode, + parsed_offsets.monotonic_seconds, + parsed_offsets.monotonic_nanoseconds, + parsed_offsets.boottime_seconds, + parsed_offsets.boottime_nanoseconds, + std::get(clock_id)}; +} +} // namespace + +namespace detail { +ClockResult ReadBoundedFd(int fd, std::size_t maximum_bytes) { + if (fd < 0) return Failure(ClockFailureReason::PlatformRead); + if (maximum_bytes > 512) + return Failure(ClockFailureReason::InputTooLong); + std::string bytes(maximum_bytes + 1, '\0'); + std::size_t total = 0; + while (total < bytes.size()) { + const ssize_t count = ::read(fd, bytes.data() + total, bytes.size() - total); + if (count < 0 && errno == EINTR) continue; + if (count < 0) return Failure(ClockFailureReason::PlatformRead); + if (count == 0) break; + total += static_cast(count); + } + if (total > maximum_bytes) return Failure(ClockFailureReason::InputTooLong); + bytes.resize(total); + return bytes; +} + +ClockResult> ParseBootUuid( + std::string_view input) { + if (input.size() > 64) return Failure(ClockFailureReason::InputTooLong); + if (!input.empty() && input.back() == '\n') input.remove_suffix(1); + if (input.size() != 36) return Failure(ClockFailureReason::MalformedBootUuid); + std::array result{}; + std::size_t output = 0; + int high_nibble = -1; + for (std::size_t i = 0; i < input.size(); ++i) { + const char c = input[i]; + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (c != '-') return Failure(ClockFailureReason::MalformedBootUuid); + continue; + } + int digit = -1; + if (c >= '0' && c <= '9') digit = c - '0'; + else if (c >= 'a' && c <= 'f') digit = c - 'a' + 10; + if (digit < 0) return Failure(ClockFailureReason::MalformedBootUuid); + if (high_nibble < 0) { + high_nibble = digit; + } else { + if (output >= result.size()) + return Failure(ClockFailureReason::MalformedBootUuid); + result[output++] = static_cast((high_nibble << 4) | digit); + high_nibble = -1; + } + } + if (output != result.size() || high_nibble >= 0) + return Failure(ClockFailureReason::MalformedBootUuid); + return result; +} + +ClockResult ParseTimeOffsets(std::string_view input) { + if (input.size() > 512) return Failure(ClockFailureReason::InputTooLong); + std::optional monotonic; + std::optional boottime; + std::size_t position = 0; + while (position < input.size()) { + const std::size_t end = input.find('\n', position); + const bool has_newline = end != std::string_view::npos; + auto line = input.substr(position, has_newline ? end - position : input.size() - position); + position = has_newline ? end + 1 : input.size(); + if (line.empty()) return Failure(ClockFailureReason::MalformedOffsets); + auto fields_result = ThreeFields(line); + if (auto* error = std::get_if(&fields_result)) return *error; + const auto fields = std::get>(fields_result); + std::int64_t seconds = 0; + std::uint32_t nanoseconds = 0; + if (!ParseSigned(fields[1], seconds) || + !ParseUnsigned(fields[2], nanoseconds)) + return Failure(ClockFailureReason::MalformedOffsets); + if (nanoseconds > 999'999'999U) + return Failure(ClockFailureReason::OffsetOutOfRange); + if (fields[0] == "monotonic") { + if (monotonic) return Failure(ClockFailureReason::MalformedOffsets); + monotonic = TimeOffsets{seconds, nanoseconds, 0, 0}; + } else if (fields[0] == "boottime") { + if (boottime) return Failure(ClockFailureReason::MalformedOffsets); + boottime = TimeOffsets{0, 0, seconds, nanoseconds}; + } else { + return Failure(ClockFailureReason::MalformedOffsets); + } + } + if (!monotonic || !boottime) + return Failure(ClockFailureReason::MalformedOffsets); + return TimeOffsets{monotonic->monotonic_seconds, + monotonic->monotonic_nanoseconds, + boottime->boottime_seconds, + boottime->boottime_nanoseconds}; +} +} // namespace detail + +ClockResult detail::ProbeCurrentLinuxClockIdentity() { + LinuxClockPlatform platform; + return ProbeIdentity(platform); +} + +LinuxMonotonicClock::LinuxMonotonicClock( + ClockIdentity identity, std::unique_ptr platform) + : identity_(identity), platform_(std::move(platform)), + failure_({{ErrorCategory::Internal, ErrorCode::Internal, + RetryDisposition::Never, Commitment::NotCommitted}, + ClockFailureReason::LatchedFailure}) {} + +ClockResult> LinuxMonotonicClock::Create( + const ClockIdentity& trusted_expected_identity, + std::unique_ptr platform) { + if (!platform) return Failure(ClockFailureReason::PlatformRead); + auto observed = ProbeIdentity(*platform); + if (auto* error = std::get_if(&observed)) return *error; + const ClockIdentity actual = std::get(observed); + if (actual.namespace_inode == 0 || actual.clock_id != 1 || + actual.monotonic_offset_nanoseconds > 999'999'999U || + actual.boottime_offset_nanoseconds > 999'999'999U || + actual != trusted_expected_identity) + return Failure(ClockFailureReason::ExpectedIdentityMismatch); + auto clock = std::unique_ptr( + new LinuxMonotonicClock(actual, std::move(platform))); + auto initial_sample = clock->Now(); + if (auto* error = std::get_if(&initial_sample)) return *error; + return clock; +} + +ClockFailure LinuxMonotonicClock::Latch(ClockFailureReason reason) { + if (!failed_) { + failed_ = true; + healthy_ = false; + failure_ = Failure(reason); + } + return failure_; +} + +ClockFailure LinuxMonotonicClock::CurrentFailure() const { return failure_; } + +ClockResult LinuxMonotonicClock::Now() { + std::lock_guard lock(mutex_); + if (failed_) return CurrentFailure(); + auto reading_result = platform_->ReadMonotonic(); + if (auto* error = std::get_if(&reading_result)) + return Latch(error->reason); + const auto reading = std::get(reading_result); + if (reading.seconds < 0 || reading.nanoseconds < 0 || + reading.nanoseconds > 999'999'999) + return Latch(ClockFailureReason::InvalidTimespec); + constexpr std::uint64_t kNanosPerSecond = 1'000'000'000ULL; + const auto seconds = static_cast(reading.seconds); + if (seconds > std::numeric_limits::max() / kNanosPerSecond) + return Latch(ClockFailureReason::NanosecondOverflow); + const std::uint64_t whole = seconds * kNanosPerSecond; + const auto fraction = static_cast(reading.nanoseconds); + if (fraction > std::numeric_limits::max() - whole) + return Latch(ClockFailureReason::NanosecondOverflow); + const MonoNanos sample{whole + fraction}; + if (last_sample_ && sample.value < last_sample_->value) + return Latch(ClockFailureReason::BackwardsSample); + last_sample_ = sample; + healthy_ = true; + return sample; +} + +ClockResult LinuxMonotonicClock::Provenance() { + std::lock_guard lock(mutex_); + if (failed_) return CurrentFailure(); + if (!healthy_) return Failure(ClockFailureReason::LatchedFailure); + return identity_; +} + +bool LinuxMonotonicClock::Healthy() const { + std::lock_guard lock(mutex_); + return healthy_ && !failed_; +} + +ClockResult> CreateLinuxClock( + const ClockIdentity& trusted_expected_identity) { + return LinuxMonotonicClock::Create( + trusted_expected_identity, std::make_unique()); +} + +} // namespace rateguard::platform diff --git a/src/platform/clock_linux.h b/src/platform/clock_linux.h new file mode 100644 index 0000000..01579e9 --- /dev/null +++ b/src/platform/clock_linux.h @@ -0,0 +1,63 @@ +#pragma once + +#include "platform/clock.h" +#include "platform/clock_linux_detail.h" + +#include +#include +#include +#include +#include + +namespace rateguard::platform { + +struct ClockReading { + std::int64_t seconds; + std::int64_t nanoseconds; +}; + +// Internal platform seam. Production uses Linux syscalls/procfs; deterministic +// tests inject a fake. It is not an application service interface. +class IClockPlatform { + public: + virtual ~IClockPlatform() = default; + [[nodiscard]] virtual ClockResult IsProcessLeader() = 0; + [[nodiscard]] virtual ClockResult ReadBootUuidFile() = 0; + [[nodiscard]] virtual ClockResult + StatTimeNamespace(bool children) = 0; + [[nodiscard]] virtual ClockResult ReadTimeOffsetsFile() = 0; + [[nodiscard]] virtual ClockResult MonotonicClockId() = 0; + [[nodiscard]] virtual ClockResult ReadMonotonic() = 0; +}; + +class LinuxMonotonicClock final : public IClock { + public: + [[nodiscard]] static ClockResult> Create( + const ClockIdentity& trusted_expected_identity, + std::unique_ptr platform); + + [[nodiscard]] ClockResult Now() override; + [[nodiscard]] ClockResult Provenance() override; + [[nodiscard]] bool Healthy() const override; + + private: + LinuxMonotonicClock(ClockIdentity identity, + std::unique_ptr platform); + [[nodiscard]] ClockFailure Latch(ClockFailureReason reason); + [[nodiscard]] ClockFailure CurrentFailure() const; + + const ClockIdentity identity_; + std::unique_ptr platform_; + mutable std::mutex mutex_; + bool healthy_{false}; + bool failed_{false}; + std::optional last_sample_; + ClockFailure failure_; +}; + +// Production factory helper is intentionally internal and always requires a +// trusted manifest identity; no API self-authorizes from a host probe. +[[nodiscard]] ClockResult> CreateLinuxClock( + const ClockIdentity& trusted_expected_identity); + +} // namespace rateguard::platform diff --git a/src/platform/clock_linux_detail.h b/src/platform/clock_linux_detail.h new file mode 100644 index 0000000..f708a69 --- /dev/null +++ b/src/platform/clock_linux_detail.h @@ -0,0 +1,34 @@ +#pragma once + +#include "platform/clock.h" + +#include + +namespace rateguard::platform::detail { + +struct NamespaceFileIdentity { + std::uint64_t device; + std::uint64_t inode; + friend constexpr bool operator==(NamespaceFileIdentity, + NamespaceFileIdentity) = default; +}; + +struct TimeOffsets { + std::int64_t monotonic_seconds; + std::uint32_t monotonic_nanoseconds; + std::int64_t boottime_seconds; + std::uint32_t boottime_nanoseconds; +}; + +[[nodiscard]] ClockResult> ParseBootUuid( + std::string_view input); +[[nodiscard]] ClockResult ParseTimeOffsets(std::string_view input); +// Bounded POSIX read primitive shared by production and tests. The caller owns +// the already-open descriptor and remains responsible for validating its type. +[[nodiscard]] ClockResult ReadBoundedFd(int fd, + std::size_t maximum_bytes); +// Internal smoke-test probe only. Production callers must use CreateLinuxClock +// with a trusted epoch-manifest identity. +[[nodiscard]] ClockResult ProbeCurrentLinuxClockIdentity(); + +} // namespace rateguard::platform::detail diff --git a/src/platform/file_io.h b/src/platform/file_io.h new file mode 100644 index 0000000..66194e3 --- /dev/null +++ b/src/platform/file_io.h @@ -0,0 +1,71 @@ +#pragma once + +// Shared POSIX descriptor ownership and I/O used by supervisor artifact stores. +// Callers validate regular-file identity and bound size before ReadAll. + +#include +#include +#include +#include + +namespace rateguard::platform::file { + +class UniqueFd { + public: + explicit UniqueFd(int fd = -1) noexcept : fd_(fd) {} + UniqueFd(const UniqueFd&) = delete; + UniqueFd& operator=(const UniqueFd&) = delete; + UniqueFd(UniqueFd&& other) noexcept : fd_(other.release()) {} + UniqueFd& operator=(UniqueFd&& other) noexcept { + if (this != &other) { + if (fd_ >= 0) ::close(fd_); + fd_ = other.release(); + } + return *this; + } + ~UniqueFd() { if (fd_ >= 0) ::close(fd_); } + [[nodiscard]] int get() const noexcept { return fd_; } + [[nodiscard]] int release() noexcept { const int value = fd_; fd_ = -1; return value; } + private: + int fd_; +}; + +inline bool WriteAll(int fd, const char* data, std::size_t size) noexcept { + std::size_t offset = 0; + while (offset < size) { + const ssize_t n = ::write(fd, data + offset, size - offset); + if (n < 0) { + if (errno == EINTR) continue; + return false; + } + if (n == 0) return false; + offset += static_cast(n); + } + return true; +} + +inline bool Sync(int fd) noexcept { + int result; + do { result = ::fsync(fd); } while (result != 0 && errno == EINTR); + return result == 0; +} + +inline bool ReadAll(int fd, std::string& out, std::size_t size) { + out.resize(size); + std::size_t offset = 0; + while (offset < size) { + const ssize_t n = ::read(fd, out.data() + offset, size - offset); + if (n < 0) { + if (errno == EINTR) continue; + return false; + } + if (n == 0) return false; + offset += static_cast(n); + } + char extra = 0; + ssize_t trailing; + do { trailing = ::read(fd, &extra, 1); } while (trailing < 0 && errno == EINTR); + return trailing == 0; +} + +} // namespace rateguard::platform::file diff --git a/src/policy/canonical_codec.cpp b/src/policy/canonical_codec.cpp new file mode 100644 index 0000000..03b3026 --- /dev/null +++ b/src/policy/canonical_codec.cpp @@ -0,0 +1,158 @@ +#include "canonical_codec.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::policy { +namespace { + +constexpr std::size_t kMaxCanonicalBytes = 64U * 1024U * 1024U; + +class Writer { + public: + bool U8(std::uint8_t value) { return Append(&value, 1); } + bool U32(std::uint32_t value) { + const std::uint8_t bytes[] = { + static_cast(value >> 24), + static_cast(value >> 16), + static_cast(value >> 8), + static_cast(value)}; + return Append(bytes, sizeof(bytes)); + } + bool U64(std::uint64_t value) { + std::uint8_t bytes[8]; + for (int i = 7; i >= 0; --i) { + bytes[i] = static_cast(value); + value >>= 8; + } + return Append(bytes, sizeof(bytes)); + } + bool Raw(const std::uint8_t* data, std::size_t size) { return Append(data, size); } + bool String(std::string_view value) { + if (value.size() > std::numeric_limits::max()) return false; + return U32(static_cast(value.size())) && + Append(reinterpret_cast(value.data()), value.size()); + } + std::vector Take() && { return std::move(bytes_); } + + private: + bool Append(const std::uint8_t* data, std::size_t size) { + if (size > kMaxCanonicalBytes - bytes_.size()) return false; + bytes_.insert(bytes_.end(), data, data + size); + return true; + } + + std::vector bytes_; +}; + +PolicyError EncodingError(std::string message) { + return {PolicyErrorCode::EncodingFailure, std::move(message)}; +} + +std::uint32_t TenantIndex(const PolicySnapshot& snapshot, std::string_view id) { + const auto& tenants = snapshot.tenants(); + const auto found = std::lower_bound(tenants.begin(), tenants.end(), id, + [](const TenantPolicy& item, std::string_view value) { return std::string_view(item.tenant_id) < value; }); + if (found == tenants.end() || std::string_view(found->tenant_id) != id) + return std::numeric_limits::max(); + return static_cast(std::distance(tenants.begin(), found)); +} + +std::uint32_t OperationIndex(const TenantPolicy& tenant, std::string_view id) { + const auto found = std::lower_bound(tenant.operations.begin(), tenant.operations.end(), id, + [](const OperationPolicy& item, std::string_view value) { return std::string_view(item.operation_id) < value; }); + if (found == tenant.operations.end() || std::string_view(found->operation_id) != id) + return std::numeric_limits::max(); + return static_cast(std::distance(tenant.operations.begin(), found)); +} + +} // namespace + +Result> CanonicalPolicyCodec::Encode( + const PolicySnapshot& snapshot) try { + Writer out; + const std::uint32_t mode = snapshot.mode() == Mode::Strict ? 1U : 2U; + if (!out.U32(1) || !out.U32(mode) || + !out.Raw(snapshot.epoch_id().data(), snapshot.epoch_id().size()) || + !out.Raw(snapshot.authority_incarnation().data(), snapshot.authority_incarnation().size()) || + !out.Raw(snapshot.trust_root_sha256().data(), snapshot.trust_root_sha256().size()) || + !out.U32(static_cast(snapshot.replica_slots().size()))) + return EncodingError("canonical policy exceeds output limit or count width"); + + for (const auto& slot : snapshot.replica_slots()) { + if (!out.U32(slot.slot_id) || !out.Raw(slot.incarnation_id.data(), slot.incarnation_id.size())) + return EncodingError("canonical policy exceeds output limit while encoding slots"); + } + if (!out.U32(static_cast(snapshot.tenants().size()))) + return EncodingError("canonical policy exceeds output limit while encoding tenants"); + for (const auto& tenant : snapshot.tenants()) { + if (!out.String(tenant.tenant_id) || !out.U64(tenant.capacity_units) || + !out.U64(tenant.rate_units_per_second)) + return EncodingError("canonical policy exceeds output limit while encoding tenant"); + if (tenant.credit_batch_units) { + if (!out.U8(1) || !out.U64(*tenant.credit_batch_units)) + return EncodingError("canonical policy exceeds output limit while encoding credit batch"); + } else if (!out.U8(0)) { + return EncodingError("canonical policy exceeds output limit while encoding strict mode"); + } + if (!out.U32(static_cast(tenant.operations.size()))) + return EncodingError("canonical policy exceeds output limit while encoding operation count"); + for (const auto& operation : tenant.operations) { + if (!out.String(operation.operation_id) || !out.U64(operation.cost_units)) + return EncodingError("canonical policy exceeds output limit while encoding operation"); + } + } + if (!out.U32(static_cast(snapshot.principals().size()))) + return EncodingError("canonical policy exceeds output limit while encoding principal count"); + for (const auto& principal : snapshot.principals()) { + if (!out.String(principal.uri) || !out.U32(static_cast(principal.role))) + return EncodingError("canonical policy exceeds output limit while encoding principal"); + if (principal.role == PrincipalRole::Replica && + (!principal.slot_id || !out.U32(*principal.slot_id))) + return EncodingError("replica principal has no validated slot"); + if (!out.U32(static_cast(principal.permissions.size()))) + return EncodingError("canonical policy exceeds output limit while encoding permissions"); + for (const auto& permission : principal.permissions) { + const auto tenant_index = TenantIndex(snapshot, permission.tenant_id); + if (tenant_index >= snapshot.tenants().size()) + return EncodingError("validated permission lost its tenant reference"); + const auto& tenant = snapshot.tenants()[tenant_index]; + const auto operation_index = OperationIndex(tenant, permission.operation_id); + if (operation_index >= tenant.operations.size()) + return EncodingError("validated permission lost its operation reference"); + if (!out.U32(tenant_index) || !out.U32(operation_index)) + return EncodingError("canonical policy exceeds output limit while encoding permission"); + } + } + return std::move(out).Take(); +} catch (const std::bad_alloc&) { + return PolicyError{PolicyErrorCode::ResourceLimit, "insufficient memory for bounded canonical encoding"}; +} catch (const std::exception&) { + return EncodingError("canonical encoding failed"); +} + +Result CanonicalPolicyCodec::Digest(const PolicySnapshot& snapshot) { + auto encoded = Encode(snapshot); + if (const auto* error = std::get_if(&encoded)) return *error; + const auto& bytes = std::get>(encoded); + Digest32 digest{}; + unsigned int length = 0; + std::unique_ptr algorithm( + EVP_MD_fetch(nullptr, "SHA256", nullptr), EVP_MD_free); + std::unique_ptr context( + EVP_MD_CTX_new(), EVP_MD_CTX_free); + if (!algorithm || !context || EVP_DigestInit_ex(context.get(), algorithm.get(), nullptr) != 1 || + EVP_DigestUpdate(context.get(), bytes.data(), bytes.size()) != 1 || + EVP_DigestFinal_ex(context.get(), digest.data(), &length) != 1 || length != digest.size()) + return PolicyError{PolicyErrorCode::CryptoFailure, "SHA-256 computation failed"}; + return digest; +} + +} // namespace rateguard::policy diff --git a/src/policy/canonical_codec.h b/src/policy/canonical_codec.h new file mode 100644 index 0000000..264f67a --- /dev/null +++ b/src/policy/canonical_codec.h @@ -0,0 +1,19 @@ +#pragma once + +#include "policy_snapshot.h" + +#include +#include +#include + +namespace rateguard::policy { + +class CanonicalPolicyCodec final { + public: + [[nodiscard]] static Result> Encode( + const PolicySnapshot& snapshot); + [[nodiscard]] static Result Digest( + const PolicySnapshot& snapshot); +}; + +} // namespace rateguard::policy diff --git a/src/policy/policy_loader.cpp b/src/policy/policy_loader.cpp new file mode 100644 index 0000000..6226cf0 --- /dev/null +++ b/src/policy/policy_loader.cpp @@ -0,0 +1,468 @@ +#include "policy_loader.h" + +#include "canonical_codec.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::policy { +namespace { + +using Json = nlohmann::json; +constexpr std::uint64_t kMaxPolicyValue = 1'000'000'000ULL; +constexpr std::size_t kMaxDiagnosticBytes = 256; + +struct Failure final { + PolicyError error; +}; + +[[noreturn]] void Fail(PolicyErrorCode code, std::string message) { + if (message.size() > kMaxDiagnosticBytes) message.resize(kMaxDiagnosticBytes); + throw Failure{{code, std::move(message)}}; +} + +class InputGuard final : public nlohmann::json_sax { + public: + using string_t = Json::string_t; + using binary_t = Json::binary_t; + using number_integer_t = Json::number_integer_t; + using number_unsigned_t = Json::number_unsigned_t; + using number_float_t = Json::number_float_t; + + bool null() override { return true; } + bool boolean(bool) override { return true; } + bool number_integer(number_integer_t) override { return true; } + bool number_unsigned(number_unsigned_t) override { return true; } + // Float tokens are rejected by this lexical guard and reported as + // InvalidJson. Boolean values remain syntactically valid JSON and are + // rejected later as InvalidValue when an integer field requires a string. + bool number_float(number_float_t, const string_t&) override { + return Reject("JSON floating-point numbers are not permitted"); + } + bool string(string_t&) override { return true; } + bool binary(binary_t&) override { return Reject("binary value is not valid policy JSON"); } + bool start_object(std::size_t) override { + if (frames_.size() >= PolicyLoader::kMaxJsonDepth) return Reject("JSON nesting exceeds depth 32"); + frames_.push_back(Frame{true, {}}); + return true; + } + bool key(string_t& value) override { + if (frames_.empty() || !frames_.back().object) return Reject("object key outside object"); + if (!frames_.back().keys.insert(value).second) return Reject("duplicate JSON object key"); + return true; + } + bool end_object() override { + if (frames_.empty() || !frames_.back().object) return Reject("mismatched object terminator"); + frames_.pop_back(); + return true; + } + bool start_array(std::size_t) override { + if (frames_.size() >= PolicyLoader::kMaxJsonDepth) return Reject("JSON nesting exceeds depth 32"); + frames_.push_back(Frame{false, {}}); + return true; + } + bool end_array() override { + if (frames_.empty() || frames_.back().object) return Reject("mismatched array terminator"); + frames_.pop_back(); + return true; + } + bool parse_error(std::size_t, const std::string&, const nlohmann::detail::exception& error) override { + (void)error; + if (error_.empty()) error_ = "invalid JSON syntax"; + return false; + } + [[nodiscard]] const std::string& error() const noexcept { return error_; } + + private: + struct Frame { + bool object; + std::unordered_set keys; + }; + bool Reject(std::string message) { + if (error_.empty()) error_ = std::move(message); + return false; + } + std::vector frames_; + std::string error_; +}; + +void CheckKeys(const Json& value, std::string_view context, + std::initializer_list required, + std::initializer_list optional = {}) { + if (!value.is_object()) Fail(PolicyErrorCode::InvalidSchema, std::string(context) + " must be an object"); + for (const auto& item : value.items()) { + const std::string_view key = item.key(); + if (std::find(required.begin(), required.end(), key) == required.end() && + std::find(optional.begin(), optional.end(), key) == optional.end()) + Fail(PolicyErrorCode::InvalidSchema, std::string(context) + " has unknown field"); + } + for (std::string_view key : required) { + if (!value.contains(std::string(key))) + Fail(PolicyErrorCode::InvalidSchema, std::string(context) + " missing field " + std::string(key)); + } +} + +const Json& Required(const Json& object, const char* key, std::string_view context) { + const auto it = object.find(key); + if (it == object.end()) Fail(PolicyErrorCode::InvalidSchema, + std::string(context) + " missing field " + key); + return *it; +} + +std::string StringValue(const Json& value, std::string_view context) { + if (!value.is_string()) Fail(PolicyErrorCode::InvalidValue, std::string(context) + " must be a string"); + return value.get(); +} + +std::uint32_t JsonU32(const Json& value, std::string_view context) { + if (value.is_number_unsigned()) { + const auto number = value.get(); + if (number <= std::numeric_limits::max()) return static_cast(number); + } else if (value.is_number_integer() && !value.is_number_float()) { + const auto number = value.get(); + if (number >= 0 && static_cast(number) <= std::numeric_limits::max()) + return static_cast(number); + } + Fail(PolicyErrorCode::InvalidValue, std::string(context) + " must be a nonnegative JSON uint32 integer"); +} + +std::uint64_t DecimalU64(const Json& value, std::string_view context) { + if (!value.is_string()) Fail(PolicyErrorCode::InvalidValue, std::string(context) + " must be a decimal string"); + const std::string text = value.get(); + if (text.empty() || (text.size() > 1 && text.front() == '0')) + Fail(PolicyErrorCode::InvalidValue, std::string(context) + " is not canonical decimal uint64"); + for (unsigned char c : text) { + if (c < '0' || c > '9') + Fail(PolicyErrorCode::InvalidValue, std::string(context) + " is not canonical decimal uint64"); + } + std::uint64_t result = 0; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), result, 10); + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) + Fail(PolicyErrorCode::InvalidValue, std::string(context) + " is outside uint64 range"); + return result; +} + +bool ValidIdentifier(std::string_view value) { + if (value.empty() || value.size() > PolicyLoader::kMaxIdentifierBytes) return false; + for (unsigned char c : value) { + const bool alnum = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'); + if (!alnum && c != '_' && c != '.' && c != '-') return false; + } + return true; +} + +template +std::array LowerHex(const Json& value, std::string_view context) { + const std::string hex = StringValue(value, context); + if (hex.size() != N * 2) Fail(PolicyErrorCode::InvalidValue, std::string(context) + " has incorrect hex width"); + std::array bytes{}; + auto nibble = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return -1; + }; + for (std::size_t i = 0; i < N; ++i) { + const int high = nibble(hex[i * 2]); + const int low = nibble(hex[i * 2 + 1]); + if (high < 0 || low < 0) + Fail(PolicyErrorCode::InvalidValue, std::string(context) + " must be lowercase hexadecimal"); + bytes[i] = static_cast((high << 4) | low); + } + return bytes; +} + +std::string Hex(const Id16& value) { + constexpr char digits[] = "0123456789abcdef"; + std::string result; + result.resize(value.size() * 2); + for (std::size_t i = 0; i < value.size(); ++i) { + result[2 * i] = digits[value[i] >> 4]; + result[2 * i + 1] = digits[value[i] & 0x0f]; + } + return result; +} + +void ValidateIdentifier(const std::string& id, std::string_view context) { + if (!ValidIdentifier(id)) Fail(PolicyErrorCode::InvalidValue, + std::string(context) + " must match 1..128 ASCII [A-Za-z0-9_.-]"); +} + +void RequireArray(const Json& value, std::string_view context) { + if (!value.is_array()) Fail(PolicyErrorCode::InvalidSchema, std::string(context) + " must be an array"); +} + +bool PermissionLess(const Permission& a, const Permission& b) { + return a.tenant_id < b.tenant_id || + (a.tenant_id == b.tenant_id && a.operation_id < b.operation_id); +} + +const TenantPolicy* FindTenantIn(const std::vector& tenants, std::string_view id) { + const auto it = std::lower_bound(tenants.begin(), tenants.end(), id, + [](const TenantPolicy& tenant, std::string_view key) { return std::string_view(tenant.tenant_id) < key; }); + return it != tenants.end() && std::string_view(it->tenant_id) == id ? &*it : nullptr; +} + +const ReplicaSlot* FindSlotIn(const std::vector& slots, std::uint32_t id) { + const auto it = std::lower_bound(slots.begin(), slots.end(), id, + [](const ReplicaSlot& slot, std::uint32_t key) { return slot.slot_id < key; }); + return it != slots.end() && it->slot_id == id ? &*it : nullptr; +} + +} // namespace + +const OperationPolicy* TenantPolicy::FindOperation(std::string_view id) const noexcept { + const auto it = std::lower_bound(operations.begin(), operations.end(), id, + [](const OperationPolicy& operation, std::string_view key) { return std::string_view(operation.operation_id) < key; }); + return it != operations.end() && std::string_view(it->operation_id) == id ? &*it : nullptr; +} + +const TenantPolicy* PolicySnapshot::FindTenant(std::string_view id) const noexcept { + return FindTenantIn(tenants_, id); +} + +const Principal* PolicySnapshot::FindPrincipal(std::string_view uri) const noexcept { + const auto it = std::lower_bound(principals_.begin(), principals_.end(), uri, + [](const Principal& principal, std::string_view key) { return std::string_view(principal.uri) < key; }); + return it != principals_.end() && std::string_view(it->uri) == uri ? &*it : nullptr; +} + +bool PolicySnapshot::IsAuthorized(std::string_view uri, PrincipalRole role, + std::string_view tenant, + std::string_view operation) const noexcept { + const Principal* principal = FindPrincipal(uri); + if (principal == nullptr || principal->role != role || + (role != PrincipalRole::Adapter && role != PrincipalRole::Replica)) return false; + const auto it = std::lower_bound(principal->permissions.begin(), principal->permissions.end(), + std::pair{tenant, operation}, + [](const Permission& item, const auto& key) { + return std::string_view(item.tenant_id) < key.first || + (std::string_view(item.tenant_id) == key.first && + std::string_view(item.operation_id) < key.second); + }); + return it != principal->permissions.end() && std::string_view(it->tenant_id) == tenant && + std::string_view(it->operation_id) == operation; +} + +Result> PolicyLoader::Load(std::string_view input) { + try { + if (input.empty() || input.size() > kMaxJsonBytes) + Fail(PolicyErrorCode::ResourceLimit, "policy JSON must be 1..64 MiB"); + + InputGuard guard; + if (!Json::sax_parse(input.begin(), input.end(), &guard)) + Fail(PolicyErrorCode::InvalidJson, guard.error().empty() ? "invalid JSON syntax" : guard.error()); + Json root = Json::parse(input.begin(), input.end(), nullptr, false); + if (root.is_discarded()) Fail(PolicyErrorCode::InvalidJson, "policy JSON parse failed"); + CheckKeys(root, "root", {"schema_version", "mode", "epoch_id", "authority_incarnation", + "trust_root_sha256", "replica_slots", "tenants", "principals"}); + if (JsonU32(Required(root, "schema_version", "root"), "schema_version") != 1) + Fail(PolicyErrorCode::InvalidSchema, "unsupported policy schema_version"); + + const std::string mode_text = StringValue(Required(root, "mode", "root"), "mode"); + Mode mode; + if (mode_text == "strict") mode = Mode::Strict; + else if (mode_text == "credit") mode = Mode::Credit; + else Fail(PolicyErrorCode::InvalidValue, "mode must be strict or credit"); + const Id16 epoch = LowerHex<16>(Required(root, "epoch_id", "root"), "epoch_id"); + const Id16 authority = LowerHex<16>(Required(root, "authority_incarnation", "root"), "authority_incarnation"); + const Digest32 trust_fingerprint = LowerHex<32>(Required(root, "trust_root_sha256", "root"), "trust_root_sha256"); + const Json& slot_rows = Required(root, "replica_slots", "root"); + RequireArray(slot_rows, "replica_slots"); + if (slot_rows.empty() || slot_rows.size() > kMaxSlots) + Fail(PolicyErrorCode::ResourceLimit, "replica_slots must contain 1..8 entries"); + std::vector slots; + slots.reserve(slot_rows.size()); + for (const Json& row : slot_rows) { + CheckKeys(row, "replica slot", {"slot_id", "incarnation_id"}); + slots.push_back({JsonU32(Required(row, "slot_id", "replica slot"), "slot_id"), + LowerHex<16>(Required(row, "incarnation_id", "replica slot"), "incarnation_id")}); + } + std::sort(slots.begin(), slots.end(), [](const auto& a, const auto& b) { return a.slot_id < b.slot_id; }); + if (std::adjacent_find(slots.begin(), slots.end(), [](const auto& a, const auto& b) { + return a.slot_id == b.slot_id; + }) != slots.end()) + Fail(PolicyErrorCode::InvalidValue, "duplicate replica slot_id"); + + const Json& tenant_rows = Required(root, "tenants", "root"); + RequireArray(tenant_rows, "tenants"); + if (tenant_rows.empty() || tenant_rows.size() > kMaxTenants) + Fail(PolicyErrorCode::ResourceLimit, "tenants must contain 1..10,000 entries"); + std::vector tenants; + tenants.reserve(tenant_rows.size()); + std::size_t total_operations = 0; + for (const Json& row : tenant_rows) { + CheckKeys(row, "tenant", {"tenant_id", "capacity_units", "rate_units_per_second", "operations"}, + {"credit_batch_units"}); + TenantPolicy tenant; + tenant.tenant_id = StringValue(Required(row, "tenant_id", "tenant"), "tenant_id"); + ValidateIdentifier(tenant.tenant_id, "tenant_id"); + tenant.capacity_units = DecimalU64(Required(row, "capacity_units", "tenant"), "capacity_units"); + tenant.rate_units_per_second = DecimalU64(Required(row, "rate_units_per_second", "tenant"), "rate_units_per_second"); + if (tenant.capacity_units == 0 || tenant.capacity_units > kMaxPolicyValue || + tenant.rate_units_per_second == 0 || tenant.rate_units_per_second > kMaxPolicyValue) + Fail(PolicyErrorCode::InvalidValue, "capacity_units and rate_units_per_second must be in 1..10^9"); + if (mode == Mode::Credit) { + tenant.credit_batch_units = DecimalU64(Required(row, "credit_batch_units", "credit tenant"), "credit_batch_units"); + if (*tenant.credit_batch_units == 0 || *tenant.credit_batch_units > tenant.capacity_units) + Fail(PolicyErrorCode::InvalidValue, "credit_batch_units must be in 1..capacity_units"); + } else if (row.contains("credit_batch_units")) { + Fail(PolicyErrorCode::InvalidSchema, "strict tenant must omit credit_batch_units"); + } + const Json& operation_rows = Required(row, "operations", "tenant"); + RequireArray(operation_rows, "tenant.operations"); + if (operation_rows.empty() || operation_rows.size() > kMaxOperationsPerTenant) + Fail(PolicyErrorCode::ResourceLimit, "each tenant must have 1..64 operations"); + if (operation_rows.size() > kMaxOperationsTotal - total_operations) + Fail(PolicyErrorCode::ResourceLimit, "operation count exceeds 100,000"); + total_operations += operation_rows.size(); + tenant.operations.reserve(operation_rows.size()); + for (const Json& op_row : operation_rows) { + CheckKeys(op_row, "operation", {"operation_id", "cost_units"}); + OperationPolicy operation; + operation.operation_id = StringValue(Required(op_row, "operation_id", "operation"), "operation_id"); + ValidateIdentifier(operation.operation_id, "operation_id"); + operation.cost_units = DecimalU64(Required(op_row, "cost_units", "operation"), "cost_units"); + if (operation.cost_units == 0 || operation.cost_units > tenant.capacity_units) + Fail(PolicyErrorCode::InvalidValue, "operation cost must be in 1..capacity_units"); + tenant.operations.push_back(std::move(operation)); + } + std::sort(tenant.operations.begin(), tenant.operations.end(), [](const auto& a, const auto& b) { + return a.operation_id < b.operation_id; + }); + if (std::adjacent_find(tenant.operations.begin(), tenant.operations.end(), [](const auto& a, const auto& b) { + return a.operation_id == b.operation_id; + }) != tenant.operations.end()) + Fail(PolicyErrorCode::InvalidValue, "duplicate operation_id within tenant"); + if (tenant.credit_batch_units) { + const auto maximum_cost = std::max_element(tenant.operations.begin(), tenant.operations.end(), + [](const auto& a, const auto& b) { return a.cost_units < b.cost_units; })->cost_units; + if (*tenant.credit_batch_units < maximum_cost) + Fail(PolicyErrorCode::InvalidValue, "credit_batch_units must cover the maximum operation cost"); + } + tenants.push_back(std::move(tenant)); + } + std::sort(tenants.begin(), tenants.end(), [](const auto& a, const auto& b) { return a.tenant_id < b.tenant_id; }); + if (std::adjacent_find(tenants.begin(), tenants.end(), [](const auto& a, const auto& b) { + return a.tenant_id == b.tenant_id; + }) != tenants.end()) + Fail(PolicyErrorCode::InvalidValue, "duplicate tenant_id"); + + const Json& principal_rows = Required(root, "principals", "root"); + RequireArray(principal_rows, "principals"); + if (principal_rows.empty() || principal_rows.size() > kMaxPrincipals) + Fail(PolicyErrorCode::ResourceLimit, "principals must contain 1..10,000 entries"); + std::vector principals; + principals.reserve(principal_rows.size()); + std::size_t total_permissions = 0; + std::size_t adapter_count = 0; + std::size_t authority_count = 0; + std::set replica_principals; + for (const Json& row : principal_rows) { + CheckKeys(row, "principal", {"uri", "role", "permissions"}, {"slot_id"}); + Principal principal; + principal.uri = StringValue(Required(row, "uri", "principal"), "principal.uri"); + if (principal.uri.empty() || principal.uri.size() > kMaxPrincipalUriBytes || + std::any_of(principal.uri.begin(), principal.uri.end(), [](unsigned char c) { return c == 0 || c > 0x7f; })) + Fail(PolicyErrorCode::InvalidValue, "principal URI must be 1..256 ASCII bytes"); + const std::string role = StringValue(Required(row, "role", "principal"), "principal.role"); + if (role == "adapter") principal.role = PrincipalRole::Adapter; + else if (role == "replica") principal.role = PrincipalRole::Replica; + else if (role == "authority") principal.role = PrincipalRole::Authority; + else Fail(PolicyErrorCode::InvalidValue, "principal role must be adapter, replica, or authority"); + if (principal.role == PrincipalRole::Replica) { + principal.slot_id = JsonU32(Required(row, "slot_id", "replica principal"), "principal.slot_id"); + } else if (row.contains("slot_id")) { + Fail(PolicyErrorCode::InvalidSchema, "only replica principals may specify slot_id"); + } + const Json& permission_rows = Required(row, "permissions", "principal"); + RequireArray(permission_rows, "principal.permissions"); + if (permission_rows.size() > kMaxPermissionPairs - total_permissions) + Fail(PolicyErrorCode::ResourceLimit, "permission pair count exceeds 100,000"); + total_permissions += permission_rows.size(); + principal.permissions.reserve(permission_rows.size()); + for (const Json& pair : permission_rows) { + CheckKeys(pair, "permission", {"tenant_id", "operation_id"}); + Permission permission{StringValue(Required(pair, "tenant_id", "permission"), "permission.tenant_id"), + StringValue(Required(pair, "operation_id", "permission"), "permission.operation_id")}; + ValidateIdentifier(permission.tenant_id, "permission.tenant_id"); + ValidateIdentifier(permission.operation_id, "permission.operation_id"); + principal.permissions.push_back(std::move(permission)); + } + std::sort(principal.permissions.begin(), principal.permissions.end(), PermissionLess); + if (std::adjacent_find(principal.permissions.begin(), principal.permissions.end()) != principal.permissions.end()) + Fail(PolicyErrorCode::InvalidValue, "duplicate permission pair for principal"); + if (principal.role == PrincipalRole::Adapter) ++adapter_count; + if (principal.role == PrincipalRole::Authority) { + ++authority_count; + if (!principal.permissions.empty()) + Fail(PolicyErrorCode::InvalidValue, "authority principal permissions must be empty"); + const std::string expected = "spiffe://rateguard.local/authority/" + Hex(authority); + if (principal.uri != expected) + Fail(PolicyErrorCode::InvalidValue, "authority principal URI does not match authority_incarnation"); + } + if (principal.role == PrincipalRole::Replica) { + const auto slot_id = *principal.slot_id; + const ReplicaSlot* slot = FindSlotIn(slots, slot_id); + if (slot == nullptr) Fail(PolicyErrorCode::InvalidValue, "replica principal references an unknown slot"); + const std::string expected = "spiffe://rateguard.local/replica/" + std::to_string(slot_id) + "/" + Hex(slot->incarnation_id); + if (principal.uri != expected) + Fail(PolicyErrorCode::InvalidValue, "replica URI, slot_id, and incarnation_id must agree"); + if (!replica_principals.insert(slot_id).second) + Fail(PolicyErrorCode::InvalidValue, "duplicate replica principal for slot_id"); + } + if (principal.role == PrincipalRole::Adapter) { + constexpr std::string_view prefix = "spiffe://rateguard.local/adapter/"; + if (!principal.uri.starts_with(prefix) || + !ValidIdentifier(std::string_view(principal.uri).substr(prefix.size())) || + principal.uri != std::string(prefix) + std::string(std::string_view(principal.uri).substr(prefix.size()))) + Fail(PolicyErrorCode::InvalidValue, "adapter principal URI must use the exact A-02 identifier form"); + } + principals.push_back(std::move(principal)); + } + std::sort(principals.begin(), principals.end(), [](const auto& a, const auto& b) { return a.uri < b.uri; }); + if (std::adjacent_find(principals.begin(), principals.end(), [](const auto& a, const auto& b) { + return a.uri == b.uri; + }) != principals.end()) + Fail(PolicyErrorCode::InvalidValue, "duplicate principal URI"); + if (adapter_count == 0 || authority_count != 1) + Fail(PolicyErrorCode::InvalidValue, "require at least one adapter and exactly one authority principal"); + if (replica_principals.size() != slots.size()) + Fail(PolicyErrorCode::InvalidValue, "require exactly one replica principal for every registered slot"); + + for (const Principal& principal : principals) { + for (const Permission& permission : principal.permissions) { + const TenantPolicy* tenant = FindTenantIn(tenants, permission.tenant_id); + if (tenant == nullptr || tenant->FindOperation(permission.operation_id) == nullptr) + Fail(PolicyErrorCode::InvalidValue, "permission references an unknown tenant/operation pair"); + } + } + + auto snapshot = std::shared_ptr(new PolicySnapshot( + mode, epoch, authority, trust_fingerprint, std::move(slots), std::move(tenants), std::move(principals))); + auto canonical = CanonicalPolicyCodec::Encode(*snapshot); + if (std::holds_alternative(canonical)) return std::get(std::move(canonical)); + return snapshot; + } catch (const Failure& failure) { + return failure.error; + } catch (const std::bad_alloc&) { + return PolicyError{PolicyErrorCode::ResourceLimit, "insufficient memory to validate bounded policy"}; + } catch (const std::exception& exception) { + (void)exception; + return PolicyError{PolicyErrorCode::InvalidJson, "policy load failed"}; + } +} + +} // namespace rateguard::policy diff --git a/src/policy/policy_loader.h b/src/policy/policy_loader.h new file mode 100644 index 0000000..a3726c8 --- /dev/null +++ b/src/policy/policy_loader.h @@ -0,0 +1,30 @@ +#pragma once + +#include "policy_snapshot.h" + +#include +#include +#include +#include + +namespace rateguard::policy { + +class PolicyLoader final { + public: + static constexpr std::size_t kMaxJsonBytes = 64U * 1024U * 1024U; + static constexpr std::size_t kMaxCanonicalBytes = 64U * 1024U * 1024U; + static constexpr std::size_t kMaxJsonDepth = 32; + static constexpr std::size_t kMaxTenants = 10'000; + static constexpr std::size_t kMaxSlots = 8; + static constexpr std::size_t kMaxOperationsPerTenant = 64; + static constexpr std::size_t kMaxOperationsTotal = 100'000; + static constexpr std::size_t kMaxPrincipals = 10'000; + static constexpr std::size_t kMaxPermissionPairs = 100'000; + static constexpr std::size_t kMaxIdentifierBytes = 128; + static constexpr std::size_t kMaxPrincipalUriBytes = 256; + + [[nodiscard]] static Result> Load( + std::string_view json); +}; + +} // namespace rateguard::policy diff --git a/src/policy/policy_snapshot.h b/src/policy/policy_snapshot.h new file mode 100644 index 0000000..2cd15ad --- /dev/null +++ b/src/policy/policy_snapshot.h @@ -0,0 +1,114 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::policy { + +enum class Mode : std::uint32_t { Strict = 1, Credit = 2 }; +enum class PrincipalRole : std::uint32_t { Adapter = 1, Replica = 2, Authority = 3 }; + +enum class PolicyErrorCode : std::uint8_t { + InvalidJson, + InvalidSchema, + InvalidValue, + ResourceLimit, + CryptoFailure, + EncodingFailure, +}; + +struct PolicyError { + PolicyErrorCode code; + std::string message; +}; + +template +using Result = std::variant; + +using Id16 = std::array; +using Digest32 = std::array; + +struct OperationPolicy { + std::string operation_id; + std::uint64_t cost_units{}; +}; + +struct TenantPolicy { + std::string tenant_id; + std::uint64_t capacity_units{}; + std::uint64_t rate_units_per_second{}; + std::optional credit_batch_units; + std::vector operations; + + [[nodiscard]] std::uint64_t initial_balance_subunits() const noexcept { + return capacity_units * 1'000'000'000ULL; + } + [[nodiscard]] const OperationPolicy* FindOperation(std::string_view id) const noexcept; +}; + +struct ReplicaSlot { + std::uint32_t slot_id{}; + Id16 incarnation_id{}; +}; + +struct Permission { + std::string tenant_id; + std::string operation_id; + friend bool operator==(const Permission&, const Permission&) = default; +}; + +struct Principal { + std::string uri; + PrincipalRole role{}; + std::optional slot_id; + std::vector permissions; +}; + +class PolicyLoader; +class CanonicalPolicyCodec; + +// Constructed only by PolicyLoader after complete validation. Public accessors +// are read-only; lookup functions never insert or lazily allocate state. +class PolicySnapshot final { + public: + [[nodiscard]] Mode mode() const noexcept { return mode_; } + [[nodiscard]] const Id16& epoch_id() const noexcept { return epoch_id_; } + [[nodiscard]] const Id16& authority_incarnation() const noexcept { return authority_incarnation_; } + [[nodiscard]] const Digest32& trust_root_sha256() const noexcept { return trust_root_sha256_; } + [[nodiscard]] const std::vector& replica_slots() const noexcept { return replica_slots_; } + [[nodiscard]] const std::vector& tenants() const noexcept { return tenants_; } + [[nodiscard]] const std::vector& principals() const noexcept { return principals_; } + [[nodiscard]] const TenantPolicy* FindTenant(std::string_view id) const noexcept; + [[nodiscard]] const Principal* FindPrincipal(std::string_view uri) const noexcept; + [[nodiscard]] bool IsAuthorized(std::string_view uri, PrincipalRole role, + std::string_view tenant, + std::string_view operation) const noexcept; + + private: + friend class PolicyLoader; + friend class CanonicalPolicyCodec; + PolicySnapshot(Mode mode, Id16 epoch, Id16 authority, Digest32 trust_root, + std::vector slots, + std::vector tenants, + std::vector principals) + : mode_(mode), epoch_id_(epoch), authority_incarnation_(authority), + trust_root_sha256_(trust_root), replica_slots_(std::move(slots)), + tenants_(std::move(tenants)), principals_(std::move(principals)) {} + + Mode mode_; + Id16 epoch_id_; + Id16 authority_incarnation_; + Digest32 trust_root_sha256_; + std::vector replica_slots_; + std::vector tenants_; + std::vector principals_; +}; + +} // namespace rateguard::policy diff --git a/src/security/authorization_resolver.cpp b/src/security/authorization_resolver.cpp new file mode 100644 index 0000000..562a68b --- /dev/null +++ b/src/security/authorization_resolver.cpp @@ -0,0 +1,241 @@ +#include "rateguard/security/authorization_resolver.h" + +#include "policy/canonical_codec.h" +#include "rateguard/v1/error_contract.h" +#include "rateguard/v1/request_validation.h" + +#include +#include +#include + +namespace rateguard::security { +namespace { + +using Reason = AuthorizationFailureReason; +using Disposition = AuthorizationDisposition; +using Failure = AuthorizationFailure; + +Failure Invalid(Reason reason = Reason::InvalidRequest) noexcept { + return {reason, Disposition::InvalidArgument}; +} +Failure Denied(Reason reason) noexcept { + return {reason, Disposition::PermissionDenied}; +} +Failure Unauthenticated(Reason reason) noexcept { + return {reason, Disposition::Unauthenticated}; +} +Failure Unavailable(Reason reason) noexcept { + return {reason, Disposition::ApplicationUnavailable}; +} + +bool BytesEqual(std::string_view bytes, const policy::Id16& expected) noexcept { + return bytes.size() == expected.size() && + std::equal(bytes.begin(), bytes.end(), expected.begin(), + [](char actual, std::uint8_t value) { + return static_cast(actual) == value; + }); +} +bool BytesEqual(std::string_view bytes, const policy::Digest32& expected) noexcept { + return bytes.size() == expected.size() && + std::equal(bytes.begin(), bytes.end(), expected.begin(), + [](char actual, std::uint8_t value) { + return static_cast(actual) == value; + }); +} + +bool IsValidWallTime(WallTime value) noexcept { + return value.unix_seconds >= 0 && value.nanoseconds < 1'000'000'000U; +} + +PeerRole ToPeerRole(policy::PrincipalRole role) noexcept { + switch (role) { + case policy::PrincipalRole::Adapter: return PeerRole::kAdapter; + case policy::PrincipalRole::Replica: return PeerRole::kReplica; + case policy::PrincipalRole::Authority: return PeerRole::kAuthority; + } + return static_cast(0); +} + +bool IsPolicyBindingValid(const CertificateRegistry& registry) { + const auto& snapshot = registry.policy(); + if (registry.epoch_id() != snapshot.epoch_id() || + registry.authority_incarnation() != snapshot.authority_incarnation() || + registry.root_der_sha256() != snapshot.trust_root_sha256()) return false; + const auto digest = policy::CanonicalPolicyCodec::Digest(snapshot); + const auto* value = std::get_if(&digest); + return value != nullptr && *value == registry.policy_digest(); +} + +} // namespace + +std::variant +AuthorizationResolver::Create(std::shared_ptr registry, + ITrustedWallClock& trusted_clock) { + if (!registry) return Unavailable(Reason::NullRegistry); + try { + if (!IsPolicyBindingValid(*registry)) return Unavailable(Reason::PolicyBindingMismatch); + return AuthorizationResolver(std::move(registry), trusted_clock); + } catch (...) { + return Unavailable(Reason::PolicyBindingMismatch); + } +} + +std::optional AuthorizationResolver::CheckPeerAndClock( + const AuthenticatedPeer& peer) const { + if (!registry_) return Unavailable(Reason::NullRegistry); + if (peer.registry().get() != registry_.get()) + return Unauthenticated(Reason::MixedRegistry); + const auto* registered = registry_->Find(peer.uri()); + if (registered == nullptr || registered != peer.certificate() || + registered->peer.role != peer.role()) + return Unauthenticated(Reason::MixedRegistry); + + if (!trusted_clock_.Healthy()) return Unavailable(Reason::ClockUntrusted); + auto time_result = trusted_clock_.Now(); + const auto* now = std::get_if(&time_result); + if (now == nullptr || !trusted_clock_.Healthy() || !IsValidWallTime(*now)) + return Unavailable(Reason::ClockUntrusted); + if (!registry_->root_validity().Contains(*now)) + return Unauthenticated(*now < registry_->root_validity().not_before + ? Reason::CertificateNotYetValid + : Reason::CertificateExpired); + if (!registered->validity.Contains(*now)) + return Unauthenticated(*now < registered->validity.not_before + ? Reason::CertificateNotYetValid + : Reason::CertificateExpired); + return std::nullopt; +} + +std::variant +AuthorizationResolver::Resolve( + const AuthenticatedPeer& peer, RpcMethod method, + const rateguard::v1::CheckAdmissionRequest& request) const noexcept { + try { + if (const auto failure = CheckPeerAndClock(peer)) return *failure; + const auto& snapshot = registry_->policy(); + if (method == RpcMethod::AdapterCheckAdmission) { + if (peer.role() != PeerRole::kAdapter) + return Denied(Reason::MethodRoleMismatch); + } else if (method == RpcMethod::ReplicaStrictCheck) { + if (peer.role() != PeerRole::kReplica) + return Denied(Reason::MethodRoleMismatch); + } else { + return Invalid(Reason::InvalidRequest); + } + const auto& epoch = snapshot.epoch_id(); + const auto& digest = registry_->policy_digest(); + if (request.ByteSizeLong() > rateguard::v1::validation::kMaxRequestBytes || + !rateguard::v1::contract::IsValidIdentifier(request.tenant_id()) || + !rateguard::v1::contract::IsValidIdentifier(request.operation_id()) || + request.attempt_id().size() != 16 || request.epoch_id().size() != 16 || + request.policy_digest().size() != 32) + return Invalid(); + if (!BytesEqual(request.epoch_id(), epoch) || + !BytesEqual(request.policy_digest(), digest)) + return Invalid(Reason::PolicyBindingMismatch); + if (method == RpcMethod::ReplicaStrictCheck && + snapshot.mode() != policy::Mode::Strict) + return Invalid(Reason::ModeMismatch); + + const auto* tenant = snapshot.FindTenant(request.tenant_id()); + if (tenant == nullptr) return Invalid(Reason::UnknownTenant); + const auto* operation = tenant->FindOperation(request.operation_id()); + if (operation == nullptr) return Invalid(Reason::UnknownOperation); + + const auto* principal = snapshot.FindPrincipal(peer.uri()); + if (principal == nullptr || ToPeerRole(principal->role) != peer.role()) + return Denied(Reason::MethodRoleMismatch); + if (!snapshot.IsAuthorized(peer.uri(), principal->role, + request.tenant_id(), request.operation_id())) + return Denied(Reason::UnauthorizedPair); + + const std::optional replica_slot = principal->slot_id; + std::optional replica_incarnation; + if (method == RpcMethod::ReplicaStrictCheck && + (!principal->slot_id || principal->role != policy::PrincipalRole::Replica)) + return Unavailable(Reason::PolicyBindingMismatch); + if (principal->role == policy::PrincipalRole::Replica) { + if (!principal->slot_id) + return Unavailable(Reason::PolicyBindingMismatch); + const auto slot = std::find_if(snapshot.replica_slots().begin(), + snapshot.replica_slots().end(), [&](const policy::ReplicaSlot& value) { + return value.slot_id == *principal->slot_id; + }); + if (slot == snapshot.replica_slots().end()) + return Unavailable(Reason::PolicyBindingMismatch); + replica_incarnation = slot->incarnation_id; + } + auto payload = std::make_shared( + peer, method, request.tenant_id(), request.operation_id(), + operation->cost_units, snapshot.mode(), request.attempt_id(), + snapshot.epoch_id(), digest, replica_slot, replica_incarnation); + const AuthorizedOperation authorized(std::move(payload)); + return std::variant( + std::in_place_index<0>, authorized); + } catch (...) { + return Unavailable(Reason::PolicyBindingMismatch); + } +} + +std::variant +AuthorizationResolver::Resolve( + const AuthenticatedPeer& peer, RpcMethod method, + const rateguard::v1::AcquireCreditRequest& request) const noexcept { + try { + if (const auto failure = CheckPeerAndClock(peer)) return *failure; + const auto& snapshot = registry_->policy(); + if (method != RpcMethod::ReplicaAcquireCredit) + return Invalid(Reason::InvalidRequest); + if (peer.role() != PeerRole::kReplica) + return Denied(Reason::MethodRoleMismatch); + const auto& digest = registry_->policy_digest(); + if (request.ByteSizeLong() > rateguard::v1::validation::kMaxRequestBytes || + !rateguard::v1::contract::IsValidIdentifier(request.tenant_id()) || + !rateguard::v1::contract::IsValidIdentifier(request.trigger_operation_id()) || + request.incarnation_id().size() != 16 || request.epoch_id().size() != 16 || + request.policy_digest().size() != 32 || request.sequence() == 0) + return Invalid(); + if (!BytesEqual(request.epoch_id(), snapshot.epoch_id()) || + !BytesEqual(request.policy_digest(), digest)) + return Invalid(Reason::PolicyBindingMismatch); + if (snapshot.mode() != policy::Mode::Credit) + return Invalid(Reason::ModeMismatch); + + const auto* principal = snapshot.FindPrincipal(peer.uri()); + if (principal == nullptr || principal->role != policy::PrincipalRole::Replica || + !principal->slot_id) + return Denied(Reason::MethodRoleMismatch); + if (*principal->slot_id != request.slot()) + return Invalid(Reason::ReplicaSlotMismatch); + const auto slot = std::find_if(snapshot.replica_slots().begin(), + snapshot.replica_slots().end(), [&](const policy::ReplicaSlot& value) { + return value.slot_id == request.slot(); + }); + if (slot == snapshot.replica_slots().end()) + return Invalid(Reason::ReplicaSlotMismatch); + if (!BytesEqual(request.incarnation_id(), slot->incarnation_id)) + return Invalid(Reason::ReplicaIncarnationMismatch); + + const auto* tenant = snapshot.FindTenant(request.tenant_id()); + if (tenant == nullptr) return Invalid(Reason::UnknownTenant); + const auto* operation = tenant->FindOperation(request.trigger_operation_id()); + if (operation == nullptr) return Invalid(Reason::UnknownOperation); + if (!snapshot.IsAuthorized(peer.uri(), principal->role, + request.tenant_id(), request.trigger_operation_id())) + return Denied(Reason::UnauthorizedPair); + if (request.trigger_cost_units() != operation->cost_units) + return Invalid(Reason::TriggerCostMismatch); + + auto payload = std::make_shared( + peer, method, request.tenant_id(), request.trigger_operation_id(), + operation->cost_units, request.slot(), slot->incarnation_id, + request.sequence(), snapshot.epoch_id(), digest); + const AuthorizedGrant authorized(std::move(payload)); + return std::variant( + std::in_place_index<0>, authorized); + } catch (...) { + return Unavailable(Reason::PolicyBindingMismatch); + } +} + +} // namespace rateguard::security diff --git a/src/security/certificate_registry.cpp b/src/security/certificate_registry.cpp new file mode 100644 index 0000000..d763476 --- /dev/null +++ b/src/security/certificate_registry.cpp @@ -0,0 +1,443 @@ +#include "rateguard/security/certificate_registry.h" + +#include "policy/policy_loader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::security { +namespace { + +using ErrorCode = CertificateRegistryErrorCode; +using Error = CertificateRegistryError; +using PolicyRole = policy::PrincipalRole; + +template +using OsslPtr = std::unique_ptr; +using BioPtr = std::unique_ptr; +using X509Ptr = OsslPtr; +using StorePtr = OsslPtr; +using StoreContextPtr = OsslPtr; +using PublicKeyPtr = OsslPtr; +using BasicConstraintsPtr = OsslPtr; +using KeyUsagePtr = OsslPtr; +using ExtendedUsagePtr = OsslPtr; +using GeneralNamesPtr = OsslPtr; + +template +using InternalResult = std::variant; + +bool IsAsciiWhitespace(unsigned char c) noexcept { + return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v'; +} + +bool IsDigit(unsigned char c) noexcept { return c >= '0' && c <= '9'; } + +bool DecodeSingleCertificatePem(std::string_view pem, X509Ptr* out) { + constexpr std::string_view kBegin = "-----BEGIN CERTIFICATE-----"; + if (out == nullptr || pem.empty() || pem.size() > CertificateRegistry::kMaxCertificatePemBytes || + pem.find('\0') != std::string_view::npos) return false; + std::size_t first = 0; + while (first < pem.size() && IsAsciiWhitespace(static_cast(pem[first]))) ++first; + if (pem.substr(first, kBegin.size()) != kBegin) return false; + + BIO* raw_bio = BIO_new_mem_buf(pem.data() + first, static_cast(pem.size() - first)); + if (raw_bio == nullptr) return false; + BioPtr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (raw_cert == nullptr) return false; + X509Ptr cert(raw_cert, X509_free); + char trailing[512]; + for (;;) { + const int count = BIO_read(bio.get(), trailing, sizeof(trailing)); + if (count < 0) return false; + if (count == 0) break; + for (int i = 0; i < count; ++i) + if (!IsAsciiWhitespace(static_cast(trailing[i]))) return false; + } + *out = std::move(cert); + return true; +} + +template +bool HasExactlyOneExtension(X509* cert, int nid, + std::unique_ptr* extension) { + const int index = X509_get_ext_by_NID(cert, nid, -1); + if (index < 0 || X509_get_ext_by_NID(cert, nid, index) >= 0) return false; + int critical = -1; + T* raw = static_cast(X509_get_ext_d2i(cert, nid, &critical, nullptr)); + if (raw == nullptr || critical == -2) { + if (raw != nullptr) Free(raw); + return false; + } + extension->reset(raw); + return true; +} + +bool HasExpectedEku(X509* cert, PolicyRole role) { + ExtendedUsagePtr usage(nullptr, EXTENDED_KEY_USAGE_free); + if (!HasExactlyOneExtension( + cert, NID_ext_key_usage, &usage)) return false; + const int count = sk_ASN1_OBJECT_num(usage.get()); + int expected_client = 0; + int expected_server = 0; + switch (role) { + case PolicyRole::Adapter: expected_client = 1; break; + case PolicyRole::Replica: expected_client = 1; expected_server = 1; break; + case PolicyRole::Authority: expected_server = 1; break; + default: return false; + } + if (count != expected_client + expected_server) return false; + int clients = 0; + int servers = 0; + for (int i = 0; i < count; ++i) { + const int nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(usage.get(), i)); + if (nid == NID_client_auth) ++clients; + else if (nid == NID_server_auth) ++servers; + else return false; // Reject anyExtendedKeyUsage and every extra purpose. + } + return clients == expected_client && servers == expected_server; +} + +bool HasExpectedKeyUsage(X509* cert, bool root) { + KeyUsagePtr usage(nullptr, ASN1_BIT_STRING_free); + if (!HasExactlyOneExtension( + cert, NID_key_usage, &usage)) return false; + if (root) { + return ASN1_BIT_STRING_get_bit(usage.get(), 5) == 1; + } + return ASN1_BIT_STRING_get_bit(usage.get(), 0) == 1 && + ASN1_BIT_STRING_get_bit(usage.get(), 5) == 0; +} + +bool HasExpectedBasicConstraints(X509* cert, bool root) { + BasicConstraintsPtr constraints(nullptr, BASIC_CONSTRAINTS_free); + if (!HasExactlyOneExtension( + cert, NID_basic_constraints, &constraints)) return false; + if (root) { + if (constraints->ca == 0 || constraints->pathlen == nullptr) return false; + std::int64_t path_length = -1; + return ASN1_INTEGER_get_int64(&path_length, constraints->pathlen) == 1 && + path_length == 0; + } + return constraints->ca == 0 && constraints->pathlen == nullptr; +} + +bool HasP256Sha256Profile(X509* cert) { + if (X509_get_signature_nid(cert) != NID_ecdsa_with_SHA256) return false; + PublicKeyPtr key(X509_get_pubkey(cert), EVP_PKEY_free); + if (!key || EVP_PKEY_is_a(key.get(), "EC") != 1) return false; + std::array group{}; + std::size_t group_size = 0; + if (EVP_PKEY_get_utf8_string_param(key.get(), OSSL_PKEY_PARAM_GROUP_NAME, + group.data(), group.size(), &group_size) != 1) + return false; + const std::string_view name(group.data(), group_size); + return name == "prime256v1" || name == "secp256r1"; +} + +bool ParseCertificateTime(const ASN1_TIME* value, WallTime* out) { + if (value == nullptr || out == nullptr || ASN1_TIME_check(value) != 1) return false; + const int type = ASN1_STRING_type(value); + const int length = ASN1_STRING_length(value); + const unsigned char* data = ASN1_STRING_get0_data(value); + const int digits = type == V_ASN1_UTCTIME ? 12 : + type == V_ASN1_GENERALIZEDTIME ? 14 : -1; + if (digits < 0 || length != digits + 1 || data == nullptr || data[digits] != 'Z') + return false; + for (int i = 0; i < digits; ++i) + if (!IsDigit(data[i])) return false; + + std::tm fields{}; + if (ASN1_TIME_to_tm(value, &fields) != 1) return false; + const int full_year = fields.tm_year + 1900; + // RFC 5280 requires UTCTime through 2049 and GeneralizedTime from 2050. + if ((type == V_ASN1_UTCTIME && (full_year < 1950 || full_year > 2049)) || + (type == V_ASN1_GENERALIZEDTIME && (full_year < 2050 || full_year > 9999))) + return false; + const std::chrono::year_month_day date{ + std::chrono::year{full_year}, + std::chrono::month{static_cast(fields.tm_mon + 1)}, + std::chrono::day{static_cast(fields.tm_mday)}}; + if (!date.ok() || fields.tm_hour < 0 || fields.tm_hour > 23 || + fields.tm_min < 0 || fields.tm_min > 59 || + fields.tm_sec < 0 || fields.tm_sec > 59) return false; + const auto days = std::chrono::sys_days{date}.time_since_epoch().count(); + constexpr std::int64_t kSecondsPerDay = 86'400; + // ASN.1 years are bounded to 0000..9999, so this checked multiplication is + // far below int64 limits; keep the check explicit to avoid future narrowing. + if (days > std::numeric_limits::max() / kSecondsPerDay || + days < std::numeric_limits::min() / kSecondsPerDay) return false; + const std::int64_t day_seconds = days * kSecondsPerDay; + const std::int64_t second_of_day = fields.tm_hour * 3600LL + fields.tm_min * 60LL + fields.tm_sec; + if (day_seconds > std::numeric_limits::max() - second_of_day) return false; + *out = WallTime{day_seconds + second_of_day, 0}; + return true; +} + +InternalResult GetValidity( + X509* cert, WallTime now, ErrorCode invalid_time_code) { + CertificateValidityWindow window{}; + if (!ParseCertificateTime(X509_get0_notBefore(cert), &window.not_before) || + !ParseCertificateTime(X509_get0_notAfter(cert), &window.not_after) || + !(window.not_before < window.not_after)) return invalid_time_code; + if (now < window.not_before) return ErrorCode::CertificateNotYetValid; + if (!(now < window.not_after)) return ErrorCode::CertificateExpired; + return window; +} + +bool GetDerAndDigest(X509* cert, std::vector* der, + policy::Digest32* digest) { + if (der == nullptr || digest == nullptr) return false; + const int size = i2d_X509(cert, nullptr); + if (size <= 0 || static_cast(size) > CertificateRegistry::kMaxCertificatePemBytes) + return false; + der->resize(static_cast(size)); + unsigned char* cursor = der->data(); + if (i2d_X509(cert, &cursor) != size) return false; + unsigned int digest_size = 0; + return EVP_Digest(der->data(), der->size(), digest->data(), &digest_size, + EVP_sha256(), nullptr) == 1 && digest_size == digest->size(); +} + +bool VerifyLeafPurpose(X509* leaf, X509* root, WallTime now, int purpose) { + PublicKeyPtr root_key(X509_get_pubkey(root), EVP_PKEY_free); + if (!root_key || X509_NAME_cmp(X509_get_issuer_name(leaf), + X509_get_subject_name(root)) != 0 || + X509_verify(leaf, root_key.get()) != 1) return false; + StorePtr store(X509_STORE_new(), X509_STORE_free); + if (!store || X509_STORE_add_cert(store.get(), root) != 1 || + X509_STORE_set_flags(store.get(), X509_V_FLAG_X509_STRICT) != 1) return false; + StoreContextPtr context(X509_STORE_CTX_new(), X509_STORE_CTX_free); + if (!context || X509_STORE_CTX_init(context.get(), store.get(), leaf, nullptr) != 1) + return false; + X509_VERIFY_PARAM* params = X509_STORE_CTX_get0_param(context.get()); + if (params == nullptr || X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_X509_STRICT) != 1) + return false; + if constexpr (std::numeric_limits::is_signed) { + if (now.unix_seconds < static_cast(std::numeric_limits::min()) || + now.unix_seconds > static_cast(std::numeric_limits::max())) return false; + } else { + if (now.unix_seconds < 0 || + static_cast(now.unix_seconds) > std::numeric_limits::max()) return false; + } + X509_VERIFY_PARAM_set_time(params, static_cast(now.unix_seconds)); + if (X509_STORE_CTX_set_purpose(context.get(), purpose) != 1) return false; + return X509_verify_cert(context.get()) == 1; +} + +bool VerifyRootSelfSignature(X509* root) { + if (X509_NAME_cmp(X509_get_subject_name(root), X509_get_issuer_name(root)) != 0) + return false; + PublicKeyPtr root_key(X509_get_pubkey(root), EVP_PKEY_free); + return root_key && X509_verify(root, root_key.get()) == 1; +} + +PeerRole ToPeerRole(PolicyRole role) { + switch (role) { + case PolicyRole::Adapter: return PeerRole::kAdapter; + case PolicyRole::Replica: return PeerRole::kReplica; + case PolicyRole::Authority: return PeerRole::kAuthority; + } + return static_cast(0); +} + +int PurposeFor(PolicyRole role) { + return role == PolicyRole::Authority ? X509_PURPOSE_SSL_SERVER + : X509_PURPOSE_SSL_CLIENT; +} + +} // namespace + +CertificateRegistry::CertificateRegistry( + std::shared_ptr policy, + policy::Digest32 policy_digest, policy::Digest32 root_der_sha256, + CertificateValidityWindow root_validity, + std::vector peers, + std::shared_ptr peer_pins, WallTime validated_at) + : policy_(std::move(policy)), policy_digest_(policy_digest), + root_der_sha256_(root_der_sha256), root_validity_(root_validity), + peers_(std::move(peers)), peer_pins_(std::move(peer_pins)), + validated_at_(validated_at) {} + +const RegisteredCertificate* CertificateRegistry::Find( + std::string_view exact_uri) const noexcept { + const auto found = std::lower_bound(peers_.begin(), peers_.end(), exact_uri, + [](const RegisteredCertificate& peer, std::string_view uri) { + return std::string_view(peer.peer.uri) < uri; + }); + return found != peers_.end() && std::string_view(found->peer.uri) == exact_uri + ? &*found : nullptr; +} + +const policy::Id16& CertificateRegistry::epoch_id() const noexcept { + return policy_->epoch_id(); +} +const policy::Id16& CertificateRegistry::authority_incarnation() const noexcept { + return policy_->authority_incarnation(); +} +const policy::PolicySnapshot& CertificateRegistry::policy() const noexcept { + return *policy_; +} +bool CertificateRegistry::AllValidAt(WallTime time) const noexcept { + if (time.unix_seconds < 0 || time.nanoseconds >= 1'000'000'000U || + !root_validity_.Contains(time)) return false; + return std::all_of(peers_.begin(), peers_.end(), + [time](const auto& peer) { return peer.validity.Contains(time); }); +} + +CertificateRegistryResult> +CertificateRegistryLoader::Load( + std::shared_ptr snapshot, + std::string_view root_certificate_pem, + std::span leaf_certificate_pems, + ITrustedWallClock& trusted_clock) try { + if (!snapshot) return Error{ErrorCode::NullPolicy}; + if (root_certificate_pem.size() > CertificateRegistry::kMaxCertificatePemBytes || + leaf_certificate_pems.size() > policy::PolicyLoader::kMaxPrincipals) + return Error{ErrorCode::ResourceLimit}; + std::size_t total_bytes = root_certificate_pem.size(); + for (const auto pem : leaf_certificate_pems) { + if (pem.size() > CertificateRegistry::kMaxCertificatePemBytes || + pem.size() > CertificateRegistry::kMaxAggregatePemBytes - total_bytes) + return Error{ErrorCode::ResourceLimit}; + total_bytes += pem.size(); + } + if (total_bytes > CertificateRegistry::kMaxAggregatePemBytes) + return Error{ErrorCode::ResourceLimit}; + if (leaf_certificate_pems.size() != snapshot->principals().size() || + leaf_certificate_pems.size() > CertificateRegistry::kMaxPrincipalCount) + return Error{ErrorCode::LeafCountMismatch}; + + auto now_result = trusted_clock.Now(); + const auto* now = std::get_if(&now_result); + if (now == nullptr || !trusted_clock.Healthy() || now->unix_seconds < 0 || + now->nanoseconds >= 1'000'000'000U) + return Error{ErrorCode::ClockUntrusted}; + const WallTime validated_at = *now; + + auto digest_result = policy::CanonicalPolicyCodec::Digest(*snapshot); + const auto* policy_digest = std::get_if(&digest_result); + if (policy_digest == nullptr) { + const auto& error = std::get(digest_result); + if (error.code == policy::PolicyErrorCode::ResourceLimit) + return Error{ErrorCode::ResourceLimit}; + if (error.code == policy::PolicyErrorCode::CryptoFailure) + return Error{ErrorCode::CryptoFailure}; + return Error{ErrorCode::PolicyDigestFailure}; + } + + X509Ptr root(nullptr, X509_free); + if (!DecodeSingleCertificatePem(root_certificate_pem, &root)) + return Error{ErrorCode::InvalidPem}; + if (!HasP256Sha256Profile(root.get()) || !HasExpectedBasicConstraints(root.get(), true) || + !HasExpectedKeyUsage(root.get(), true) || X509_check_ca(root.get()) <= 0 || + !VerifyRootSelfSignature(root.get())) + return Error{ErrorCode::InvalidRootProfile}; + + std::vector root_der; + policy::Digest32 root_digest{}; + if (!GetDerAndDigest(root.get(), &root_der, &root_digest)) + return Error{ErrorCode::CryptoFailure}; + if (root_digest != snapshot->trust_root_sha256()) + return Error{ErrorCode::RootFingerprintMismatch}; + auto root_validity_result = GetValidity(root.get(), validated_at, + ErrorCode::InvalidRootProfile); + if (const auto* error = std::get_if(&root_validity_result)) + return Error{*error}; + const auto root_validity = std::get(root_validity_result); + + std::vector registered; + std::vector pins; + registered.reserve(leaf_certificate_pems.size()); + pins.reserve(leaf_certificate_pems.size()); + std::set> seen; + for (const auto pem : leaf_certificate_pems) { + X509Ptr leaf(nullptr, X509_free); + if (!DecodeSingleCertificatePem(pem, &leaf)) return Error{ErrorCode::InvalidPem}; + GeneralNamesPtr names(nullptr, GENERAL_NAMES_free); + if (!HasExactlyOneExtension( + leaf.get(), NID_subject_alt_name, &names)) + return Error{ErrorCode::IdentityMismatch}; + std::string uri; + std::size_t uri_count = 0; + const int general_name_count = sk_GENERAL_NAME_num(names.get()); + for (int i = 0; i < general_name_count; ++i) { + const GENERAL_NAME* name = sk_GENERAL_NAME_value(names.get(), i); + if (name == nullptr || name->type != GEN_URI) continue; + ++uri_count; + const ASN1_IA5STRING* value = name->d.uniformResourceIdentifier; + const int length = ASN1_STRING_length(value); + const unsigned char* data = ASN1_STRING_get0_data(value); + if (length <= 0 || length > 256 || data == nullptr || + std::memchr(data, '\0', static_cast(length)) != nullptr) + return Error{ErrorCode::IdentityMismatch}; + uri.assign(reinterpret_cast(data), static_cast(length)); + for (unsigned char c : uri) if (c > 0x7f) return Error{ErrorCode::IdentityMismatch}; + } + if (uri_count != 1) return Error{ErrorCode::IdentityMismatch}; + const policy::Principal* principal = snapshot->FindPrincipal(uri); + if (principal == nullptr) return Error{ErrorCode::UnknownPrincipal}; + if (!seen.insert(uri).second) return Error{ErrorCode::DuplicateLeaf}; + + if (!HasP256Sha256Profile(leaf.get()) || + !HasExpectedBasicConstraints(leaf.get(), false) || + !HasExpectedKeyUsage(leaf.get(), false) || !HasExpectedEku(leaf.get(), principal->role) || + X509_check_ca(leaf.get()) != 0) + return Error{ErrorCode::InvalidLeafProfile}; + auto validity_result = GetValidity(leaf.get(), validated_at, + ErrorCode::InvalidLeafProfile); + if (const auto* error = std::get_if(&validity_result)) return Error{*error}; + if (!VerifyLeafPurpose(leaf.get(), root.get(), validated_at, + PurposeFor(principal->role))) + return Error{ErrorCode::InvalidChain}; + if (principal->role == PolicyRole::Replica && + !VerifyLeafPurpose(leaf.get(), root.get(), validated_at, X509_PURPOSE_SSL_SERVER)) + return Error{ErrorCode::InvalidChain}; + std::vector leaf_der; + policy::Digest32 leaf_digest{}; + if (!GetDerAndDigest(leaf.get(), &leaf_der, &leaf_digest)) + return Error{ErrorCode::CryptoFailure}; + RegisteredPeer peer_pin{uri, ToPeerRole(principal->role), leaf_digest}; + RegisteredCertificate certificate{peer_pin, + std::get(validity_result)}; + pins.push_back(std::move(peer_pin)); + registered.push_back(std::move(certificate)); + } + if (seen.size() != snapshot->principals().size()) return Error{ErrorCode::MissingPrincipal}; + std::sort(registered.begin(), registered.end(), [](const auto& a, const auto& b) { + return a.peer.uri < b.peer.uri; + }); + auto pin_registry = std::make_shared(std::move(pins)); + if (!pin_registry->valid()) return Error{ErrorCode::DuplicateLeaf}; + return std::shared_ptr(new CertificateRegistry( + std::move(snapshot), *policy_digest, root_digest, root_validity, + std::move(registered), std::move(pin_registry), validated_at)); +} catch (const std::bad_alloc&) { + return Error{ErrorCode::ResourceLimit}; +} catch (const std::exception&) { + return Error{ErrorCode::CryptoFailure}; +} catch (...) { + return Error{ErrorCode::CryptoFailure}; +} + +} // namespace rateguard::security diff --git a/src/security/client_call_guard.cpp b/src/security/client_call_guard.cpp new file mode 100644 index 0000000..58445e4 --- /dev/null +++ b/src/security/client_call_guard.cpp @@ -0,0 +1,199 @@ +#include "rateguard/security/client_call_guard.h" + +#include "policy/canonical_codec.h" + +#include +#include + +namespace rateguard::security { +namespace { + +using Reason = ClientGuardFailureReason; +using Disposition = ClientGuardDisposition; +using Failure = ClientCallGuardFailure; + +Failure CredentialFailure(Reason reason) noexcept { + return {reason, Disposition::CredentialInvalid}; +} +Failure DependencyFailure(Reason reason) noexcept { + return {reason, Disposition::ApplicationUnavailable}; +} + +bool IsValidWallTime(WallTime value) noexcept { + return value.unix_seconds >= 0 && value.nanoseconds < 1'000'000'000U; +} + +bool IsConfiguredUri(std::string_view uri) noexcept { + if (uri.empty() || uri.size() > 256 || + uri.find('\0') != std::string_view::npos) return false; + return std::all_of(uri.begin(), uri.end(), [](unsigned char byte) { + return byte <= 0x7f; + }); +} + +bool PolicyBindingMatches(const CertificateRegistry& registry) { + const auto& policy = registry.policy(); + if (registry.epoch_id() != policy.epoch_id() || + registry.authority_incarnation() != policy.authority_incarnation() || + registry.root_der_sha256() != policy.trust_root_sha256()) return false; + const auto digest = policy::CanonicalPolicyCodec::Digest(policy); + const auto* value = std::get_if(&digest); + return value != nullptr && *value == registry.policy_digest(); +} + +bool HasRole(const CertificateRegistry& registry, std::string_view uri, + PeerRole expected) noexcept { + const auto* certificate = registry.Find(uri); + const auto* principal = registry.policy().FindPrincipal(uri); + if (certificate == nullptr || principal == nullptr) return false; + if (certificate->peer.role != expected) return false; + switch (expected) { + case PeerRole::kAdapter: + return principal->role == policy::PrincipalRole::Adapter && + !principal->slot_id.has_value(); + case PeerRole::kReplica: { + if (principal->role != policy::PrincipalRole::Replica || !principal->slot_id) + return false; + return std::any_of(registry.policy().replica_slots().begin(), + registry.policy().replica_slots().end(), + [&](const policy::ReplicaSlot& slot) { + return slot.slot_id == *principal->slot_id; + }); + } + case PeerRole::kAuthority: + return principal->role == policy::PrincipalRole::Authority && + !principal->slot_id.has_value(); + } + return false; +} + +std::pair ExpectedRoles(ClientCallPurpose purpose) noexcept { + switch (purpose) { + case ClientCallPurpose::AdapterToReplicaAdmission: + return {PeerRole::kAdapter, PeerRole::kReplica}; + case ClientCallPurpose::ReplicaToAuthority: + return {PeerRole::kReplica, PeerRole::kAuthority}; + } + return {static_cast(0), static_cast(0)}; +} + +Reason ExpiryReason(const CertificateValidityWindow& window, WallTime now, + Reason before, Reason after) noexcept { + return now < window.not_before ? before : after; +} + +} // namespace + +std::variant ClientCallGuard::Create( + std::shared_ptr registry, + ITrustedWallClock& trusted_clock, ClientCallPurpose purpose, + std::string local_uri, std::string expected_server_uri) { + if (!registry) return DependencyFailure(Reason::NullRegistry); + if (!IsConfiguredUri(local_uri)) return CredentialFailure(Reason::InvalidClientIdentity); + if (!IsConfiguredUri(expected_server_uri)) + return CredentialFailure(Reason::InvalidServerIdentity); + try { + if (!PolicyBindingMatches(*registry)) + return DependencyFailure(Reason::PolicyBindingMismatch); + const auto roles = ExpectedRoles(purpose); + if (roles.first == static_cast(0)) + return CredentialFailure(Reason::InvalidClientIdentity); + if (!registry->Find(local_uri)) + return CredentialFailure(Reason::MissingClientCertificate); + if (!registry->Find(expected_server_uri)) + return CredentialFailure(Reason::MissingServerCertificate); + if (!HasRole(*registry, local_uri, roles.first)) + return CredentialFailure(Reason::ClientRoleMismatch); + if (!HasRole(*registry, expected_server_uri, roles.second)) + return CredentialFailure(Reason::ServerRoleMismatch); + + auto binding = std::make_shared( + detail::ClientCallBinding{registry, registry->epoch_id(), + registry->policy_digest(), purpose, + std::move(local_uri), + std::move(expected_server_uri)}); + const ClientCallGuard guard(std::move(binding), trusted_clock); + return std::variant( + std::in_place_index<0>, guard); + } catch (...) { + return DependencyFailure(Reason::DependencyFailure); + } +} + +std::variant +ClientCallGuard::ValidateCurrentTime() const { + if (!binding_ || !binding_->registry) + return DependencyFailure(Reason::PolicyBindingMismatch); + if (!trusted_clock_.Healthy()) return DependencyFailure(Reason::ClockUntrusted); + const auto time_result = trusted_clock_.Now(); + const auto* now = std::get_if(&time_result); + if (now == nullptr || !trusted_clock_.Healthy()) + return DependencyFailure(Reason::ClockUntrusted); + if (!IsValidWallTime(*now)) return DependencyFailure(Reason::InvalidWallTime); + + const auto& registry = *binding_->registry; + if (!registry.root_validity().Contains(*now)) + return CredentialFailure(ExpiryReason(registry.root_validity(), *now, + Reason::RootNotYetValid, Reason::RootExpired)); + const auto* local = registry.Find(binding_->local_uri); + if (local == nullptr) return CredentialFailure(Reason::MissingClientCertificate); + if (!local->validity.Contains(*now)) + return CredentialFailure(ExpiryReason(local->validity, *now, + Reason::ClientNotYetValid, Reason::ClientExpired)); + const auto* server = registry.Find(binding_->expected_server_uri); + if (server == nullptr) return CredentialFailure(Reason::MissingServerCertificate); + if (!server->validity.Contains(*now)) + return CredentialFailure(ExpiryReason(server->validity, *now, + Reason::ServerNotYetValid, Reason::ServerExpired)); + return *now; +} + +std::variant +ClientCallGuard::ValidateBeforeCall() const { + try { + const auto time_result = ValidateCurrentTime(); + const auto* now = std::get_if(&time_result); + if (now == nullptr) + return std::get(time_result); + auto payload = std::make_shared( + detail::ClientCallProofPayload{binding_, *now}); + const PreparedClientCall prepared(std::move(payload)); + return std::variant( + std::in_place_index<0>, prepared); + } catch (...) { + return DependencyFailure(Reason::DependencyFailure); + } +} + +std::variant +ClientCallGuard::ValidateBeforeForward(const PreparedClientCall& prepared) const { + try { + if (!binding_ || !prepared.payload_ || + prepared.payload_->binding.get() != binding_.get() || + !prepared.payload_->binding || + prepared.payload_->binding->registry.get() != binding_->registry.get() || + prepared.payload_->binding->epoch_id != binding_->epoch_id || + prepared.payload_->binding->policy_digest != binding_->policy_digest || + prepared.payload_->binding->purpose != binding_->purpose || + prepared.payload_->binding->local_uri != binding_->local_uri || + prepared.payload_->binding->expected_server_uri != binding_->expected_server_uri || + !IsValidWallTime(prepared.payload_->checked_at)) + return CredentialFailure(Reason::ForeignPreparedCall); + + const auto time_result = ValidateCurrentTime(); + const auto* now = std::get_if(&time_result); + if (now == nullptr) + return std::get(time_result); + if (*now < prepared.payload_->checked_at) + return DependencyFailure(Reason::ClockUntrusted); + auto payload = std::make_shared( + detail::ClientCallProofPayload{binding_, *now}); + const ClientCallGuardPassed passed(std::move(payload)); + return std::variant( + std::in_place_index<0>, passed); + } catch (...) { + return DependencyFailure(Reason::DependencyFailure); + } +} + +} // namespace rateguard::security diff --git a/src/security/peer_authenticator.cpp b/src/security/peer_authenticator.cpp new file mode 100644 index 0000000..34243e5 --- /dev/null +++ b/src/security/peer_authenticator.cpp @@ -0,0 +1,215 @@ +#include "rateguard/security/peer_authenticator.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace rateguard::security { +namespace { + +PeerAuthFailure Failure(PeerAuthFailureReason reason, + PeerAuthDisposition disposition) noexcept { + return PeerAuthFailure{reason, disposition}; +} + +enum class DigestResult : std::uint8_t { Success, InvalidPem, CryptoFailure }; + +bool IsAsciiWhitespace(unsigned char c) noexcept { + return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v'; +} + +bool IsAscii(std::string_view value) noexcept { + for (unsigned char c : value) { + if (c > 0x7fU) return false; + } + return true; +} + +bool HasOnlyWhitespaceRemainder(BIO* bio) noexcept { + std::array bytes{}; + int count = 0; + while ((count = BIO_read(bio, bytes.data(), static_cast(bytes.size()))) > 0) { + for (int i = 0; i < count; ++i) { + if (!IsAsciiWhitespace(static_cast(bytes[static_cast(i)]))) { + return false; + } + } + } + return count == 0; +} + +DigestResult LeafPemDigest(std::string_view pem, Sha256Digest* digest) { + if (digest == nullptr || pem.empty() || + pem.size() > CertificateRegistry::kMaxCertificatePemBytes || + pem.find('\0') != std::string_view::npos || + pem.size() > static_cast(std::numeric_limits::max())) { + return DigestResult::InvalidPem; + } + + constexpr std::string_view kBeginCertificate = "-----BEGIN CERTIFICATE-----"; + std::size_t first = 0; + while (first < pem.size() && IsAsciiWhitespace(static_cast(pem[first]))) { + ++first; + } + if (pem.substr(first, kBeginCertificate.size()) != kBeginCertificate) { + return DigestResult::InvalidPem; + } + + const std::size_t length = pem.size() - first; + BIO* raw_bio = BIO_new_mem_buf(pem.data() + first, static_cast(length)); + if (raw_bio == nullptr) return DigestResult::CryptoFailure; + std::unique_ptr bio(raw_bio, &BIO_free); + X509* raw_certificate = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (raw_certificate == nullptr) return DigestResult::InvalidPem; + std::unique_ptr certificate(raw_certificate, &X509_free); + if (!HasOnlyWhitespaceRemainder(bio.get())) return DigestResult::InvalidPem; + + const int der_size = i2d_X509(certificate.get(), nullptr); + if (der_size <= 0) return DigestResult::CryptoFailure; + if (der_size > static_cast(CertificateRegistry::kMaxCertificatePemBytes)) { + return DigestResult::InvalidPem; + } + std::vector der(static_cast(der_size)); + unsigned char* cursor = der.data(); + if (i2d_X509(certificate.get(), &cursor) != der_size) return DigestResult::CryptoFailure; + + unsigned int digest_size = 0; + if (EVP_Digest(der.data(), der.size(), digest->data(), &digest_size, + EVP_sha256(), nullptr) != 1 || digest_size != digest->size()) { + return DigestResult::CryptoFailure; + } + return DigestResult::Success; +} + +template +bool ExactlyOne(const std::vector& values) noexcept { + return values.size() == 1; +} + +} // namespace + +std::variant PeerAuthenticator::Authenticate( + const grpc::AuthContext& auth_context) const noexcept { + try { + if (!registry_) { + return Failure(PeerAuthFailureReason::NullRegistry, + PeerAuthDisposition::ApplicationUnavailable); + } + if (!auth_context.IsPeerAuthenticated()) { + return Failure(PeerAuthFailureReason::UnauthenticatedContext, + PeerAuthDisposition::Unauthenticated); + } + + const auto transports = auth_context.FindPropertyValues( + GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME); + if (!ExactlyOne(transports)) { + return Failure(PeerAuthFailureReason::MissingOrAmbiguousTransport, + PeerAuthDisposition::Unauthenticated); + } + if (transports.front().data() == nullptr) { + return Failure(PeerAuthFailureReason::UnsupportedTransport, + PeerAuthDisposition::Unauthenticated); + } + const std::string_view transport(transports.front().data(), transports.front().size()); + if (transport != GRPC_TLS_TRANSPORT_SECURITY_TYPE) { + return Failure(PeerAuthFailureReason::UnsupportedTransport, + PeerAuthDisposition::Unauthenticated); + } + + const auto uris = auth_context.FindPropertyValues(GRPC_PEER_URI_PROPERTY_NAME); + if (!ExactlyOne(uris)) { + return Failure(PeerAuthFailureReason::MissingOrAmbiguousUri, + PeerAuthDisposition::Unauthenticated); + } + if (uris.front().data() == nullptr) { + return Failure(PeerAuthFailureReason::InvalidUri, + PeerAuthDisposition::Unauthenticated); + } + const std::string_view uri(uris.front().data(), uris.front().size()); + if (uri.empty() || uri.size() > 256 || uri.find('\0') != std::string_view::npos || + !IsAscii(uri)) { + return Failure(PeerAuthFailureReason::InvalidUri, + PeerAuthDisposition::Unauthenticated); + } + + const auto leaves = auth_context.FindPropertyValues(GRPC_X509_PEM_CERT_PROPERTY_NAME); + if (!ExactlyOne(leaves)) { + return Failure(PeerAuthFailureReason::MissingOrAmbiguousLeaf, + PeerAuthDisposition::Unauthenticated); + } + if (leaves.front().data() == nullptr) { + return Failure(PeerAuthFailureReason::InvalidLeafPem, + PeerAuthDisposition::Unauthenticated); + } + const std::string_view leaf_pem(leaves.front().data(), leaves.front().size()); + if (leaf_pem.size() > CertificateRegistry::kMaxCertificatePemBytes) { + return Failure(PeerAuthFailureReason::OversizedLeaf, + PeerAuthDisposition::Unauthenticated); + } + + const RegisteredCertificate* registered = registry_->Find(uri); + if (registered == nullptr) { + return Failure(PeerAuthFailureReason::UnregisteredUri, + PeerAuthDisposition::Unauthenticated); + } + + Sha256Digest presented_digest{}; + const auto digest_result = LeafPemDigest(leaf_pem, &presented_digest); + if (digest_result == DigestResult::InvalidPem) { + return Failure(PeerAuthFailureReason::InvalidLeafPem, + PeerAuthDisposition::Unauthenticated); + } + if (digest_result == DigestResult::CryptoFailure) { + return Failure(PeerAuthFailureReason::CryptoFailure, + PeerAuthDisposition::ApplicationUnavailable); + } + if (presented_digest != registered->peer.leaf_der_sha256) { + return Failure(PeerAuthFailureReason::LeafPinMismatch, + PeerAuthDisposition::Unauthenticated); + } + + if (!trusted_clock_.Healthy()) { + return Failure(PeerAuthFailureReason::ClockUntrusted, + PeerAuthDisposition::ApplicationUnavailable); + } + auto current_time = trusted_clock_.Now(); + const auto* now = std::get_if(¤t_time); + if (now == nullptr || !trusted_clock_.Healthy()) { + return Failure(PeerAuthFailureReason::ClockUntrusted, + PeerAuthDisposition::ApplicationUnavailable); + } + if (now->unix_seconds < 0 || now->nanoseconds >= 1'000'000'000U) { + return Failure(PeerAuthFailureReason::ClockUntrusted, + PeerAuthDisposition::ApplicationUnavailable); + } + if (!registry_->root_validity().Contains(*now) || + !registered->validity.Contains(*now)) { + const auto& window = !registry_->root_validity().Contains(*now) + ? registry_->root_validity() + : registered->validity; + const auto reason = *now < window.not_before + ? PeerAuthFailureReason::CertificateNotYetValid + : PeerAuthFailureReason::CertificateExpired; + return Failure(reason, PeerAuthDisposition::Unauthenticated); + } + + const AuthenticatedPeer authenticated(registry_, registered); + return std::variant( + std::in_place_index<0>, authenticated); + } catch (const std::bad_alloc&) { + return Failure(PeerAuthFailureReason::CryptoFailure, + PeerAuthDisposition::ApplicationUnavailable); + } catch (...) { + return Failure(PeerAuthFailureReason::CryptoFailure, + PeerAuthDisposition::ApplicationUnavailable); + } +} + +} // namespace rateguard::security diff --git a/src/security/pinned_peer_rpc_client.cpp b/src/security/pinned_peer_rpc_client.cpp new file mode 100644 index 0000000..e45043e --- /dev/null +++ b/src/security/pinned_peer_rpc_client.cpp @@ -0,0 +1,421 @@ +#include "rateguard/security/pinned_peer_rpc_client.h" + +#include "rateguard/security/tls_certificate_verifier.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::security { +namespace { + +constexpr std::size_t kMaxCredentialBytes = 64U * 1024U; +constexpr int kRpcMessageLimitBytes = 16 * 1024; + +using BioPtr = std::unique_ptr; +using X509Ptr = std::unique_ptr; +using PkeyPtr = std::unique_ptr; + +enum class PemReadFailure : std::uint8_t { Invalid, Crypto }; + +bool IsAsciiWhitespace(unsigned char ch) noexcept { + return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\f' || ch == '\v'; +} + +bool OnlyWhitespaceRemainder(BIO* bio) noexcept { + std::array bytes{}; + int count = 0; + while ((count = BIO_read(bio, bytes.data(), static_cast(bytes.size()))) > 0) { + for (int i = 0; i < count; ++i) { + if (!IsAsciiWhitespace(static_cast(bytes[static_cast(i)]))) + return false; + } + } + return count == 0; +} + +std::variant ReadSingleCertificate(std::string_view pem) { + constexpr std::string_view marker = "-----BEGIN CERTIFICATE-----"; + if (pem.empty() || pem.size() > kMaxCredentialBytes || + pem.size() > static_cast(std::numeric_limits::max()) || + pem.find('\0') != std::string_view::npos) return PemReadFailure::Invalid; + std::size_t first = 0; + while (first < pem.size() && IsAsciiWhitespace(static_cast(pem[first]))) ++first; + if (pem.substr(first, marker.size()) != marker) return PemReadFailure::Invalid; + BioPtr bio(BIO_new_mem_buf(pem.data() + first, static_cast(pem.size() - first)), &BIO_free); + if (!bio) return PemReadFailure::Crypto; + X509* raw = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (raw == nullptr) return PemReadFailure::Invalid; + X509Ptr certificate(raw, &X509_free); + if (!OnlyWhitespaceRemainder(bio.get())) return PemReadFailure::Invalid; + return std::variant(std::in_place_index<0>, + std::move(certificate)); +} + +std::variant ReadSinglePrivateKey(std::string_view pem) { + if (pem.empty() || pem.size() > kMaxCredentialBytes || + pem.size() > static_cast(std::numeric_limits::max()) || + pem.find('\0') != std::string_view::npos) return PemReadFailure::Invalid; + std::size_t first = 0; + while (first < pem.size() && IsAsciiWhitespace(static_cast(pem[first]))) ++first; + constexpr std::string_view private_key_marker = "-----BEGIN PRIVATE KEY-----"; + constexpr std::string_view ec_private_key_marker = "-----BEGIN EC PRIVATE KEY-----"; + if (pem.substr(first, private_key_marker.size()) != private_key_marker && + pem.substr(first, ec_private_key_marker.size()) != ec_private_key_marker) + return PemReadFailure::Invalid; + BioPtr bio(BIO_new_mem_buf(pem.data() + first, static_cast(pem.size() - first)), &BIO_free); + if (!bio) return PemReadFailure::Crypto; + // Returning zero rejects encrypted PEM without invoking an interactive + // password prompt. No parser detail or key bytes are exposed to callers. + const auto reject_password = [](char*, int, int, void*) -> int { return 0; }; + EVP_PKEY* raw = PEM_read_bio_PrivateKey(bio.get(), nullptr, reject_password, nullptr); + if (raw == nullptr) return PemReadFailure::Invalid; + PkeyPtr key(raw, &EVP_PKEY_free); + if (!OnlyWhitespaceRemainder(bio.get())) return PemReadFailure::Invalid; + return std::variant(std::in_place_index<0>, + std::move(key)); +} + +std::variant CertificateDigest(std::string_view pem) { + auto parsed = ReadSingleCertificate(pem); + auto* cert = std::get_if(&parsed); + if (cert == nullptr) return std::get(parsed); + const int size = i2d_X509(cert->get(), nullptr); + if (size <= 0) return PemReadFailure::Crypto; + if (static_cast(size) > kMaxCredentialBytes) return PemReadFailure::Invalid; + std::vector der(static_cast(size)); + unsigned char* cursor = der.data(); + if (i2d_X509(cert->get(), &cursor) != size) return PemReadFailure::Crypto; + Sha256Digest digest{}; + unsigned int actual_size = 0; + if (EVP_Digest(der.data(), der.size(), digest.data(), &actual_size, + EVP_sha256(), nullptr) != 1 || actual_size != digest.size()) + return PemReadFailure::Crypto; + return digest; +} + +bool ValidTarget(std::string_view target) noexcept { + if (target.empty() || target.size() > 256 || target.find('\0') != std::string_view::npos) + return false; + for (unsigned char ch : target) { + if (ch < 0x21 || ch > 0x7e) return false; + } + return true; +} + +bool AtMostCredentialBound(const PinnedPeerClientConfig& config) noexcept { + return config.root_certificate_pem.size() <= kMaxCredentialBytes && + config.local_certificate_pem.size() <= kMaxCredentialBytes && + config.local_private_key_pem.size() <= kMaxCredentialBytes; +} + +PinnedClientFactoryFailure FactoryFailure(PinnedClientFactoryFailureReason reason, + ClientGuardDisposition disposition = + ClientGuardDisposition::CredentialInvalid) noexcept { + return {reason, disposition}; +} + +PinnedClientCallFailure CallFailure(PinnedClientCallFailureReason reason) noexcept { + return {reason, std::nullopt}; +} + +PinnedClientCallFailure CallFailure(ClientCallGuardFailure failure) noexcept { + return {PinnedClientCallFailureReason::GuardRejected, failure}; +} + +std::optional BoundedAuthorityDeadline( + std::chrono::system_clock::time_point requested) noexcept { + const auto now = std::chrono::system_clock::now(); + if (requested == std::chrono::system_clock::time_point::max() || requested <= now) + return std::nullopt; + const auto authority_cap = now + std::chrono::milliseconds(20); + return std::min(requested, authority_cap); +} + +} // namespace + +struct PinnedPeerRpcClient::Impl final { + ClientCallPurpose purpose; + policy::Mode mode; + std::shared_ptr registry; + std::shared_ptr provider; + std::shared_ptr credentials; + std::shared_ptr channel; + std::unique_ptr admission_stub; + std::unique_ptr authority_stub; + ClientCallGuard guard; + + Impl(ClientCallPurpose purpose_arg, policy::Mode mode_arg, + std::shared_ptr registry_arg, + std::shared_ptr provider_arg, + std::shared_ptr credentials_arg, + std::shared_ptr channel_arg, ClientCallGuard guard_arg) + : purpose(purpose_arg), mode(mode_arg), registry(std::move(registry_arg)), + provider(std::move(provider_arg)), credentials(std::move(credentials_arg)), + channel(std::move(channel_arg)), guard(std::move(guard_arg)) {} +}; + +PinnedPeerRpcClient::PinnedPeerRpcClient(std::unique_ptr impl) noexcept + : impl_(std::move(impl)) {} +PinnedPeerRpcClient::PinnedPeerRpcClient(PinnedPeerRpcClient&&) noexcept = default; +PinnedPeerRpcClient& PinnedPeerRpcClient::operator=(PinnedPeerRpcClient&&) noexcept = default; +PinnedPeerRpcClient::~PinnedPeerRpcClient() = default; + +std::variant +PinnedPeerRpcClient::Create(PinnedPeerClientConfig config, + std::shared_ptr registry, + ITrustedWallClock& trusted_clock) noexcept { + if (!registry) return FactoryFailure(PinnedClientFactoryFailureReason::NullRegistry, + ClientGuardDisposition::ApplicationUnavailable); + if (!ValidTarget(config.target)) return FactoryFailure(PinnedClientFactoryFailureReason::InvalidTarget); + if (!AtMostCredentialBound(config)) + return FactoryFailure(PinnedClientFactoryFailureReason::OversizedCredential); + + try { + auto guard_result = ClientCallGuard::Create(registry, trusted_clock, config.purpose, + config.local_uri, + config.expected_server_uri); + auto* guard_value = std::get_if(&guard_result); + if (guard_value == nullptr) { + const auto& failure = std::get(guard_result); + return FactoryFailure(PinnedClientFactoryFailureReason::InvalidEndpointBinding, + failure.disposition); + } + + auto root_digest = CertificateDigest(config.root_certificate_pem); + const auto* root_hash = std::get_if(&root_digest); + if (root_hash == nullptr) { + const auto reason = std::get(root_digest) == PemReadFailure::Invalid + ? PinnedClientFactoryFailureReason::InvalidRootPem + : PinnedClientFactoryFailureReason::DependencyFailure; + return FactoryFailure(reason, reason == PinnedClientFactoryFailureReason::DependencyFailure + ? ClientGuardDisposition::ApplicationUnavailable + : ClientGuardDisposition::CredentialInvalid); + } + if (*root_hash != registry->root_der_sha256()) + return FactoryFailure(PinnedClientFactoryFailureReason::RootPinMismatch); + + auto local_digest = CertificateDigest(config.local_certificate_pem); + const auto* local_hash = std::get_if(&local_digest); + if (local_hash == nullptr) { + const auto reason = std::get(local_digest) == PemReadFailure::Invalid + ? PinnedClientFactoryFailureReason::InvalidClientCertificatePem + : PinnedClientFactoryFailureReason::DependencyFailure; + return FactoryFailure(reason, reason == PinnedClientFactoryFailureReason::DependencyFailure + ? ClientGuardDisposition::ApplicationUnavailable + : ClientGuardDisposition::CredentialInvalid); + } + const auto* local_record = registry->Find(config.local_uri); + if (local_record == nullptr || *local_hash != local_record->peer.leaf_der_sha256) + return FactoryFailure(PinnedClientFactoryFailureReason::ClientPinMismatch); + + auto certificate = ReadSingleCertificate(config.local_certificate_pem); + auto* certificate_value = std::get_if(&certificate); + if (certificate_value == nullptr) + return FactoryFailure(PinnedClientFactoryFailureReason::InvalidClientCertificatePem); + auto key = ReadSinglePrivateKey(config.local_private_key_pem); + auto* key_value = std::get_if(&key); + if (key_value == nullptr) { + const auto reason = std::get(key) == PemReadFailure::Invalid + ? PinnedClientFactoryFailureReason::InvalidPrivateKeyPem + : PinnedClientFactoryFailureReason::DependencyFailure; + return FactoryFailure(reason, reason == PinnedClientFactoryFailureReason::DependencyFailure + ? ClientGuardDisposition::ApplicationUnavailable + : ClientGuardDisposition::CredentialInvalid); + } + if (X509_check_private_key(certificate_value->get(), key_value->get()) != 1) + return FactoryFailure(PinnedClientFactoryFailureReason::PrivateKeyMismatch); + + const auto* server_record = registry->Find(config.expected_server_uri); + if (server_record == nullptr) + return FactoryFailure(PinnedClientFactoryFailureReason::InvalidEndpointBinding); + + using grpc::experimental::IdentityKeyCertPair; + using grpc::experimental::StaticDataCertificateProvider; + std::vector pairs; + pairs.push_back({config.local_private_key_pem, config.local_certificate_pem}); + auto provider = std::make_shared( + config.root_certificate_pem, pairs); + + grpc::experimental::TlsChannelCredentialsOptions options; + options.set_certificate_provider(provider); + options.watch_root_certs(); + options.watch_identity_key_cert_pairs(); + options.set_verify_server_certs(true); + options.set_check_call_host(false); + auto verifier = + grpc::experimental::ExternalCertificateVerifier::Create( + registry->peer_pins(), ExpectedPeer{server_record->peer.uri, + server_record->peer.leaf_der_sha256, + server_record->peer.role}); + if (!verifier || verifier->c_verifier() == nullptr) + return FactoryFailure(PinnedClientFactoryFailureReason::CredentialConstructionFailed, + ClientGuardDisposition::ApplicationUnavailable); + options.set_certificate_verifier(std::move(verifier)); + auto credentials = grpc::experimental::TlsCredentials(options); + if (!credentials) + return FactoryFailure(PinnedClientFactoryFailureReason::CredentialConstructionFailed, + ClientGuardDisposition::ApplicationUnavailable); + + grpc::ChannelArguments arguments; + // Per-client pool prevents accidental cross-guard channel reuse. + arguments.SetInt("grpc.use_local_subchannel_pool", 1); + // Disable transparent/configured retries and experimental hedging. + arguments.SetInt("grpc.enable_retries", 0); + arguments.SetInt("grpc.experimental.enable_hedging", 0); + arguments.SetInt("grpc.max_metadata_size", kRpcMessageLimitBytes); + arguments.SetMaxSendMessageSize(kRpcMessageLimitBytes); + arguments.SetMaxReceiveMessageSize(kRpcMessageLimitBytes); + // Deliberately do not attach grpc_ssl_session_cache: this factory does not + // opt in to gRPC's client session-cache resumption path. Reconnect behavior + // remains a separate SEC-11 qualification; no resumption pass is claimed. + auto channel = grpc::CreateCustomChannel(config.target, credentials, arguments); + if (!channel) + return FactoryFailure(PinnedClientFactoryFailureReason::ChannelConstructionFailed, + ClientGuardDisposition::ApplicationUnavailable); + + const auto mode = registry->policy().mode(); + auto impl = std::make_unique(config.purpose, mode, + std::move(registry), std::move(provider), std::move(credentials), + channel, *guard_value); + if (config.purpose == ClientCallPurpose::AdapterToReplicaAdmission) + impl->admission_stub = rateguard::v1::AdmissionService::NewStub(channel); + else + impl->authority_stub = rateguard::v1::AuthorityService::NewStub(channel); + if ((!impl->admission_stub && config.purpose == ClientCallPurpose::AdapterToReplicaAdmission) || + (!impl->authority_stub && config.purpose == ClientCallPurpose::ReplicaToAuthority)) + return FactoryFailure(PinnedClientFactoryFailureReason::StubConstructionFailed, + ClientGuardDisposition::ApplicationUnavailable); + return PinnedPeerRpcClient(std::move(impl)); + } catch (...) { + return FactoryFailure(PinnedClientFactoryFailureReason::DependencyFailure, + ClientGuardDisposition::ApplicationUnavailable); + } +} + +template +PinnedClientCallResult PinnedPeerRpcClient::InvokeOnce( + std::chrono::system_clock::time_point deadline, RpcCall&& rpc_call) noexcept { + if (!impl_) return NotSent{CallFailure(PinnedClientCallFailureReason::LocalAllocationFailure)}; + if (deadline == std::chrono::system_clock::time_point::max() || + deadline <= std::chrono::system_clock::now()) + return NotSent{CallFailure(PinnedClientCallFailureReason::InvalidDeadline)}; + auto guarded = impl_->guard.ValidateBeforeCall(); + auto* proof = std::get_if(&guarded); + if (proof == nullptr) return NotSent{CallFailure(std::get(guarded))}; + + // Allocate the response/proof bundle before the call. Once the stub is + // entered, returning an Invoked value cannot allocate or lose its proof. + std::shared_ptr::Payload> payload; + try { + payload = std::make_shared::Payload>(*proof); + } catch (...) { + return NotSent{CallFailure(PinnedClientCallFailureReason::LocalAllocationFailure)}; + } + + bool invoked = false; + try { + grpc::ClientContext context; + context.set_deadline(deadline); + invoked = true; + auto status = rpc_call(&context, &payload->response); + payload->transport_status.emplace(std::move(status)); + } catch (...) { + if (!invoked) + return NotSent{CallFailure(PinnedClientCallFailureReason::LocalAllocationFailure)}; + // The stub has been entered. A local exception cannot establish whether + // the remote operation committed; retain Invoked with no raw status. + } + std::shared_ptr::Payload> immutable_payload = + std::move(payload); + return Invoked(std::move(immutable_payload)); +} + +PinnedClientCallResult +PinnedPeerRpcClient::CheckAdmission( + const rateguard::v1::CheckAdmissionRequest& request, + std::chrono::system_clock::time_point deadline) noexcept { + if (!impl_ || impl_->purpose != ClientCallPurpose::AdapterToReplicaAdmission) + return NotSent{CallFailure(PinnedClientCallFailureReason::PurposeMethodMismatch)}; + if (request.ByteSizeLong() > static_cast(kRpcMessageLimitBytes)) + return NotSent{CallFailure(PinnedClientCallFailureReason::OversizedRequest)}; + if (!impl_->admission_stub) + return NotSent{CallFailure(PinnedClientCallFailureReason::LocalAllocationFailure)}; + return InvokeOnce(deadline, + [&](grpc::ClientContext* context, rateguard::v1::AdmissionDecision* response) { + return impl_->admission_stub->CheckAdmission(context, request, response); + }); +} + +PinnedClientCallResult +PinnedPeerRpcClient::StrictCheck( + const rateguard::v1::CheckAdmissionRequest& request, + std::chrono::system_clock::time_point deadline) noexcept { + if (!impl_ || impl_->purpose != ClientCallPurpose::ReplicaToAuthority) + return NotSent{CallFailure(PinnedClientCallFailureReason::PurposeMethodMismatch)}; + if (impl_->mode != policy::Mode::Strict) + return NotSent{CallFailure(PinnedClientCallFailureReason::PolicyModeMismatch)}; + if (request.ByteSizeLong() > static_cast(kRpcMessageLimitBytes)) + return NotSent{CallFailure(PinnedClientCallFailureReason::OversizedRequest)}; + if (!impl_->authority_stub) + return NotSent{CallFailure(PinnedClientCallFailureReason::LocalAllocationFailure)}; + const auto bounded_deadline = BoundedAuthorityDeadline(deadline); + if (!bounded_deadline) + return NotSent{CallFailure(PinnedClientCallFailureReason::InvalidDeadline)}; + return InvokeOnce(*bounded_deadline, + [&](grpc::ClientContext* context, rateguard::v1::AdmissionDecision* response) { + return impl_->authority_stub->StrictCheck(context, request, response); + }); +} + +PinnedClientCallResult +PinnedPeerRpcClient::AcquireCredit( + const rateguard::v1::AcquireCreditRequest& request, + std::chrono::system_clock::time_point deadline) noexcept { + if (!impl_ || impl_->purpose != ClientCallPurpose::ReplicaToAuthority) + return NotSent{CallFailure(PinnedClientCallFailureReason::PurposeMethodMismatch)}; + if (impl_->mode != policy::Mode::Credit) + return NotSent{CallFailure(PinnedClientCallFailureReason::PolicyModeMismatch)}; + if (request.ByteSizeLong() > static_cast(kRpcMessageLimitBytes)) + return NotSent{CallFailure(PinnedClientCallFailureReason::OversizedRequest)}; + if (!impl_->authority_stub) + return NotSent{CallFailure(PinnedClientCallFailureReason::LocalAllocationFailure)}; + const auto bounded_deadline = BoundedAuthorityDeadline(deadline); + if (!bounded_deadline) + return NotSent{CallFailure(PinnedClientCallFailureReason::InvalidDeadline)}; + return InvokeOnce(*bounded_deadline, + [&](grpc::ClientContext* context, rateguard::v1::AcquireCreditResponse* response) { + return impl_->authority_stub->AcquireCredit(context, request, response); + }); +} + +std::variant +PinnedPeerRpcClient::ValidateBeforeForward( + const Invoked& invocation) const noexcept { + if (!impl_ || impl_->purpose != ClientCallPurpose::AdapterToReplicaAdmission) { + return ClientCallGuardFailure{ClientGuardFailureReason::ForeignPreparedCall, + ClientGuardDisposition::CredentialInvalid}; + } + return impl_->guard.ValidateBeforeForward(invocation.payload_->proof); +} + +} // namespace rateguard::security diff --git a/src/security/tls_certificate_verifier.cpp b/src/security/tls_certificate_verifier.cpp new file mode 100644 index 0000000..5de6e83 --- /dev/null +++ b/src/security/tls_certificate_verifier.cpp @@ -0,0 +1,104 @@ +#include "rateguard/security/tls_certificate_verifier.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace rateguard::security { +namespace { + +grpc::Status Reject(const char* why) { + return {grpc::StatusCode::UNAUTHENTICATED, why}; +} + +bool LeafDigest(std::string_view pem, Sha256Digest* out) { + if (pem.empty() || pem.size() > 64 * 1024 || out == nullptr) return false; + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (raw_bio == nullptr) return false; + std::unique_ptr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (raw_cert == nullptr) return false; + std::unique_ptr cert(raw_cert, X509_free); + char trailing[256]; + for (;;) { + const int n = BIO_read(bio.get(), trailing, sizeof(trailing)); + if (n <= 0) break; + for (int i = 0; i < n; ++i) { + const unsigned char c = static_cast(trailing[i]); + if (c != ' ' && c != '\t' && c != '\r' && c != '\n') return false; + } + } + const int der_size = i2d_X509(cert.get(), nullptr); + if (der_size <= 0 || der_size > 64 * 1024) return false; + std::string der(static_cast(der_size), '\0'); + unsigned char* cursor = reinterpret_cast(der.data()); + if (i2d_X509(cert.get(), &cursor) != der_size) return false; + unsigned int digest_size = 0; + return EVP_Digest(der.data(), der.size(), out->data(), &digest_size, + EVP_sha256(), nullptr) == 1 && digest_size == out->size(); +} + +bool HasNul(grpc::string_ref value) { + return std::memchr(value.data(), '\0', value.size()) != nullptr; +} + +} // namespace + +PeerRegistry::PeerRegistry(std::vector records) { + if (records.empty() || records.size() > 10000) { valid_ = false; return; } + for (auto& record : records) { + const bool valid_role = record.role == PeerRole::kAdapter || + record.role == PeerRole::kReplica || + record.role == PeerRole::kAuthority; + if (record.uri.empty() || record.uri.size() > 256 || + record.uri.find('\0') != std::string::npos || !valid_role || + !records_.emplace(record.uri, record).second) { + valid_ = false; + records_.clear(); + return; + } + } +} + +const RegisteredPeer* PeerRegistry::Find(std::string_view exact_uri) const noexcept { + auto it = records_.find(exact_uri); + return it == records_.end() ? nullptr : &it->second; +} + +PinnedPeerVerifier::PinnedPeerVerifier(std::shared_ptr registry, + std::optional expected) + : registry_(std::move(registry)), expected_(std::move(expected)) {} + +bool PinnedPeerVerifier::Verify( + grpc::experimental::TlsCustomVerificationCheckRequest* request, + std::function, grpc::Status* sync_status) { + if (sync_status == nullptr) std::abort(); + *sync_status = Reject("peer certificate identity rejected"); + if (request == nullptr || !registry_ || !registry_->valid()) return true; + const auto uris = request->uri_names(); + if (uris.size() != 1 || uris[0].empty() || HasNul(uris[0])) return true; + const std::string_view uri(uris[0].data(), uris[0].size()); + const RegisteredPeer* record = registry_->Find(uri); + if (record == nullptr) return true; + Sha256Digest digest{}; + const auto pem = request->peer_cert(); + if (!LeafDigest(std::string_view(pem.data(), pem.size()), &digest)) return true; + if (expected_) { + if (uri != expected_->exact_uri || digest != expected_->leaf_der_sha256 || + record->role != expected_->role || + record->leaf_der_sha256 != expected_->leaf_der_sha256) return true; + } else if (digest != record->leaf_der_sha256) { + return true; + } + *sync_status = grpc::Status::OK; + return true; +} + +} // namespace rateguard::security diff --git a/src/security/trusted_wall_clock.cpp b/src/security/trusted_wall_clock.cpp new file mode 100644 index 0000000..f7cd349 --- /dev/null +++ b/src/security/trusted_wall_clock.cpp @@ -0,0 +1,179 @@ +#include "security/trusted_wall_clock.h" + +#include +#include +#include + +#if defined(__linux__) +#include +#endif + +namespace rateguard::security { +namespace { +using rateguard::v1::contract::ErrorCategory; +using rateguard::v1::contract::ErrorCode; +using rateguard::v1::contract::RetryDisposition; + +constexpr std::uint64_t kStaUnsync = 0x0040ULL; +constexpr std::uint64_t kStaClockError = 0x1000ULL; +constexpr std::int32_t kTimeOk = 0; +constexpr std::int32_t kTimeInsert = 1; +constexpr std::int32_t kTimeDelete = 2; +constexpr std::int32_t kTimeOops = 3; +constexpr std::int32_t kTimeWait = 4; +constexpr std::int32_t kTimeError = 5; +constexpr std::int64_t kMaxNanoseconds = 999'999'999; + +TrustedWallClockFailure Failure(TrustedWallClockFailureReason reason) { + return {reason}; +} + +std::optional CheckSynchronization( + SynchronizationStatus status) { + switch (status.state) { + case kTimeOk: + case kTimeInsert: + case kTimeDelete: + case kTimeOops: + case kTimeWait: + break; + case kTimeError: + return TrustedWallClockFailureReason::TimeErrorState; + default: + return TrustedWallClockFailureReason::UnknownState; + } + if ((status.flags & kStaUnsync) != 0) + return TrustedWallClockFailureReason::UnsynchronizedFlag; + if ((status.flags & kStaClockError) != 0) + return TrustedWallClockFailureReason::ClockErrorFlag; + return std::nullopt; +} + +} // namespace + +rateguard::v1::contract::ServiceError TrustedWallClockFailure::ToServiceError( + rateguard::v1::contract::Commitment phase_commitment) const noexcept { + return {ErrorCategory::Dependency, ErrorCode::Unavailable, + RetryDisposition::Never, phase_commitment}; +} + +TrustedWallClock::TrustedWallClock( + std::unique_ptr platform) + : platform_(std::move(platform)), + failure_(Failure(TrustedWallClockFailureReason::LatchedFailure)) {} + +TrustedWallClockResult> +TrustedWallClock::Create(std::unique_ptr platform) { + if (!platform) + return Failure(TrustedWallClockFailureReason::PlatformUnavailable); + auto clock = std::unique_ptr( + new TrustedWallClock(std::move(platform))); + auto initial_sample = clock->Now(); + if (const auto* failure = std::get_if(&initial_sample)) + return *failure; + return clock; +} + +TrustedWallClockFailure TrustedWallClock::Latch( + TrustedWallClockFailureReason reason) { + if (!failed_) { + failed_ = true; + healthy_ = false; + failure_ = Failure(reason); + } + return failure_; +} + +TrustedWallClockFailure TrustedWallClock::CurrentFailure() const { + return failure_; +} + +TrustedWallClockResult TrustedWallClock::Now() { + std::lock_guard lock(mutex_); + if (failed_) return CurrentFailure(); + + auto synchronization = platform_->ReadSynchronization(); + if (const auto* error = std::get_if(&synchronization)) + return Latch(error->reason); + if (const auto problem = CheckSynchronization( + std::get(synchronization))) + return Latch(*problem); + + auto realtime = platform_->ReadRealtime(); + if (const auto* error = std::get_if(&realtime)) + return Latch(error->reason); + const RawWallTime raw = std::get(realtime); + if (raw.seconds < 0) return Latch(TrustedWallClockFailureReason::InvalidSeconds); + if (raw.nanoseconds < 0 || raw.nanoseconds > kMaxNanoseconds) + return Latch(TrustedWallClockFailureReason::InvalidNanoseconds); + + const WallTime sample{raw.seconds, static_cast(raw.nanoseconds)}; + if (last_sample_ && sample < *last_sample_) + return Latch(TrustedWallClockFailureReason::BackwardsRead); + last_sample_ = sample; + healthy_ = true; + return sample; +} + +bool TrustedWallClock::Healthy() const { + std::lock_guard lock(mutex_); + return healthy_ && !failed_; +} + +TrustedWallClockResult +NativeTrustedWallClockPlatform::ReadSynchronization() { +#if defined(__linux__) + struct timex query {}; + query.modes = 0; // Read-only query; never adjust kernel time or require CAP_SYS_TIME. + const int state = ::adjtimex(&query); + if (state < 0) return Failure(TrustedWallClockFailureReason::SynchronizationSyscall); + return SynchronizationStatus{state, + static_cast( + static_cast(query.status))}; +#else + return Failure(TrustedWallClockFailureReason::PlatformUnavailable); +#endif +} + +TrustedWallClockResult +NativeTrustedWallClockPlatform::ReadRealtime() { +#if defined(__linux__) + struct timespec reading {}; + if (::clock_gettime(CLOCK_REALTIME, &reading) != 0) + return Failure(TrustedWallClockFailureReason::RealtimeSyscall); + return RawWallTime{static_cast(reading.tv_sec), + static_cast(reading.tv_nsec)}; +#else + return Failure(TrustedWallClockFailureReason::PlatformUnavailable); +#endif +} + +const char* FailureReasonName(TrustedWallClockFailureReason reason) noexcept { + switch (reason) { + case TrustedWallClockFailureReason::SynchronizationSyscall: + return "synchronization_syscall"; + case TrustedWallClockFailureReason::RealtimeSyscall: + return "realtime_syscall"; + case TrustedWallClockFailureReason::PlatformUnavailable: + return "platform_unavailable"; + case TrustedWallClockFailureReason::TimeErrorState: + return "time_error_state"; + case TrustedWallClockFailureReason::UnknownState: + return "unknown_sync_state"; + case TrustedWallClockFailureReason::UnsynchronizedFlag: + return "sta_unsync"; + case TrustedWallClockFailureReason::ClockErrorFlag: + return "sta_clockerr"; + case TrustedWallClockFailureReason::InvalidSeconds: + return "invalid_seconds"; + case TrustedWallClockFailureReason::InvalidNanoseconds: + return "invalid_nanoseconds"; + case TrustedWallClockFailureReason::BackwardsRead: + return "backwards_read"; + case TrustedWallClockFailureReason::LatchedFailure: + return "latched_failure"; + } + return "unknown_failure"; +} + +} // namespace rateguard::security diff --git a/src/security/trusted_wall_clock.h b/src/security/trusted_wall_clock.h new file mode 100644 index 0000000..c6b11b2 --- /dev/null +++ b/src/security/trusted_wall_clock.h @@ -0,0 +1,109 @@ +#pragma once + +#include "rateguard/v1/error_contract.h" + +#include +#include +#include +#include +#include + +namespace rateguard::security { + +struct WallTime { + std::int64_t unix_seconds; + std::uint32_t nanoseconds; + friend constexpr bool operator==(WallTime, WallTime) = default; + friend constexpr bool operator<(WallTime lhs, WallTime rhs) noexcept { + return lhs.unix_seconds < rhs.unix_seconds || + (lhs.unix_seconds == rhs.unix_seconds && + lhs.nanoseconds < rhs.nanoseconds); + } +}; + +struct SynchronizationStatus { + std::int32_t state; + std::uint64_t flags; +}; + +struct RawWallTime { + std::int64_t seconds; + std::int64_t nanoseconds; +}; + +enum class TrustedWallClockFailureReason : std::uint8_t { + SynchronizationSyscall, + RealtimeSyscall, + PlatformUnavailable, + TimeErrorState, + UnknownState, + UnsynchronizedFlag, + ClockErrorFlag, + InvalidSeconds, + InvalidNanoseconds, + BackwardsRead, + LatchedFailure, +}; + +struct TrustedWallClockFailure { + TrustedWallClockFailureReason reason; + + // The clock cannot infer whether its caller has committed quota or may + // already have returned ALLOW. The operation layer supplies that phase. + [[nodiscard]] rateguard::v1::contract::ServiceError ToServiceError( + rateguard::v1::contract::Commitment phase_commitment) const noexcept; +}; + +template +using TrustedWallClockResult = std::variant; + +class ITrustedWallClock { + public: + virtual ~ITrustedWallClock() = default; + [[nodiscard]] virtual TrustedWallClockResult Now() = 0; + [[nodiscard]] virtual bool Healthy() const = 0; +}; + +class ITrustedWallClockPlatform { + public: + virtual ~ITrustedWallClockPlatform() = default; + // Read-only synchronization query. Implementations must not change clock state. + [[nodiscard]] virtual TrustedWallClockResult + ReadSynchronization() = 0; + [[nodiscard]] virtual TrustedWallClockResult ReadRealtime() = 0; +}; + +class NativeTrustedWallClockPlatform final : public ITrustedWallClockPlatform { + public: + [[nodiscard]] TrustedWallClockResult + ReadSynchronization() override; + [[nodiscard]] TrustedWallClockResult ReadRealtime() override; +}; + +class TrustedWallClock final : public ITrustedWallClock { + public: + [[nodiscard]] static TrustedWallClockResult> + Create(std::unique_ptr platform); + + [[nodiscard]] TrustedWallClockResult Now() override; + [[nodiscard]] bool Healthy() const override; + + private: + explicit TrustedWallClock(std::unique_ptr platform); + [[nodiscard]] TrustedWallClockFailure Latch( + TrustedWallClockFailureReason reason); + [[nodiscard]] TrustedWallClockFailure CurrentFailure() const; + + std::unique_ptr platform_; + mutable std::mutex mutex_; + bool healthy_{false}; + bool failed_{false}; + std::optional last_sample_; + TrustedWallClockFailure failure_; +}; + +// Names are stable diagnostic labels for bounded probe JSON; no raw diagnostics. +[[nodiscard]] const char* FailureReasonName( + TrustedWallClockFailureReason reason) noexcept; + +} // namespace rateguard::security diff --git a/src/supervisor/bootstrap_inventory.cpp b/src/supervisor/bootstrap_inventory.cpp new file mode 100644 index 0000000..b776b7c --- /dev/null +++ b/src/supervisor/bootstrap_inventory.cpp @@ -0,0 +1,516 @@ +#include "supervisor/bootstrap_inventory.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +struct BootstrapCodecAccess { + static BootstrapInventory Make(std::array domain, std::uint64_t revision, + EpochId epoch, IncarnationId authority, PolicyDigest digest, + platform::ClockIdentity clock, + std::shared_ptr> records, + bool recovery, BootstrapError reason) noexcept { + return BootstrapInventory(domain, revision, epoch, authority, digest, clock, + std::move(records), recovery, reason); + } +}; + +namespace { +using Json = nlohmann::json; +constexpr std::uint32_t kNanosPerSecond = 1'000'000'000U; +constexpr std::int32_t kClockMonotonic = 1; +constexpr std::size_t kMaxDepth = 6; + +struct Failure { BootstrapError error; }; +[[noreturn]] void Fail(BootstrapError error) { throw Failure{error}; } + +bool AllZero(const auto& bytes) noexcept { + return std::all_of(bytes.begin(), bytes.end(), [](std::uint8_t byte) { return byte == 0; }); +} + +bool ValidClock(const platform::ClockIdentity& c) noexcept { + return !AllZero(c.boot_uuid) && c.namespace_device != 0 && c.namespace_inode != 0 && + c.clock_id == kClockMonotonic && c.monotonic_offset_nanoseconds < kNanosPerSecond && + c.boottime_offset_nanoseconds < kNanosPerSecond; +} + +bool ValidParticipantId(std::string_view id) noexcept { + if (id.empty() || id.size() > 64) return false; + for (unsigned char c : id) + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_')) return false; + return true; +} + +bool ValidContainerId(std::string_view id) noexcept { + if (id.size() != 64) return false; + for (unsigned char c : id) + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; + return true; +} + +bool PlannedRosterValid(const BootstrapPlan& plan) { + if (AllZero(plan.domain_id) || AllZero(plan.epoch_id) || AllZero(plan.authority_incarnation) || AllZero(plan.policy_digest) || + !ValidClock(plan.expected_clock_identity) || plan.participants.empty() || + plan.participants.size() > kMaxParticipants) return false; + std::size_t authorities = 0, replicas = 0, adapters = 0, witnesses = 0; + std::set> ids; + std::set containers; + std::set replica_slots; + for (const auto& p : plan.participants) { + if (!ValidParticipantId(p.participant_id) || !ValidContainerId(p.container_id) || + AllZero(p.incarnation) || !ids.emplace(static_cast(p.role), p.participant_id).second || + !containers.insert(p.container_id).second) return false; + switch (p.role) { + case ParticipantRole::Authority: + ++authorities; + if (p.slot_id != 0 || p.incarnation != plan.authority_incarnation) return false; + break; + case ParticipantRole::Replica: + ++replicas; + if (!replica_slots.insert(p.slot_id).second) return false; + break; + case ParticipantRole::Adapter: + ++adapters; + if (p.slot_id != 0) return false; + break; + case ParticipantRole::Witness: + ++witnesses; + if (p.slot_id != 0) return false; + break; + default: return false; + } + } + return authorities == 1 && witnesses == 1 && adapters > 0 && replicas > 0 && replicas <= kMaxReplicaSlots; +} + +bool ValidBootstrapError(BootstrapError error) noexcept { + return static_cast(error) <= static_cast(BootstrapError::RevisionExhausted); +} + +class JsonGuard final : public nlohmann::json_sax { + public: + using string_t = Json::string_t; + using binary_t = Json::binary_t; + using number_integer_t = Json::number_integer_t; + using number_unsigned_t = Json::number_unsigned_t; + using number_float_t = Json::number_float_t; + bool null() override { return true; } + bool boolean(bool) override { return true; } + bool number_integer(number_integer_t) override { return true; } + bool number_unsigned(number_unsigned_t) override { return true; } + bool number_float(number_float_t, const string_t&) override { return Reject(BootstrapError::InvalidEncoding); } + bool string(string_t&) override { return true; } + bool binary(binary_t&) override { return Reject(BootstrapError::InvalidEncoding); } + bool start_object(std::size_t) override { + if (stack_.size() >= kMaxDepth) return Reject(BootstrapError::InvalidEncoding); + stack_.push_back(Frame{true, {}}); return true; + } + bool key(string_t& key) override { + if (stack_.empty() || !stack_.back().object) return Reject(BootstrapError::InvalidEncoding); + if (!stack_.back().keys.insert(key).second) return Reject(BootstrapError::DuplicateKey); + return true; + } + bool end_object() override { + if (stack_.empty() || !stack_.back().object) return Reject(BootstrapError::InvalidEncoding); + stack_.pop_back(); return true; + } + bool start_array(std::size_t) override { + if (stack_.size() >= kMaxDepth) return Reject(BootstrapError::InvalidEncoding); + stack_.push_back(Frame{false, {}}); return true; + } + bool end_array() override { + if (stack_.empty() || stack_.back().object) return Reject(BootstrapError::InvalidEncoding); + stack_.pop_back(); return true; + } + bool parse_error(std::size_t, const std::string&, const nlohmann::detail::exception&) override { + if (!error_) error_ = BootstrapError::InvalidEncoding; + return false; + } + [[nodiscard]] BootstrapError error() const noexcept { return error_.value_or(BootstrapError::InvalidEncoding); } + private: + struct Frame { bool object; std::set> keys; }; + bool Reject(BootstrapError e) { if (!error_) error_ = e; return false; } + std::vector stack_; + std::optional error_; +}; + +void CheckKeys(const Json& value, std::initializer_list required) { + if (!value.is_object()) Fail(BootstrapError::InvalidEncoding); + for (const auto& item : value.items()) + if (std::find(required.begin(), required.end(), std::string_view(item.key())) == required.end()) + Fail(BootstrapError::UnknownKey); + for (auto key : required) if (!value.contains(std::string(key))) Fail(BootstrapError::MissingKey); +} + +std::string Hex(const auto& bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string result(bytes.size() * 2, '0'); + for (std::size_t i = 0; i < bytes.size(); ++i) { + result[2 * i] = digits[bytes[i] >> 4]; result[2 * i + 1] = digits[bytes[i] & 15]; + } + return result; +} + +template std::array ParseHex(const Json& value) { + if (!value.is_string()) Fail(BootstrapError::InvalidEncoding); + const auto text = value.get(); + if (text.size() != N * 2) Fail(BootstrapError::InvalidEncoding); + auto nibble = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return -1; + }; + std::array result{}; + for (std::size_t i = 0; i < N; ++i) { + int hi = nibble(text[2 * i]), lo = nibble(text[2 * i + 1]); + if (hi < 0 || lo < 0) Fail(BootstrapError::InvalidEncoding); + result[i] = static_cast((hi << 4) | lo); + } + return result; +} + +std::string U64(std::uint64_t value) { return std::to_string(value); } +std::string I64(std::int64_t value) { return std::to_string(value); } +std::uint64_t ParseU64(const Json& value) { + if (!value.is_string()) Fail(BootstrapError::InvalidEncoding); + const auto text = value.get(); + if (text.empty() || (text.size() > 1 && text.front() == '0')) Fail(BootstrapError::InvalidEncoding); + for (unsigned char c : text) if (c < '0' || c > '9') Fail(BootstrapError::InvalidEncoding); + std::uint64_t out{}; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), out); + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) Fail(BootstrapError::InvalidEncoding); + return out; +} +std::int64_t ParseI64(const Json& value) { + if (!value.is_string()) Fail(BootstrapError::InvalidEncoding); + const auto text = value.get(); + if (text.empty() || text == "-0" || (text.size() > 1 && text[0] == '0') || + (text.size() > 2 && text[0] == '-' && text[1] == '0')) Fail(BootstrapError::InvalidEncoding); + const std::size_t begin = text.front() == '-' ? 1 : 0; + if (begin == text.size()) Fail(BootstrapError::InvalidEncoding); + for (std::size_t i = begin; i < text.size(); ++i) + if (text[i] < '0' || text[i] > '9') Fail(BootstrapError::InvalidEncoding); + std::int64_t out{}; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), out); + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) Fail(BootstrapError::InvalidEncoding); + return out; +} +std::uint32_t U32(const Json& value) { + std::uint64_t n{}; + if (value.is_number_unsigned()) n = value.get(); + else if (value.is_number_integer()) { + const auto signed_n = value.get(); + if (signed_n < 0) Fail(BootstrapError::InvalidEncoding); + n = static_cast(signed_n); + } else Fail(BootstrapError::InvalidEncoding); + if (n > std::numeric_limits::max()) Fail(BootstrapError::InvalidEncoding); + return static_cast(n); +} +std::int32_t I32(const Json& value) { + std::int64_t n{}; + if (value.is_number_unsigned()) { + const auto u = value.get(); + if (u > static_cast(std::numeric_limits::max())) Fail(BootstrapError::InvalidEncoding); + n = static_cast(u); + } else if (value.is_number_integer()) n = value.get(); + else Fail(BootstrapError::InvalidEncoding); + if (n < std::numeric_limits::min() || n > std::numeric_limits::max()) + Fail(BootstrapError::InvalidEncoding); + return static_cast(n); +} + +const char* RoleName(ParticipantRole role) { + switch (role) { + case ParticipantRole::Authority: return "AUTHORITY"; + case ParticipantRole::Replica: return "REPLICA"; + case ParticipantRole::Adapter: return "ADAPTER"; + case ParticipantRole::Witness: return "WITNESS"; + } + Fail(BootstrapError::InvalidEncoding); +} +ParticipantRole ParseRole(const Json& value) { + if (!value.is_string()) Fail(BootstrapError::InvalidEncoding); + const auto role = value.get(); + if (role == "AUTHORITY") return ParticipantRole::Authority; + if (role == "REPLICA") return ParticipantRole::Replica; + if (role == "ADAPTER") return ParticipantRole::Adapter; + if (role == "WITNESS") return ParticipantRole::Witness; + Fail(BootstrapError::InvalidEncoding); +} + +Json ClockJson(const platform::ClockIdentity& c) { + return Json{{"boot_uuid", Hex(c.boot_uuid)}, {"boottime_offset_nanoseconds", c.boottime_offset_nanoseconds}, + {"boottime_offset_seconds", I64(c.boottime_offset_seconds)}, {"clock_id", c.clock_id}, + {"monotonic_offset_nanoseconds", c.monotonic_offset_nanoseconds}, + {"monotonic_offset_seconds", I64(c.monotonic_offset_seconds)}, + {"namespace_device", U64(c.namespace_device)}, {"namespace_inode", U64(c.namespace_inode)}}; +} +platform::ClockIdentity ParseClock(const Json& j) { + CheckKeys(j, {"boot_uuid", "boottime_offset_nanoseconds", "boottime_offset_seconds", "clock_id", + "monotonic_offset_nanoseconds", "monotonic_offset_seconds", "namespace_device", "namespace_inode"}); + platform::ClockIdentity c{}; + c.boot_uuid = ParseHex<16>(j.at("boot_uuid")); c.namespace_device = ParseU64(j.at("namespace_device")); + c.namespace_inode = ParseU64(j.at("namespace_inode")); + c.monotonic_offset_seconds = ParseI64(j.at("monotonic_offset_seconds")); + c.monotonic_offset_nanoseconds = U32(j.at("monotonic_offset_nanoseconds")); + c.boottime_offset_seconds = ParseI64(j.at("boottime_offset_seconds")); + c.boottime_offset_nanoseconds = U32(j.at("boottime_offset_nanoseconds")); c.clock_id = I32(j.at("clock_id")); + if (!ValidClock(c)) Fail(BootstrapError::InvalidEncoding); + return c; +} + +Json RecordJson(const BootstrapRecord& r) { + Json process = nullptr; + Json clock = nullptr; + if (r.identity_recorded) { + process = Json{{"pid", U64(r.pid)}, {"pid_start_ticks", U64(r.pid_start_ticks)}}; + clock = ClockJson(r.clock_identity); + } + return Json{{"clock_identity", std::move(clock)}, {"container_id", r.planned.container_id}, + {"identity_recorded", r.identity_recorded}, {"incarnation", Hex(r.planned.incarnation)}, + {"participant_id", r.planned.participant_id}, {"process", std::move(process)}, + {"role", RoleName(r.planned.role)}, {"slot_id", r.planned.slot_id}}; +} + +Json PayloadJson(const BootstrapInventory& i) { + Json rows = Json::array(); + for (const auto& record : i.records()) rows.push_back(RecordJson(record)); + return Json{{"authority_incarnation", Hex(i.authority_incarnation())}, + {"domain_id", Hex(i.domain_id())}, + {"epoch_id", Hex(i.epoch_id())}, {"expected_clock_identity", ClockJson(i.expected_clock_identity())}, + {"participants", std::move(rows)}, {"policy_digest", Hex(i.policy_digest())}, + {"recovery_reason", static_cast(i.recovery_reason())}, + {"recovery_required", i.recovery_required()}, {"revision", U64(i.revision())}, {"schema_version", 1}}; +} + +std::array Sha256(std::string_view text) { + std::array out{}; unsigned int length = 0; + if (EVP_Digest(text.data(), text.size(), out.data(), &length, EVP_sha256(), nullptr) != 1 || length != out.size()) + Fail(BootstrapError::DigestFailure); + return out; +} + +Json ParseJson(std::string_view text) { + JsonGuard guard; + if (!Json::sax_parse(text.begin(), text.end(), &guard)) Fail(guard.error()); + try { return Json::parse(text); } catch (...) { Fail(BootstrapError::InvalidEncoding); } +} + +BootstrapInventory ParsePayload(const Json& j) { + CheckKeys(j, {"authority_incarnation", "domain_id", "epoch_id", "expected_clock_identity", "participants", "policy_digest", + "recovery_reason", "recovery_required", "revision", "schema_version"}); + const auto& version = j.at("schema_version"); + bool v1 = version.is_number_unsigned() ? version.get() == 1 + : version.is_number_integer() && version.get() == 1; + if (!v1) Fail(BootstrapError::UnsupportedSchema); + const auto& recovery = j.at("recovery_required"); + if (!recovery.is_boolean()) Fail(BootstrapError::InvalidEncoding); + const auto reason_num = U32(j.at("recovery_reason")); + if (reason_num > static_cast(BootstrapError::RevisionExhausted)) Fail(BootstrapError::InvalidEncoding); + const auto reason = static_cast(reason_num); + const bool is_recovery = recovery.get(); + if (is_recovery != (reason != BootstrapError::None)) Fail(BootstrapError::InvalidEncoding); + const auto& ps = j.at("participants"); + if (!ps.is_array() || ps.empty() || ps.size() > kMaxParticipants) Fail(BootstrapError::InvalidEncoding); + BootstrapPlan plan; + plan.domain_id = ParseHex<16>(j.at("domain_id")); + plan.epoch_id = ParseHex<16>(j.at("epoch_id")); + plan.authority_incarnation = ParseHex<16>(j.at("authority_incarnation")); + plan.policy_digest = ParseHex<32>(j.at("policy_digest")); + plan.expected_clock_identity = ParseClock(j.at("expected_clock_identity")); + std::vector records; + records.reserve(ps.size()); + for (const auto& p : ps) { + CheckKeys(p, {"clock_identity", "container_id", "identity_recorded", "incarnation", "participant_id", "process", "role", "slot_id"}); + PlannedParticipant planned; + planned.role = ParseRole(p.at("role")); planned.slot_id = U32(p.at("slot_id")); + if (!p.at("participant_id").is_string() || !p.at("container_id").is_string()) Fail(BootstrapError::InvalidEncoding); + planned.participant_id = p.at("participant_id").get(); + planned.container_id = p.at("container_id").get(); + planned.incarnation = ParseHex<16>(p.at("incarnation")); + const auto& recorded = p.at("identity_recorded"); + if (!recorded.is_boolean()) Fail(BootstrapError::InvalidEncoding); + const bool has_identity = recorded.get(); + BootstrapRecord record{planned, 0, 0, has_identity, {}}; + if (has_identity) { + CheckKeys(p.at("process"), {"pid", "pid_start_ticks"}); + record.pid = ParseU64(p.at("process").at("pid")); + record.pid_start_ticks = ParseU64(p.at("process").at("pid_start_ticks")); + record.clock_identity = ParseClock(p.at("clock_identity")); + } else if (!p.at("process").is_null() || !p.at("clock_identity").is_null()) { + Fail(BootstrapError::InvalidEncoding); + } + plan.participants.push_back(planned); + records.push_back(std::move(record)); + } + if (!PlannedRosterValid(plan)) Fail(BootstrapError::InvalidEncoding); + std::sort(records.begin(), records.end(), [](const auto& a, const auto& b) { + if (a.planned.role != b.planned.role) return static_cast(a.planned.role) < static_cast(b.planned.role); + if (a.planned.participant_id != b.planned.participant_id) return a.planned.participant_id < b.planned.participant_id; + return a.planned.slot_id < b.planned.slot_id; + }); + const auto revision = ParseU64(j.at("revision")); + if (revision == 0) Fail(BootstrapError::InvalidEncoding); + BootstrapInventory inventory = BootstrapCodecAccess::Make(plan.domain_id, revision, plan.epoch_id, plan.authority_incarnation, + plan.policy_digest, plan.expected_clock_identity, + std::make_shared>(std::move(records)), is_recovery, reason); + // Check every recorded identity against its exact plan and ensure process IDs are unique. + for (std::size_t n = 0; n < inventory.records().size(); ++n) { + const auto& r = inventory.records()[n]; + if (!r.identity_recorded) continue; + if (r.pid == 0 || r.pid_start_ticks == 0 || !(r.clock_identity == inventory.expected_clock_identity())) + Fail(BootstrapError::InvalidEncoding); + for (std::size_t k = 0; k < n; ++k) + if (inventory.records()[k].identity_recorded && inventory.records()[k].pid == r.pid) + Fail(BootstrapError::InvalidEncoding); + } + if (is_recovery && reason == BootstrapError::None) Fail(BootstrapError::InvalidEncoding); + return inventory; +} +} // namespace + +std::variant BootstrapInventory::Create(const BootstrapPlan& plan) noexcept { + try { + if (plan.participants.size() > kMaxParticipants) return BootstrapError::TooManyParticipants; + if (!PlannedRosterValid(plan)) return BootstrapError::InvalidPlan; + std::vector records; + records.reserve(plan.participants.size()); + for (const auto& participant : plan.participants) records.push_back(BootstrapRecord{participant, 0, 0, false, {}}); + std::sort(records.begin(), records.end(), [](const auto& a, const auto& b) { + if (a.planned.role != b.planned.role) return static_cast(a.planned.role) < static_cast(b.planned.role); + if (a.planned.participant_id != b.planned.participant_id) return a.planned.participant_id < b.planned.participant_id; + return a.planned.slot_id < b.planned.slot_id; + }); + BootstrapInventory result(plan.domain_id, 1, plan.epoch_id, plan.authority_incarnation, plan.policy_digest, + plan.expected_clock_identity, + std::make_shared>(std::move(records)), false, BootstrapError::None); + const auto encoded = EncodeBootstrapInventoryV1(result); + if (const auto* error = std::get_if(&encoded)) return *error; + return result; + } catch (...) { return BootstrapError::AllocationFailure; } +} + +std::size_t BootstrapInventory::recorded_count() const noexcept { + return static_cast(std::count_if(records_->begin(), records_->end(), [](const auto& r) { return r.identity_recorded; })); +} + +BootstrapTransition BootstrapInventory::RecordIdentity(const ObservedBootstrapIdentity& observed) const noexcept { + try { + auto records = *records_; + auto fail = [&](BootstrapError error) { + if (recovery_required_) return BootstrapTransition{*this, BootstrapError::RecoveryRequired}; + if (revision_ == std::numeric_limits::max()) + return BootstrapTransition{BootstrapInventory(domain_id_, revision_, epoch_id_, authority_incarnation_, policy_digest_, + expected_clock_identity_, records_, true, BootstrapError::RevisionExhausted), BootstrapError::RevisionExhausted}; + return BootstrapTransition{BootstrapInventory(domain_id_, revision_ + 1, epoch_id_, authority_incarnation_, policy_digest_, + expected_clock_identity_, records_, true, error), error}; + }; + if (recovery_required_) return BootstrapTransition{*this, BootstrapError::RecoveryRequired}; + const auto it = std::find_if(records.begin(), records.end(), [&](const auto& r) { + return r.planned.role == observed.participant.role && r.planned.participant_id == observed.participant.participant_id; + }); + if (it == records.end()) return fail(BootstrapError::IdentityNotInPlan); + if (!(it->planned == observed.participant) || observed.pid == 0 || observed.pid_start_ticks == 0 || + !(observed.clock_identity == expected_clock_identity_) || !ValidClock(observed.clock_identity)) + return fail(BootstrapError::IdentityMismatch); + if (it->identity_recorded) { + const bool same = it->pid == observed.pid && it->pid_start_ticks == observed.pid_start_ticks && + it->clock_identity == observed.clock_identity; + if (same) return BootstrapTransition{*this, BootstrapError::None}; + return fail(BootstrapError::IdentityMismatch); + } + for (const auto& record : records) { + if (&record != &*it && record.identity_recorded && record.pid == observed.pid) + return fail(BootstrapError::DuplicateProcessIdentity); + } + it->pid = observed.pid; + it->pid_start_ticks = observed.pid_start_ticks; + it->clock_identity = observed.clock_identity; + it->identity_recorded = true; + if (revision_ == std::numeric_limits::max()) + return fail(BootstrapError::RevisionExhausted); + return BootstrapTransition{BootstrapInventory(domain_id_, revision_ + 1, epoch_id_, authority_incarnation_, policy_digest_, + expected_clock_identity_, std::make_shared>(std::move(records)), + false, BootstrapError::None), BootstrapError::None}; + } catch (...) { + return BootstrapTransition{RequireRecovery(BootstrapError::AllocationFailure), BootstrapError::AllocationFailure}; + } +} + +BootstrapInventory BootstrapInventory::RequireRecovery(BootstrapError reason) const noexcept { + if (recovery_required_) return *this; + if (!ValidBootstrapError(reason) || reason == BootstrapError::None) reason = BootstrapError::InvalidPlan; + if (revision_ == std::numeric_limits::max()) + return BootstrapInventory(domain_id_, revision_, epoch_id_, authority_incarnation_, policy_digest_, + expected_clock_identity_, records_, true, BootstrapError::RevisionExhausted); + return BootstrapInventory(domain_id_, revision_ + 1, epoch_id_, authority_incarnation_, policy_digest_, expected_clock_identity_, + records_, true, reason); +} + +std::variant BootstrapInventory::ReadyCandidate() const noexcept { + try { + if (recovery_required_) return BootstrapError::RecoveryRequired; + if (revision_ == std::numeric_limits::max()) return BootstrapError::RevisionExhausted; + if (recorded_count() != records_->size()) return BootstrapError::IncompleteRoster; + EpochCandidate candidate{epoch_id_, authority_incarnation_, policy_digest_, expected_clock_identity_, {}}; + candidate.participants.reserve(records_->size()); + for (const auto& record : *records_) { + if (!record.identity_recorded) return BootstrapError::IncompleteRoster; + candidate.participants.push_back(Participant{record.planned.role, record.planned.slot_id, + record.planned.participant_id, record.planned.incarnation, + ProcessIdentity{record.planned.container_id, record.pid, record.pid_start_ticks}, record.clock_identity}); + } + if (ValidateEpochCandidate(candidate)) return BootstrapError::IdentityMismatch; + return candidate; + } catch (...) { return BootstrapError::AllocationFailure; } +} + +BootstrapEncodeResult EncodeBootstrapInventoryV1(const BootstrapInventory& inventory) noexcept { + try { + const auto payload = PayloadJson(inventory).dump(-1, ' ', false, Json::error_handler_t::strict); + if (payload.size() > kMaxBootstrapBytes) return BootstrapError::TooLarge; + const auto digest = Sha256(payload); + Json envelope{{"inventory", Json::parse(payload)}, {"sha256", Hex(digest)}}; + auto encoded = envelope.dump(-1, ' ', false, Json::error_handler_t::strict); + if (encoded.size() > kMaxBootstrapBytes) return BootstrapError::TooLarge; + return encoded; + } catch (const Failure& e) { return e.error; } + catch (...) { return BootstrapError::AllocationFailure; } +} + +BootstrapDecodeResult DecodeBootstrapInventoryV1(std::string_view envelope) noexcept { + if (envelope.size() > kMaxBootstrapBytes) return BootstrapError::TooLarge; + try { + const auto root = ParseJson(envelope); + CheckKeys(root, {"inventory", "sha256"}); + const auto expected = ParseHex<32>(root.at("sha256")); + auto inventory = ParsePayload(root.at("inventory")); + const auto payload = PayloadJson(inventory).dump(-1, ' ', false, Json::error_handler_t::strict); + if (Sha256(payload) != expected) return BootstrapError::DigestMismatch; + const auto canonical = EncodeBootstrapInventoryV1(inventory); + if (const auto* error = std::get_if(&canonical)) return *error; + if (std::get(canonical) != envelope) return BootstrapError::NonCanonical; + return inventory; + } catch (const Failure& e) { return e.error; } + catch (...) { return BootstrapError::AllocationFailure; } +} + +BootstrapDigestResult BootstrapDigestV1(const BootstrapInventory& inventory) noexcept { + try { + const auto payload = PayloadJson(inventory).dump(-1, ' ', false, Json::error_handler_t::strict); + if (payload.size() > kMaxBootstrapBytes) return BootstrapError::TooLarge; + return Sha256(payload); + } catch (const Failure& e) { return e.error; } + catch (...) { return BootstrapError::AllocationFailure; } +} + +} // namespace rateguard::supervisor diff --git a/src/supervisor/bootstrap_inventory.h b/src/supervisor/bootstrap_inventory.h new file mode 100644 index 0000000..00282ac --- /dev/null +++ b/src/supervisor/bootstrap_inventory.h @@ -0,0 +1,155 @@ +#pragma once + +// Pure value model for durable-before-launch epoch bootstrap. This component +// does not launch processes, persist files, or claim that a returned value is +// durable. The supervisor/store must persist each next value before acting on it. + +#include "supervisor/epoch_gate.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +inline constexpr std::size_t kMaxBootstrapBytes = 4U * 1024U * 1024U; + +struct PlannedParticipant { + ParticipantRole role{}; + std::uint32_t slot_id{}; + std::string participant_id; + IncarnationId incarnation{}; + std::string container_id; + friend bool operator==(const PlannedParticipant&, const PlannedParticipant&) = default; +}; + +struct ObservedBootstrapIdentity { + PlannedParticipant participant; + std::uint64_t pid{}; + std::uint64_t pid_start_ticks{}; + platform::ClockIdentity clock_identity{}; + friend bool operator==(const ObservedBootstrapIdentity&, const ObservedBootstrapIdentity&) = default; +}; + +struct BootstrapRecord { + PlannedParticipant planned; + std::uint64_t pid{}; + std::uint64_t pid_start_ticks{}; + bool identity_recorded{}; + platform::ClockIdentity clock_identity{}; + friend bool operator==(const BootstrapRecord&, const BootstrapRecord&) = default; +}; + +struct BootstrapPlan { + std::array domain_id{}; + EpochId epoch_id{}; + IncarnationId authority_incarnation{}; + PolicyDigest policy_digest{}; + platform::ClockIdentity expected_clock_identity{}; + std::vector participants; +}; + +enum class BootstrapError : std::uint8_t { + None, + InvalidPlan, + TooManyParticipants, + IdentityNotInPlan, + IdentityMismatch, + DuplicateProcessIdentity, + RecoveryRequired, + IncompleteRoster, + InvalidEncoding, + DuplicateKey, + UnknownKey, + MissingKey, + UnsupportedSchema, + NonCanonical, + DigestMismatch, + TooLarge, + DigestFailure, + AllocationFailure, + RevisionExhausted, +}; + +class BootstrapInventory; +struct BootstrapTransition; +struct BootstrapCodecAccess; + +class BootstrapInventory final { + public: + [[nodiscard]] static std::variant Create( + const BootstrapPlan& plan) noexcept; + + [[nodiscard]] const EpochId& epoch_id() const noexcept { return epoch_id_; } + [[nodiscard]] const std::array& domain_id() const noexcept { return domain_id_; } + [[nodiscard]] std::uint64_t revision() const noexcept { return revision_; } + [[nodiscard]] const IncarnationId& authority_incarnation() const noexcept { return authority_incarnation_; } + [[nodiscard]] const PolicyDigest& policy_digest() const noexcept { return policy_digest_; } + [[nodiscard]] const platform::ClockIdentity& expected_clock_identity() const noexcept { + return expected_clock_identity_; + } + [[nodiscard]] const std::vector& records() const noexcept { return *records_; } + [[nodiscard]] bool recovery_required() const noexcept { return recovery_required_; } + [[nodiscard]] BootstrapError recovery_reason() const noexcept { return recovery_reason_; } + [[nodiscard]] std::size_t recorded_count() const noexcept; + + // Returns a new value. Exact duplicate registration is idempotent. Any + // mismatch, unknown registration, or identity collision irreversibly latches + // recovery_required in the returned value. The store must persist it before + // exposing a response or taking a subsequent process action. + [[nodiscard]] BootstrapTransition RecordIdentity( + const ObservedBootstrapIdentity& observed) const noexcept; + + [[nodiscard]] BootstrapInventory RequireRecovery(BootstrapError reason) const noexcept; + [[nodiscard]] std::variant ReadyCandidate() const noexcept; + + private: + friend struct BootstrapTransition; + friend struct BootstrapCodecAccess; + friend std::variant EncodeBootstrapInventoryV1( + const BootstrapInventory&) noexcept; + friend std::variant DecodeBootstrapInventoryV1( + std::string_view) noexcept; + BootstrapInventory(std::array domain, std::uint64_t revision, + EpochId epoch, IncarnationId authority, PolicyDigest digest, + platform::ClockIdentity clock, + std::shared_ptr> records, + bool recovery, BootstrapError reason) noexcept + : domain_id_(domain), revision_(revision), epoch_id_(epoch), authority_incarnation_(authority), policy_digest_(digest), + expected_clock_identity_(clock), records_(std::move(records)), + recovery_required_(recovery), recovery_reason_(reason) {} + + std::array domain_id_{}; + std::uint64_t revision_{1}; + EpochId epoch_id_{}; + IncarnationId authority_incarnation_{}; + PolicyDigest policy_digest_{}; + platform::ClockIdentity expected_clock_identity_{}; + std::shared_ptr> records_; + bool recovery_required_{}; + BootstrapError recovery_reason_{BootstrapError::None}; +}; + +struct BootstrapTransition final { + BootstrapInventory next; + BootstrapError status{BootstrapError::None}; +}; + +using BootstrapEncodeResult = std::variant; +using BootstrapDecodeResult = std::variant; +using BootstrapDigestResult = std::variant, BootstrapError>; + +[[nodiscard]] BootstrapEncodeResult EncodeBootstrapInventoryV1( + const BootstrapInventory& inventory) noexcept; +[[nodiscard]] BootstrapDecodeResult DecodeBootstrapInventoryV1( + std::string_view envelope) noexcept; +[[nodiscard]] BootstrapDigestResult BootstrapDigestV1( + const BootstrapInventory& inventory) noexcept; + +} // namespace rateguard::supervisor diff --git a/src/supervisor/bootstrap_recovery_reader.cpp b/src/supervisor/bootstrap_recovery_reader.cpp new file mode 100644 index 0000000..4ddaf46 --- /dev/null +++ b/src/supervisor/bootstrap_recovery_reader.cpp @@ -0,0 +1,751 @@ +#include "supervisor/bootstrap_recovery_reader.h" +#include "supervisor/epoch_artifact_layout.h" + +#include "platform/file_io.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { +namespace { +using platform::file::ReadAll; +using platform::file::UniqueFd; + +constexpr char kLockName[] = "owner.lock"; +constexpr char kAnchorName[] = "runtime-anchor.json"; +using namespace epoch_layout_v1; + +bool Fail(IRecoveryReaderIo* io, RecoveryReaderIoPoint point) noexcept { + return io != nullptr && io->FailAt(point); +} + +bool SameInode(const struct stat& a, const struct stat& b) noexcept { + return a.st_dev == b.st_dev && a.st_ino == b.st_ino; +} + +RecoveryFileIdentity Identity(const struct stat& st) noexcept { +#if defined(__APPLE__) + const auto mtime = st.st_mtimespec; + const auto ctime = st.st_ctimespec; +#else + const auto mtime = st.st_mtim; + const auto ctime = st.st_ctim; +#endif + return {static_cast(st.st_dev), static_cast(st.st_ino), + static_cast(st.st_uid), static_cast(st.st_nlink), + static_cast(st.st_mode), static_cast(st.st_size), + static_cast(mtime.tv_sec), static_cast(mtime.tv_nsec), + static_cast(ctime.tv_sec), static_cast(ctime.tv_nsec)}; +} + +bool IsOwnedPrivateDirectory(const struct stat& st) noexcept { + return S_ISDIR(st.st_mode) && st.st_uid == ::geteuid() && (st.st_mode & 07777) == 0700; +} + +bool IsOwnedIntentFile(const struct stat& st) noexcept { + return S_ISREG(st.st_mode) && st.st_uid == ::geteuid() && (st.st_mode & 07777) == 0600 && + st.st_nlink == 1 && st.st_size >= 0; +} + +struct Entry final { + std::string name; + struct stat st {}; + bool stat_ok{}; +}; + +struct Listing final { + std::vector entries; + bool complete{true}; + bool empty{}; + bool limit_reached{}; +}; + +struct ScanContext final { + BootstrapRecoverySnapshot& snapshot; + IRecoveryReaderIo* io{}; + std::size_t issue_count{}; + std::size_t bytes_reserved{}; + std::size_t participants_retained{}; + bool stop{}; +}; + +void MarkIncomplete(ScanContext& ctx) noexcept { ctx.snapshot.scan_complete = false; } + +void AddRootIssue(ScanContext& ctx, RecoveryIssueCode code) { + MarkIncomplete(ctx); + if (ctx.issue_count >= kMaxRecoveryIssues) { + ctx.snapshot.issues_truncated = true; + return; + } + if (ctx.issue_count + 1 == kMaxRecoveryIssues) { + ctx.snapshot.issues.push_back({RecoveryIssueCode::ResourceLimit, std::nullopt}); + ++ctx.issue_count; + ctx.snapshot.issues_truncated = true; + return; + } + ctx.snapshot.issues.push_back({code, std::nullopt}); + ++ctx.issue_count; +} + +void AddEpochIssue(ScanContext& ctx, std::size_t epoch_index, RecoveryIssueCode code) { + MarkIncomplete(ctx); + auto& epoch = ctx.snapshot.epochs[epoch_index]; + if (epoch.issues.size() >= kMaxRecoveryEpochIssues || + ctx.issue_count >= kMaxRecoveryIssues) { + epoch.issues_truncated = true; + ctx.snapshot.issues_truncated = true; + return; + } + if (epoch.issues.size() + 1 == kMaxRecoveryEpochIssues || + ctx.issue_count + 1 == kMaxRecoveryIssues) { + epoch.issues.push_back(RecoveryIssueCode::ResourceLimit); + if (ctx.issue_count < kMaxRecoveryIssues) + ctx.snapshot.issues.push_back({RecoveryIssueCode::ResourceLimit, epoch_index}); + ++ctx.issue_count; + epoch.issues_truncated = true; + ctx.snapshot.issues_truncated = true; + return; + } + epoch.issues.push_back(code); + ctx.snapshot.issues.push_back({code, epoch_index}); + ++ctx.issue_count; +} + +Listing EnumerateDirectory(int directory_fd, ScanContext& ctx, + RecoveryReaderIoPoint fail_point, std::size_t cap, + RecoveryReaderIoPoint stat_point) { + Listing listing; + if (Fail(ctx.io, fail_point)) { + listing.complete = false; + return listing; + } + UniqueFd scan(::openat(directory_fd, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (scan.get() < 0) { + listing.complete = false; + return listing; + } + struct stat original{}, opened{}; + if (::fstat(directory_fd, &original) != 0 || ::fstat(scan.get(), &opened) != 0 || + !SameInode(original, opened) || !IsOwnedPrivateDirectory(opened)) { + listing.complete = false; + return listing; + } + listing.entries.reserve(cap); + DIR* stream = ::fdopendir(scan.get()); + if (stream == nullptr) { + listing.complete = false; + return listing; + } + (void)scan.release(); + const auto close_directory = [](DIR* value) noexcept { if (value != nullptr) ::closedir(value); }; + std::unique_ptr directory(stream, close_directory); + for (;;) { + errno = 0; + dirent* item = ::readdir(directory.get()); + if (item == nullptr) { + if (errno != 0) listing.complete = false; + break; + } + const std::string_view name(item->d_name); + if (name == "." || name == "..") continue; + if (listing.entries.size() >= cap) { + listing.complete = false; + listing.limit_reached = true; + break; + } + Entry entry; + entry.name.assign(name); + if (Fail(ctx.io, stat_point) || + ::fstatat(directory_fd, entry.name.c_str(), &entry.st, AT_SYMLINK_NOFOLLOW) != 0) { + entry.stat_ok = false; + listing.complete = false; + } else { + entry.stat_ok = true; + } + listing.entries.push_back(std::move(entry)); + } + directory.reset(); + std::sort(listing.entries.begin(), listing.entries.end(), [](const Entry& a, const Entry& b) { + return a.name < b.name; + }); + listing.empty = listing.entries.empty(); + return listing; +} + +bool SameListing(const Listing& a, const Listing& b) noexcept { + if (!a.complete || !b.complete || a.entries.size() != b.entries.size()) return false; + for (std::size_t i = 0; i < a.entries.size(); ++i) { + const auto& left = a.entries[i]; + const auto& right = b.entries[i]; + if (left.name != right.name || left.stat_ok != right.stat_ok) return false; + if (left.stat_ok && !(Identity(left.st) == Identity(right.st))) return false; + } + return true; +} + +void ProcessBootstrapIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, + const Entry& root_entry) { + auto& diagnostic = ctx.snapshot.epochs[epoch_index]; + UniqueFd child(::openat(root_fd, diagnostic.directory_name.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (Fail(ctx.io, RecoveryReaderIoPoint::OpenEpochDirectory) || child.get() < 0) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidEpochDirectory); + return; + } + struct stat child_fd_stat{}, child_path_stat{}; + if (::fstat(child.get(), &child_fd_stat) != 0 || !IsOwnedPrivateDirectory(child_fd_stat) || + ::fstatat(root_fd, diagnostic.directory_name.c_str(), &child_path_stat, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(root_entry.st, child_fd_stat) || !SameInode(child_path_stat, child_fd_stat)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); + return; + } + diagnostic.directory_identity = Identity(child_fd_stat); + + Listing child_before = EnumerateDirectory(child.get(), ctx, RecoveryReaderIoPoint::EnumerateEpoch, + kMaxRecoveryChildEntries, RecoveryReaderIoPoint::StatRootEntry); + if (!child_before.complete) AddEpochIssue(ctx, epoch_index, + child_before.limit_reached ? RecoveryIssueCode::TooManyChildEntries + : RecoveryIssueCode::EpochDirectoryChanged); + bool found_intent = false; + for (const auto& entry : child_before.entries) { + if (!entry.stat_ok) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidIntentFile); + continue; + } + if (entry.name == kIntentFileName) found_intent = true; + else if (entry.name != kManifestStoreDirectoryName) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochHasUnexpectedEntry); + } + if (ctx.stop) return; + if (!found_intent) { + struct stat probe{}; + if (::fstatat(child.get(), kIntentFileName, &probe, AT_SYMLINK_NOFOLLOW) == 0) { + found_intent = true; + } else if (errno == ENOENT) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::MissingIntent); + return; + } else { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidIntentFile); + return; + } + } + + if (Fail(ctx.io, RecoveryReaderIoPoint::StatIntent)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidIntentFile); + return; + } + struct stat path_before{}; + if (::fstatat(child.get(), kIntentFileName, &path_before, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedIntentFile(path_before)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidIntentFile); + return; + } + const auto file_size = static_cast(path_before.st_size); + if (file_size > kMaxRecoveryAggregateBytes - ctx.bytes_reserved) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::AggregateByteLimit); + ctx.stop = true; + return; + } + // Conservatively charge the stat-reported extent before allocating or reading. + ctx.bytes_reserved += static_cast(file_size); + if (file_size > kMaxBootstrapBytes) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentTooLarge); + return; + } + + if (Fail(ctx.io, RecoveryReaderIoPoint::OpenIntent)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentReadFailed); + return; + } + UniqueFd intent(::openat(child.get(), kIntentFileName, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (intent.get() < 0) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentReadFailed); + return; + } + struct stat file_fd_before{}, path_opened{}; + if (::fstat(intent.get(), &file_fd_before) != 0 || !IsOwnedIntentFile(file_fd_before) || + !SameInode(path_before, file_fd_before) || + ::fstatat(child.get(), kIntentFileName, &path_opened, AT_SYMLINK_NOFOLLOW) != 0 || + !(Identity(path_opened) == Identity(file_fd_before))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentChanged); + return; + } + diagnostic.intent_identity = Identity(file_fd_before); + if (Fail(ctx.io, RecoveryReaderIoPoint::ReadIntent)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentReadFailed); + return; + } + std::string bytes; + if (!ReadAll(intent.get(), bytes, static_cast(file_size))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentReadFailed); + return; + } + struct stat file_fd_after{}, path_after{}; + if (Fail(ctx.io, RecoveryReaderIoPoint::RevalidateEntry) || + ::fstat(intent.get(), &file_fd_after) != 0 || !IsOwnedIntentFile(file_fd_after) || + ::fstatat(child.get(), kIntentFileName, &path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedIntentFile(path_after) || + !(Identity(file_fd_before) == Identity(file_fd_after)) || + !(Identity(file_fd_after) == Identity(path_after))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentChanged); + return; + } + diagnostic.intent_identity = Identity(file_fd_after); + + const auto decoded = DecodeBootstrapInventoryV1(bytes); + if (const auto* error = std::get_if(&decoded)) { + AddEpochIssue(ctx, epoch_index, *error == BootstrapError::DigestMismatch + ? RecoveryIssueCode::DigestMismatch : RecoveryIssueCode::InvalidEncoding); + return; + } + auto inventory = std::get(decoded); + if (inventory.domain_id() != ctx.snapshot.domain_id) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::DomainMismatch); + return; + } + const auto parsed_directory_epoch = ParseEpochDirectoryName(diagnostic.directory_name); + if (!parsed_directory_epoch || inventory.epoch_id() != *parsed_directory_epoch) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochMismatch); + return; + } + const auto digest = BootstrapDigestV1(inventory); + if (const auto* error = std::get_if(&digest)) { + (void)error; + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::DigestFailure); + return; + } + const auto actual_digest = std::get>(digest); + diagnostic.canonical_digest = actual_digest; + if (inventory.recovery_required()) AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::RecoveryAlreadyLatched); + if (ctx.participants_retained + inventory.records().size() > kMaxRecoveryAggregateParticipants) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::AggregateParticipantLimit); + ctx.stop = true; + return; + } + ctx.participants_retained += inventory.records().size(); + diagnostic.inventory = std::make_shared(std::move(inventory)); + + if (!child_before.limit_reached) { + Listing child_after = EnumerateDirectory(child.get(), ctx, RecoveryReaderIoPoint::EnumerateEpoch, + kMaxRecoveryChildEntries, RecoveryReaderIoPoint::StatRootEntry); + if (!SameListing(child_before, child_after)) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); + } + struct stat child_fd_after{}, child_path_after{}; + if (::fstat(child.get(), &child_fd_after) != 0 || + ::fstatat(root_fd, diagnostic.directory_name.c_str(), &child_path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedPrivateDirectory(child_fd_after) || + !(Identity(child_fd_stat) == Identity(child_fd_after)) || + !(Identity(child_fd_after) == Identity(child_path_after))) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); +} + +bool IsOwnedEmptyLock(const struct stat& st) noexcept { + return IsOwnedIntentFile(st) && st.st_size == 0; +} + +bool ChargeRead(ScanContext& ctx, std::size_t bytes, std::size_t epoch_index) { + if (bytes > kMaxRecoveryAggregateBytes - ctx.bytes_reserved) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::AggregateByteLimit); + ctx.stop = true; + return false; + } + // Charge the stat-reported extent before allocation/open/read and never + // refund it after any parse, open, or read failure. + ctx.bytes_reserved += bytes; + return true; +} + +void ProcessManifestStore(ScanContext& ctx, int root_fd, std::size_t epoch_index, + const Entry& root_entry, + const std::optional& expected_store, + bool baseline_stat_failed) { + auto& epoch = ctx.snapshot.epochs[epoch_index]; + UniqueFd epoch_fd(::openat(root_fd, epoch.directory_name.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (epoch_fd.get() < 0) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); + return; + } + struct stat epoch_fd_stat{}, epoch_path_stat{}; + if (::fstat(epoch_fd.get(), &epoch_fd_stat) != 0 || + !IsOwnedPrivateDirectory(epoch_fd_stat) || + ::fstatat(root_fd, epoch.directory_name.c_str(), &epoch_path_stat, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(root_entry.st, epoch_fd_stat) || !SameInode(epoch_fd_stat, epoch_path_stat)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); + return; + } + + struct stat store_initial{}; + if (::fstatat(epoch_fd.get(), kManifestStoreDirectoryName, &store_initial, AT_SYMLINK_NOFOLLOW) != 0) { + if (errno == ENOENT && !expected_store && !baseline_stat_failed) + return; // Bootstrap-only history is a valid diagnostic shape. + if (errno == ENOENT && expected_store) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreChanged); + else + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreDirectory); + return; + } + RecoveryEpochDiagnostic::ManifestDiagnostic diagnostic; + epoch.manifest_store = diagnostic; + auto& manifest_diag = *epoch.manifest_store; + if (baseline_stat_failed || !expected_store || !(Identity(store_initial) == *expected_store)) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreChanged); + if (!IsOwnedPrivateDirectory(store_initial)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreDirectory); + return; + } + UniqueFd store_fd; + if (Fail(ctx.io, RecoveryReaderIoPoint::OpenManifestStoreDirectory)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreDirectory); + return; + } + store_fd = UniqueFd(::openat(epoch_fd.get(), kManifestStoreDirectoryName, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + struct stat store_fd_before{}, store_path_opened{}; + if (store_fd.get() < 0 || ::fstat(store_fd.get(), &store_fd_before) != 0 || + !IsOwnedPrivateDirectory(store_fd_before) || + !(Identity(store_initial) == Identity(store_fd_before)) || + ::fstatat(epoch_fd.get(), kManifestStoreDirectoryName, &store_path_opened, AT_SYMLINK_NOFOLLOW) != 0 || + !(Identity(store_fd_before) == Identity(store_path_opened))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreDirectory); + return; + } + manifest_diag.directory_identity = Identity(store_fd_before); + + Listing before = EnumerateDirectory(store_fd.get(), ctx, + RecoveryReaderIoPoint::EnumerateManifestStore, kMaxRecoveryManifestStoreEntries, + RecoveryReaderIoPoint::StatManifestStoreEntry); + if (!before.complete) + AddEpochIssue(ctx, epoch_index, before.limit_reached + ? RecoveryIssueCode::TooManyManifestStoreEntries + : RecoveryIssueCode::ManifestStoreChanged); + for (const auto& entry : before.entries) { + if (!entry.stat_ok) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreFile); + continue; + } + if (entry.name == kManifestStoreLockFileName || entry.name == kManifestFileName) continue; + else AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreHasUnexpectedEntry); + } + // Always probe the two allowlisted names, even when an unrelated temporary + // or unknown entry made the listing incomplete. This preserves known data. + const auto validate_lock = [&]() { + struct stat path_before{}; + if (::fstatat(store_fd.get(), kManifestStoreLockFileName, &path_before, AT_SYMLINK_NOFOLLOW) != 0) { + AddEpochIssue(ctx, epoch_index, errno == ENOENT + ? RecoveryIssueCode::MissingManifestStoreFile + : RecoveryIssueCode::InvalidManifestStoreFile); + return; + } + if (!IsOwnedEmptyLock(path_before)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreFile); + return; + } + if (Fail(ctx.io, RecoveryReaderIoPoint::OpenManifestLock)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreReadFailed); + return; + } + UniqueFd lock(::openat(store_fd.get(), kManifestStoreLockFileName, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + struct stat fd_stat{}, path_after{}; + if (lock.get() < 0 || ::fstat(lock.get(), &fd_stat) != 0 || !IsOwnedEmptyLock(fd_stat) || + !(Identity(path_before) == Identity(fd_stat)) || + Fail(ctx.io, RecoveryReaderIoPoint::RevalidateManifestLock) || + ::fstatat(store_fd.get(), kManifestStoreLockFileName, &path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !(Identity(fd_stat) == Identity(path_after))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileChanged); + return; + } + manifest_diag.owner_lock_identity = Identity(fd_stat); + }; + validate_lock(); + + const auto read_manifest = [&]() { + struct stat path_before{}; + if (::fstatat(store_fd.get(), kManifestFileName, &path_before, AT_SYMLINK_NOFOLLOW) != 0) { + AddEpochIssue(ctx, epoch_index, errno == ENOENT + ? RecoveryIssueCode::MissingManifestStoreFile + : RecoveryIssueCode::InvalidManifestStoreFile); + return; + } + if (!IsOwnedIntentFile(path_before)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreFile); + return; + } + const auto size = static_cast(path_before.st_size); + if (size > std::numeric_limits::max()) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileTooLarge); + return; + } + if (!ChargeRead(ctx, static_cast(size), epoch_index)) return; + if (size > kMaxManifestBytes) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileTooLarge); + return; + } + if (Fail(ctx.io, RecoveryReaderIoPoint::OpenManifestFile)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreReadFailed); + return; + } + UniqueFd file(::openat(store_fd.get(), kManifestFileName, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + struct stat fd_before{}, path_opened{}; + if (file.get() < 0 || ::fstat(file.get(), &fd_before) != 0 || + !IsOwnedIntentFile(fd_before) || !(Identity(path_before) == Identity(fd_before)) || + ::fstatat(store_fd.get(), kManifestFileName, &path_opened, AT_SYMLINK_NOFOLLOW) != 0 || + !(Identity(fd_before) == Identity(path_opened))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileChanged); + return; + } + manifest_diag.manifest_identity = Identity(fd_before); + if (Fail(ctx.io, RecoveryReaderIoPoint::ReadManifestFile)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreReadFailed); + return; + } + std::string bytes; + if (!ReadAll(file.get(), bytes, static_cast(size))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreReadFailed); + return; + } + struct stat fd_after{}, path_after{}; + if (Fail(ctx.io, RecoveryReaderIoPoint::RevalidateManifestFile) || + ::fstat(file.get(), &fd_after) != 0 || !IsOwnedIntentFile(fd_after) || + ::fstatat(store_fd.get(), kManifestFileName, &path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedIntentFile(path_after) || !(Identity(fd_before) == Identity(fd_after)) || + !(Identity(fd_after) == Identity(path_after))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileChanged); + return; + } + manifest_diag.manifest_identity = Identity(fd_after); + const auto decoded = DecodeManifestV1(bytes); + if (const auto* codec_error = std::get_if(&decoded)) { + if (*codec_error == ManifestCodecError::DigestMismatch) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestCodecDigestMismatch); + else if (*codec_error == ManifestCodecError::DigestFailure) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::DigestFailure); + else + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestEncoding); + return; + } + auto manifest = std::get(decoded); + if (ctx.participants_retained + manifest.candidate.participants.size() > + kMaxRecoveryAggregateParticipants) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::AggregateParticipantLimit); + ctx.stop = true; + return; + } + ctx.participants_retained += manifest.candidate.participants.size(); + const auto digest = ManifestDigestV1(manifest); + if (const auto* codec_error = std::get_if(&digest)) { + (void)codec_error; + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::DigestFailure); + return; + } + manifest_diag.canonical_digest = std::get>(digest); + manifest_diag.decoded_manifest = std::make_shared(std::move(manifest)); + const auto& inventory = epoch.inventory; + if (!inventory) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestBootstrapNotReady); + return; + } + const auto candidate = inventory->ReadyCandidate(); + if (std::holds_alternative(candidate)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestBootstrapNotReady); + } else if (std::get(candidate) != manifest_diag.decoded_manifest->candidate) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestCandidateMismatch); + } + }; + read_manifest(); + + Listing after = EnumerateDirectory(store_fd.get(), ctx, + RecoveryReaderIoPoint::EnumerateManifestStore, kMaxRecoveryManifestStoreEntries, + RecoveryReaderIoPoint::StatManifestStoreEntry); + if (!SameListing(before, after)) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreChanged); + struct stat store_fd_after{}, store_path_after{}, epoch_fd_after{}, epoch_path_after{}; + if (Fail(ctx.io, RecoveryReaderIoPoint::RevalidateManifestStore) || + ::fstat(store_fd.get(), &store_fd_after) != 0 || + !IsOwnedPrivateDirectory(store_fd_after) || + !(Identity(store_fd_before) == Identity(store_fd_after)) || + ::fstatat(epoch_fd.get(), kManifestStoreDirectoryName, &store_path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedPrivateDirectory(store_path_after) || + !(Identity(store_fd_after) == Identity(store_path_after)) || + ::fstat(epoch_fd.get(), &epoch_fd_after) != 0 || + ::fstatat(root_fd, epoch.directory_name.c_str(), &epoch_path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedPrivateDirectory(epoch_fd_after) || + !(Identity(root_entry.st) == Identity(epoch_fd_after)) || + !(Identity(epoch_fd_after) == Identity(epoch_path_after))) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreChanged); +} + +void ProcessEpochArtifacts(ScanContext& ctx, int root_fd, std::size_t epoch_index, + const Entry& root_entry) { + std::optional expected_store; + bool baseline_stat_failed = false; + UniqueFd epoch_fd(::openat(root_fd, ctx.snapshot.epochs[epoch_index].directory_name.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (epoch_fd.get() >= 0) { + struct stat path_stat{}; + if (::fstatat(epoch_fd.get(), kManifestStoreDirectoryName, &path_stat, AT_SYMLINK_NOFOLLOW) == 0) + expected_store = Identity(path_stat); + else if (errno != ENOENT) + baseline_stat_failed = true; + } else { + baseline_stat_failed = true; + } + ProcessBootstrapIntent(ctx, root_fd, epoch_index, root_entry); + if (!ctx.stop) + ProcessManifestStore(ctx, root_fd, epoch_index, root_entry, expected_store, baseline_stat_failed); +} + +} // namespace + +BootstrapRecoveryReadResult BootstrapRecoveryReader::Read( + const RuntimeOwner& owner, IRecoveryReaderIo* test_io) noexcept { + try { + if (owner.mode() != RuntimeOwnerMode::RecoveryRequired) + return RecoveryReaderFatal::OwnerNotRecoveryMode; + if (Fail(test_io, RecoveryReaderIoPoint::ValidateOwnerBefore) || + std::holds_alternative(owner.ValidateOwnership())) + return RecoveryReaderFatal::OwnerInvalid; + auto root_result = [&]() -> DuplicateFdResult { + if (Fail(test_io, RecoveryReaderIoPoint::DuplicateRoot)) return RuntimeOwnerError::IoFailure; + return owner.DuplicateRootFd(); + }(); + if (const auto* error = std::get_if(&root_result)) { + (void)error; + return RecoveryReaderFatal::RootDescriptorUnavailable; + } + UniqueFd root(std::get(root_result)); + struct stat root_stat{}; + if (::fstat(root.get(), &root_stat) != 0 || !IsOwnedPrivateDirectory(root_stat)) + return RecoveryReaderFatal::RootDescriptorUnavailable; + + auto snapshot = std::make_shared(); + snapshot->domain_id = owner.domain_id(); + snapshot->scan_complete = true; + snapshot->epochs.reserve(kMaxRecoveryEpochDirectories); + snapshot->issues.reserve(kMaxRecoveryIssues); + ScanContext ctx{*snapshot, test_io}; + Listing root_before = EnumerateDirectory(root.get(), ctx, RecoveryReaderIoPoint::EnumerateRootFirst, + kMaxRecoveryRootEntries, RecoveryReaderIoPoint::StatRootEntry); + if (!root_before.complete) { + AddRootIssue(ctx, root_before.limit_reached ? RecoveryIssueCode::TooManyRootEntries + : RecoveryIssueCode::RootEnumerationFailed); + } + std::size_t epoch_dirs = 0; + bool found_any_epoch_dir = false; + for (const auto& entry : root_before.entries) { + if (ctx.stop) break; + if (!entry.stat_ok) AddRootIssue(ctx, RecoveryIssueCode::RootEntryStatFailed); + if (entry.name == kLockName || entry.name == kAnchorName) continue; + if (!entry.name.starts_with(kEpochDirectoryPrefix)) { + AddRootIssue(ctx, RecoveryIssueCode::UnexpectedRootEntry); + continue; + } + found_any_epoch_dir = true; + const auto parsed = ParseEpochDirectoryName(entry.name); + if (!parsed) { + AddRootIssue(ctx, RecoveryIssueCode::InvalidEpochDirectoryName); + continue; + } + if (++epoch_dirs > kMaxRecoveryEpochDirectories) { + AddRootIssue(ctx, RecoveryIssueCode::TooManyEpochDirectories); + ctx.stop = true; + break; + } + if (!entry.stat_ok || !IsOwnedPrivateDirectory(entry.st)) { + RecoveryEpochDiagnostic bad; + bad.directory_name = entry.name; + if (entry.stat_ok) bad.directory_identity = Identity(entry.st); + snapshot->epochs.push_back(std::move(bad)); + AddEpochIssue(ctx, snapshot->epochs.size() - 1, RecoveryIssueCode::InvalidEpochDirectory); + continue; + } + RecoveryEpochDiagnostic diagnostic; + diagnostic.directory_name = entry.name; + diagnostic.directory_identity = Identity(entry.st); + snapshot->epochs.push_back(std::move(diagnostic)); + const auto index = snapshot->epochs.size() - 1; + ProcessEpochArtifacts(ctx, root.get(), index, entry); + } + if (root_before.limit_reached) ctx.stop = true; + if (root_before.empty) { + AddRootIssue(ctx, RecoveryIssueCode::EmptyRoot); + ctx.stop = true; + } else if (!found_any_epoch_dir || std::none_of(snapshot->epochs.begin(), snapshot->epochs.end(), + [](const auto& epoch) { return epoch.inventory != nullptr; })) { + AddRootIssue(ctx, RecoveryIssueCode::NoValidIntents); + } + + // Compare the union of bootstrap and manifest targets across epochs. + // Matching representations in one epoch intentionally repeat the same + // participants; only duplicates across epoch contexts are collisions. + std::set> containers; + std::set>> processes; + for (std::size_t i = 0; i < snapshot->epochs.size() && !ctx.stop; ++i) { + std::set> epoch_containers; + std::set>> epoch_processes; + const auto add_target = [&](const std::string& container, std::uint64_t pid, + std::uint64_t start_ticks, + const std::array& boot) { + epoch_containers.insert(container); + if (pid != 0 && start_ticks != 0) epoch_processes.emplace(pid, start_ticks, boot); + }; + if (const auto& inventory = snapshot->epochs[i].inventory; inventory) { + for (const auto& record : inventory->records()) { + add_target(record.planned.container_id, record.identity_recorded ? record.pid : 0, + record.identity_recorded ? record.pid_start_ticks : 0, + record.clock_identity.boot_uuid); + } + } + if (const auto& manifest = snapshot->epochs[i].manifest_store; + manifest && manifest->decoded_manifest) { + for (const auto& participant : manifest->decoded_manifest->candidate.participants) { + add_target(participant.process.container_id, participant.process.pid, + participant.process.pid_start_ticks, participant.clock_identity.boot_uuid); + } + } + for (const auto& container : epoch_containers) { + if (!containers.insert(container).second) { + AddEpochIssue(ctx, i, RecoveryIssueCode::IdentityCollisionAcrossEpochs); + if (ctx.stop) break; + } + } + for (const auto& process : epoch_processes) { + if (!processes.insert(process).second) { + AddEpochIssue(ctx, i, RecoveryIssueCode::IdentityCollisionAcrossEpochs); + if (ctx.stop) break; + } + } + } + + if (!ctx.stop) { + Listing root_after = EnumerateDirectory(root.get(), ctx, RecoveryReaderIoPoint::EnumerateRootSecond, + kMaxRecoveryRootEntries, RecoveryReaderIoPoint::StatRootEntry); + struct stat root_after_stat{}; + if (!SameListing(root_before, root_after) || ::fstat(root.get(), &root_after_stat) != 0 || + !IsOwnedPrivateDirectory(root_after_stat) || + !(Identity(root_stat) == Identity(root_after_stat))) + AddRootIssue(ctx, RecoveryIssueCode::RootChangedDuringScan); + } + if (Fail(test_io, RecoveryReaderIoPoint::ValidateOwnerAfter) || + std::holds_alternative(owner.ValidateOwnership())) + AddRootIssue(ctx, RecoveryIssueCode::OwnerChangedDuringScan); + if (!found_any_epoch_dir) snapshot->scan_complete = false; + return std::shared_ptr(std::move(snapshot)); + } catch (...) { + return RecoveryReaderFatal::AllocationFailure; + } +} + +} // namespace rateguard::supervisor diff --git a/src/supervisor/bootstrap_recovery_reader.h b/src/supervisor/bootstrap_recovery_reader.h new file mode 100644 index 0000000..b454f4c --- /dev/null +++ b/src/supervisor/bootstrap_recovery_reader.h @@ -0,0 +1,180 @@ +#pragma once + +// Read-only diagnostic scan of bootstrap artifacts under an existing, +// recovery-mode RuntimeOwner. The result is never a serving or fencing token. + +#include "supervisor/bootstrap_inventory.h" +#include "supervisor/manifest_codec.h" +#include "supervisor/runtime_owner.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +inline constexpr std::size_t kMaxRecoveryEpochDirectories = 1024; +inline constexpr std::size_t kMaxRecoveryRootEntries = 4096; +inline constexpr std::size_t kMaxRecoveryChildEntries = 16; +inline constexpr std::size_t kMaxRecoveryManifestStoreEntries = 16; +inline constexpr std::size_t kMaxRecoveryAggregateBytes = 64U * 1024U * 1024U; +inline constexpr std::size_t kMaxRecoveryAggregateParticipants = 16'384; +inline constexpr std::size_t kMaxRecoveryIssues = 256; +inline constexpr std::size_t kMaxRecoveryEpochIssues = 16; + +struct RecoveryFileIdentity final { + std::uint64_t device{}; + std::uint64_t inode{}; + std::uint64_t owner_id{}; + std::uint64_t link_count{}; + std::uint32_t mode{}; + std::uint64_t size{}; + std::int64_t mtime_seconds{}; + std::uint32_t mtime_nanoseconds{}; + std::int64_t ctime_seconds{}; + std::uint32_t ctime_nanoseconds{}; + friend bool operator==(const RecoveryFileIdentity&, const RecoveryFileIdentity&) = default; +}; + +enum class RecoveryIssueCode : std::uint8_t { + RootEntryStatFailed, + UnexpectedRootEntry, + InvalidEpochDirectoryName, + InvalidEpochDirectory, + EpochDirectoryChanged, + EpochHasUnexpectedEntry, + TooManyChildEntries, + MissingIntent, + InvalidIntentFile, + IntentReadFailed, + IntentChanged, + IntentTooLarge, + AggregateByteLimit, + AggregateParticipantLimit, + InvalidEncoding, + DigestFailure, + DigestMismatch, + DomainMismatch, + EpochMismatch, + IdentityCollisionAcrossEpochs, + RecoveryAlreadyLatched, + EmptyRoot, + NoValidIntents, + TooManyRootEntries, + TooManyEpochDirectories, + RootEnumerationFailed, + RootChangedDuringScan, + OwnerChangedDuringScan, + ResourceLimit, + InvalidManifestStoreDirectory, + ManifestStoreChanged, + ManifestStoreHasUnexpectedEntry, + TooManyManifestStoreEntries, + MissingManifestStoreFile, + InvalidManifestStoreFile, + ManifestStoreReadFailed, + ManifestStoreFileChanged, + ManifestStoreFileTooLarge, + InvalidManifestEncoding, + ManifestCodecDigestMismatch, + ManifestCandidateMismatch, + ManifestBootstrapNotReady, +}; + +struct RecoveryEpochDiagnostic final { + // Canonical `epoch-<32 lowercase hex>` form only; never an arbitrary name. + std::string directory_name; + RecoveryFileIdentity directory_identity{}; + std::optional intent_identity; + std::shared_ptr inventory; + std::optional> canonical_digest; + // Present only when the optional `manifest-store` child existed and was + // inspected. A decoded manifest is diagnostic data, never an activation, + // stop, reset, or successor-epoch authorization. + struct ManifestDiagnostic final { + RecoveryFileIdentity directory_identity{}; + std::optional owner_lock_identity; + std::optional manifest_identity; + std::shared_ptr decoded_manifest; + std::optional> canonical_digest; + }; + std::optional manifest_store; + std::vector issues; + bool issues_truncated{}; +}; + +struct RecoveryIssue final { + RecoveryIssueCode code{}; + // Index into snapshot.epochs for an epoch-local issue; absent for root scope. + // Raw arbitrary filesystem names are deliberately never returned. + std::optional epoch_index; +}; + +struct BootstrapRecoverySnapshot final { + RuntimeDomainId domain_id{}; + // Diagnostic structural result only. False for unknown/temp entries, + // recovery-latched or colliding inventories, mutation, or resource limits. + // True never proves prior fsync, process exit, or permission to serve/reset. + // This is a bounded scan, not an atomic cross-epoch snapshot or protection + // against hostile same-UID mutation; each known inventory is independently + // decoded and retains its historical clock provenance without current-time + // comparison. + bool scan_complete{}; + std::vector epochs; + std::vector issues; + bool issues_truncated{}; +}; + +enum class RecoveryReaderFatal : std::uint8_t { + OwnerNotRecoveryMode, + OwnerInvalid, + RootDescriptorUnavailable, + AllocationFailure, +}; + +using BootstrapRecoveryReadResult = + std::variant, RecoveryReaderFatal>; + +enum class RecoveryReaderIoPoint : std::uint8_t { + ValidateOwnerBefore, + DuplicateRoot, + EnumerateRootFirst, + EnumerateRootSecond, + StatRootEntry, + OpenEpochDirectory, + EnumerateEpoch, + StatIntent, + OpenIntent, + ReadIntent, + RevalidateEntry, + ValidateOwnerAfter, + OpenManifestStoreDirectory, + EnumerateManifestStore, + StatManifestStoreEntry, + OpenManifestLock, + RevalidateManifestLock, + OpenManifestFile, + ReadManifestFile, + RevalidateManifestFile, + RevalidateManifestStore, +}; + +class IRecoveryReaderIo { + public: + virtual ~IRecoveryReaderIo() = default; + // Test hook only; it must outlive the read call. Failure is fail-closed. + [[nodiscard]] virtual bool FailAt(RecoveryReaderIoPoint point) noexcept = 0; +}; + +class BootstrapRecoveryReader final { + public: + [[nodiscard]] static BootstrapRecoveryReadResult Read( + const RuntimeOwner& owner, IRecoveryReaderIo* test_io = nullptr) noexcept; +}; + +} // namespace rateguard::supervisor diff --git a/src/supervisor/bootstrap_store.cpp b/src/supervisor/bootstrap_store.cpp new file mode 100644 index 0000000..4a6c8e2 --- /dev/null +++ b/src/supervisor/bootstrap_store.cpp @@ -0,0 +1,461 @@ +#include "supervisor/bootstrap_store.h" + +#include "platform/file_io.h" +#include "supervisor/epoch_artifact_layout.h" + +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { +namespace { +using platform::file::ReadAll; +using platform::file::Sync; +using platform::file::UniqueFd; +using platform::file::WriteAll; + +constexpr auto& kIntentName = epoch_layout_v1::kIntentFileName; +constexpr auto& kTempName = epoch_layout_v1::kIntentTemporaryFileName; + +bool Fail(IBootstrapStoreIo* io, BootstrapStoreIoPoint point) noexcept { + return io != nullptr && io->FailAt(point); +} + +bool SameInode(const struct stat& a, const struct stat& b) noexcept { + return a.st_dev == b.st_dev && a.st_ino == b.st_ino; +} + +bool ValidOwnedDir(const struct stat& st) noexcept { + return S_ISDIR(st.st_mode) && st.st_uid == ::geteuid() && (st.st_mode & 07777) == 0700; +} + +bool ValidIntentFile(const struct stat& st) noexcept { + return S_ISREG(st.st_mode) && st.st_uid == ::geteuid() && + (st.st_mode & 07777) == 0600 && st.st_nlink == 1 && st.st_size >= 0 && + static_cast(st.st_size) <= kMaxBootstrapBytes; +} + +bool CloseChecked(UniqueFd& fd) noexcept { + const int raw = fd.release(); + if (raw < 0) return true; + // close(EINTR) is treated as uncertain; do not retry a possibly reused fd. + return ::close(raw) == 0; +} + +} // namespace + +struct BootstrapStore::State { + InitialEpochClaim claim; + UniqueFd root_fd; + UniqueFd child_fd; + struct stat root_stat {}; + struct stat child_stat {}; + struct stat intent_stat {}; + bool intent_identity_valid{}; + std::string child_name; + std::shared_ptr committed; + std::array digest{}; + std::string committed_bytes; + IBootstrapStoreIo* test_io{}; + mutable std::mutex mutex; + bool busy{}; + bool writable{}; + bool storage_uncertain{}; + BootstrapVisibility last_visibility{BootstrapVisibility::NotVisible}; + + explicit State(InitialEpochClaim value) : claim(std::move(value)) {} +}; + +namespace { + +BootstrapStoreError CheckLocation(BootstrapStore::State& state) noexcept { + if (Fail(state.test_io, BootstrapStoreIoPoint::CheckOwner)) return BootstrapStoreError::OwnerLost; + const auto ownership = state.claim.ValidateOwnership(); + if (std::holds_alternative(ownership)) return BootstrapStoreError::OwnerLost; + if (Fail(state.test_io, BootstrapStoreIoPoint::CheckRoot)) return BootstrapStoreError::InvalidRoot; + struct stat current_root{}; + if (::fstat(state.root_fd.get(), ¤t_root) != 0 || !ValidOwnedDir(current_root) || + !SameInode(current_root, state.root_stat)) return BootstrapStoreError::InvalidRoot; + if (Fail(state.test_io, BootstrapStoreIoPoint::CheckChild)) return BootstrapStoreError::InvalidChild; + struct stat child_fd{}, child_path{}; + if (::fstat(state.child_fd.get(), &child_fd) != 0 || + ::fstatat(state.root_fd.get(), state.child_name.c_str(), &child_path, AT_SYMLINK_NOFOLLOW) != 0 || + !ValidOwnedDir(child_fd) || !S_ISDIR(child_path.st_mode) || !SameInode(child_fd, state.child_stat) || + !SameInode(child_path, state.child_stat)) return BootstrapStoreError::InvalidChild; + return BootstrapStoreError::None; +} + +BootstrapStoreError CheckRootOnly(BootstrapStore::State& state) noexcept { + if (Fail(state.test_io, BootstrapStoreIoPoint::CheckOwner)) return BootstrapStoreError::OwnerLost; + if (std::holds_alternative(state.claim.ValidateOwnership())) + return BootstrapStoreError::OwnerLost; + if (Fail(state.test_io, BootstrapStoreIoPoint::CheckRoot)) return BootstrapStoreError::InvalidRoot; + struct stat current_root{}; + if (::fstat(state.root_fd.get(), ¤t_root) != 0 || !ValidOwnedDir(current_root) || + !SameInode(current_root, state.root_stat)) return BootstrapStoreError::InvalidRoot; + return BootstrapStoreError::None; +} + +struct PersistResult final { + BootstrapVisibility visibility{BootstrapVisibility::NotVisible}; + BootstrapStoreError error{BootstrapStoreError::None}; +}; + +PersistResult NotPersisted(BootstrapStoreError error) noexcept { + return {BootstrapVisibility::NotVisible, error}; +} + +BootstrapStoreError ReadIntent(BootstrapStore::State& state, std::string& bytes, + struct stat* final_identity = nullptr) noexcept { + try { + auto checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return checked; + if (Fail(state.test_io, BootstrapStoreIoPoint::CheckCurrentFile)) return BootstrapStoreError::InvalidIntent; + struct stat path_stat{}; + if (::fstatat(state.child_fd.get(), kIntentName, &path_stat, AT_SYMLINK_NOFOLLOW) != 0 || + !ValidIntentFile(path_stat)) return BootstrapStoreError::InvalidIntent; + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return checked; + UniqueFd file(::openat(state.child_fd.get(), kIntentName, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (file.get() < 0) return BootstrapStoreError::InvalidIntent; + struct stat fd_stat{}, entry_stat{}; + if (::fstat(file.get(), &fd_stat) != 0 || !ValidIntentFile(fd_stat) || + !SameInode(fd_stat, path_stat) || + ::fstatat(state.child_fd.get(), kIntentName, &entry_stat, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(fd_stat, entry_stat)) return BootstrapStoreError::InvalidIntent; + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return checked; + if (Fail(state.test_io, BootstrapStoreIoPoint::ReadCurrentFile)) return BootstrapStoreError::IoFailure; + if (!ReadAll(file.get(), bytes, static_cast(fd_stat.st_size))) return BootstrapStoreError::IoFailure; + struct stat after_fd{}, after_path{}; + if (::fstat(file.get(), &after_fd) != 0 || + ::fstatat(state.child_fd.get(), kIntentName, &after_path, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(after_fd, after_path) || !SameInode(after_fd, path_stat) || !ValidIntentFile(after_fd)) + return BootstrapStoreError::InvalidIntent; + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return checked; + if (!CloseChecked(file)) return BootstrapStoreError::IoFailure; + if (final_identity != nullptr) *final_identity = after_fd; + return BootstrapStoreError::None; + } catch (...) { return BootstrapStoreError::AllocationFailure; } +} + +PersistResult AtomicReplace(BootstrapStore::State& state, std::string_view bytes, + bool require_existing) noexcept { + auto checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return NotPersisted(checked); + if (require_existing) { + std::string old_bytes; + struct stat old_identity{}; + const auto read_result = ReadIntent(state, old_bytes, &old_identity); + if (read_result != BootstrapStoreError::None) return NotPersisted(read_result); + if (old_bytes != state.committed_bytes || !state.intent_identity_valid || + !SameInode(old_identity, state.intent_stat)) return NotPersisted(BootstrapStoreError::StorageUncertain); + } else { + struct stat existing{}; + if (::fstatat(state.child_fd.get(), kIntentName, &existing, AT_SYMLINK_NOFOLLOW) == 0 || errno != ENOENT) + return NotPersisted(BootstrapStoreError::InvalidIntent); + } + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return NotPersisted(checked); + if (Fail(state.test_io, BootstrapStoreIoPoint::CreateTemp)) return NotPersisted(BootstrapStoreError::IoFailure); + UniqueFd temp(::openat(state.child_fd.get(), kTempName, + O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, 0600)); + if (temp.get() < 0) return NotPersisted(BootstrapStoreError::IoFailure); + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return NotPersisted(checked); + struct stat temp_stat{}, temp_path{}; + if (::fchmod(temp.get(), 0600) != 0 || ::fstat(temp.get(), &temp_stat) != 0 || + !ValidIntentFile(temp_stat) || + ::fstatat(state.child_fd.get(), kTempName, &temp_path, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(temp_stat, temp_path)) return NotPersisted(BootstrapStoreError::IoFailure); + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return NotPersisted(checked); + if (Fail(state.test_io, BootstrapStoreIoPoint::WriteTemp) || + !WriteAll(temp.get(), bytes.data(), bytes.size())) return NotPersisted(BootstrapStoreError::IoFailure); + struct stat written_fd{}, written_path{}; + if (::fstat(temp.get(), &written_fd) != 0 || !ValidIntentFile(written_fd) || + static_cast(written_fd.st_size) != bytes.size() || + ::fstatat(state.child_fd.get(), kTempName, &written_path, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(written_fd, written_path)) return NotPersisted(BootstrapStoreError::IoFailure); + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return NotPersisted(checked); + if (Fail(state.test_io, BootstrapStoreIoPoint::SyncTemp) || !Sync(temp.get())) + return NotPersisted(BootstrapStoreError::IoFailure); + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return NotPersisted(checked); + if (Fail(state.test_io, BootstrapStoreIoPoint::CloseTemp) || !CloseChecked(temp)) + return NotPersisted(BootstrapStoreError::IoFailure); + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return NotPersisted(checked); + if (Fail(state.test_io, BootstrapStoreIoPoint::RenameTemp)) + return NotPersisted(BootstrapStoreError::IoFailure); + // Revalidate the target after temp fsync/close and immediately before the + // rename so a changed file is never silently overwritten. + if (require_existing) { + std::string latest; + struct stat latest_identity{}; + const auto latest_result = ReadIntent(state, latest, &latest_identity); + if (latest_result != BootstrapStoreError::None || latest != state.committed_bytes || + !SameInode(latest_identity, state.intent_stat)) return NotPersisted( + latest_result == BootstrapStoreError::None ? BootstrapStoreError::StorageUncertain : latest_result); + } else { + struct stat target{}; + if (::fstatat(state.child_fd.get(), kIntentName, &target, AT_SYMLINK_NOFOLLOW) == 0 || errno != ENOENT) + return NotPersisted(BootstrapStoreError::InvalidIntent); + } + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) return NotPersisted(checked); + if (require_existing) { + // The runtime root is held by one trusted owner. Revalidate the exact old + // file immediately before this atomic replacement; hostile same-UID + // concurrent writers are outside the runtime-owner trust model. + if (::renameat(state.child_fd.get(), kTempName, state.child_fd.get(), kIntentName) != 0) + return NotPersisted(BootstrapStoreError::IoFailure); + } else { + // linkat provides POSIX no-replace publication. The temporary second link + // is removed before directory fsync; any failure after link visibility is + // reported as VisibleDurabilityUnknown and permanently blocks readiness. + if (::linkat(state.child_fd.get(), kTempName, state.child_fd.get(), kIntentName, 0) != 0) + return NotPersisted(BootstrapStoreError::IoFailure); + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) + return {BootstrapVisibility::VisibleDurabilityUnknown, checked}; + struct stat temp_link{}, intent_link{}; + if (::fstatat(state.child_fd.get(), kTempName, &temp_link, AT_SYMLINK_NOFOLLOW) != 0 || + ::fstatat(state.child_fd.get(), kIntentName, &intent_link, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(temp_link, intent_link) || !S_ISREG(temp_link.st_mode) || temp_link.st_nlink != 2) + return {BootstrapVisibility::VisibleDurabilityUnknown, BootstrapStoreError::InvalidIntent}; + if (::unlinkat(state.child_fd.get(), kTempName, 0) != 0) + return {BootstrapVisibility::VisibleDurabilityUnknown, BootstrapStoreError::DurabilityUncertain}; + } + checked = CheckLocation(state); + if (checked != BootstrapStoreError::None) + return {BootstrapVisibility::VisibleDurabilityUnknown, checked}; + if (Fail(state.test_io, BootstrapStoreIoPoint::SyncChild) || !Sync(state.child_fd.get())) + return {BootstrapVisibility::VisibleDurabilityUnknown, BootstrapStoreError::DurabilityUncertain}; + std::string verify; + struct stat new_identity{}; + const auto read_result = ReadIntent(state, verify, &new_identity); + if (read_result != BootstrapStoreError::None) + return {BootstrapVisibility::VisibleDurabilityUnknown, read_result}; + if (verify != bytes) return {BootstrapVisibility::VisibleDurabilityUnknown, BootstrapStoreError::DurabilityUncertain}; + state.intent_stat = new_identity; + state.intent_identity_valid = true; + return {BootstrapVisibility::Durable, BootstrapStoreError::None}; +} + +void MarkUnwritable(BootstrapStore::State& state, BootstrapVisibility visibility) noexcept { + std::lock_guard lock(state.mutex); + state.writable = false; + state.storage_uncertain = true; + state.last_visibility = visibility; + state.busy = false; +} + +} // namespace + +BootstrapStore::BootstrapStore(std::unique_ptr state) noexcept : state_(std::move(state)) {} +BootstrapStore::~BootstrapStore() = default; + +BootstrapStoreOpenResult BootstrapStore::CreateNew(InitialEpochClaim claim, const BootstrapPlan& plan, + IBootstrapStoreIo* test_io) noexcept { + const auto failure = [](BootstrapStoreError error, + BootstrapVisibility visibility = BootstrapVisibility::NotVisible) { + return BootstrapStoreOpenResult{nullptr, visibility, error}; + }; + try { + if (std::holds_alternative(claim.ValidateOwnership())) + return failure(BootstrapStoreError::InvalidClaim); + if (plan.domain_id != claim.domain_id()) return failure(BootstrapStoreError::DomainMismatch); + if (plan.epoch_id != claim.epoch_id()) return failure(BootstrapStoreError::EpochMismatch); + auto model = BootstrapInventory::Create(plan); + if (std::holds_alternative(model)) + return failure(BootstrapStoreError::InvalidPlan); + const auto encoded = EncodeBootstrapInventoryV1(std::get(model)); + if (const auto* error = std::get_if(&encoded)) + return failure(*error == BootstrapError::AllocationFailure ? BootstrapStoreError::AllocationFailure : BootstrapStoreError::InvalidPlan); + const std::string bytes = std::get(encoded); + const auto digest_result = BootstrapDigestV1(std::get(model)); + if (const auto* error = std::get_if(&digest_result)) + return failure(*error == BootstrapError::AllocationFailure ? BootstrapStoreError::AllocationFailure : BootstrapStoreError::InvalidPlan); + auto child_name_result = epoch_layout_v1::FormatEpochDirectoryName(plan.epoch_id); + if (const auto* error = std::get_if(&child_name_result)) + return failure(*error == epoch_layout_v1::LayoutError::AllocationFailure + ? BootstrapStoreError::AllocationFailure + : BootstrapStoreError::InvalidPlan); + + auto state = std::make_unique(std::move(claim)); + state->test_io = test_io; + state->child_name = std::get(std::move(child_name_result)); + state->committed = std::make_shared(std::get(model)); + state->digest = std::get>(digest_result); + state->committed_bytes = bytes; + auto root_dup = state->claim.DuplicateRootFd(); + if (const auto* error = std::get_if(&root_dup)) { + (void)error; return failure(BootstrapStoreError::InvalidClaim); + } + state->root_fd = UniqueFd(std::get(root_dup)); + if (::fstat(state->root_fd.get(), &state->root_stat) != 0 || !ValidOwnedDir(state->root_stat)) + return failure(BootstrapStoreError::InvalidRoot); + auto store = std::unique_ptr(new BootstrapStore(std::move(state))); + auto& store_state = *store->state_; + auto check = CheckRootOnly(store_state); + if (check != BootstrapStoreError::None) return failure(check); + if (Fail(test_io, BootstrapStoreIoPoint::MakeChild)) return failure(BootstrapStoreError::IoFailure); + if (::mkdirat(store_state.root_fd.get(), store_state.child_name.c_str(), 0700) != 0) + return failure(errno == EEXIST ? BootstrapStoreError::ExistingEpoch : BootstrapStoreError::IoFailure); + check = CheckRootOnly(store_state); + if (check != BootstrapStoreError::None) return failure(check); + if (Fail(test_io, BootstrapStoreIoPoint::SyncRootAfterMkdir) || !Sync(store_state.root_fd.get())) + return failure(BootstrapStoreError::DurabilityUncertain); + check = CheckRootOnly(store_state); + if (check != BootstrapStoreError::None) return failure(check); + if (Fail(test_io, BootstrapStoreIoPoint::OpenChild)) return failure(BootstrapStoreError::IoFailure); + store_state.child_fd = UniqueFd(::openat(store_state.root_fd.get(), store_state.child_name.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)); + if (store_state.child_fd.get() < 0 || ::fstat(store_state.child_fd.get(), &store_state.child_stat) != 0 || + !ValidOwnedDir(store_state.child_stat)) return failure(BootstrapStoreError::InvalidChild); + struct stat child_path{}; + if (::fstatat(store_state.root_fd.get(), store_state.child_name.c_str(), &child_path, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(child_path, store_state.child_stat)) return failure(BootstrapStoreError::InvalidChild); + check = CheckLocation(store_state); + if (check != BootstrapStoreError::None) return failure(check); + if (::fchmod(store_state.child_fd.get(), 0700) != 0 || + ::fstat(store_state.child_fd.get(), &store_state.child_stat) != 0 || + !ValidOwnedDir(store_state.child_stat)) return failure(BootstrapStoreError::InvalidChild); + check = CheckLocation(store_state); + if (check != BootstrapStoreError::None) return failure(check); + const auto written = AtomicReplace(store_state, bytes, false); + if (written.error != BootstrapStoreError::None) + return failure(written.error, written.visibility); + store_state.writable = true; + store_state.last_visibility = BootstrapVisibility::Durable; + return {std::move(store), BootstrapVisibility::Durable, BootstrapStoreError::None}; + } catch (...) { return failure(BootstrapStoreError::AllocationFailure); } +} + +std::shared_ptr BootstrapStore::Snapshot() const noexcept { + std::lock_guard lock(state_->mutex); + return state_->committed; +} + +BootstrapStoreUpdate BootstrapStore::RecordIdentity( + std::uint64_t expected_revision, const std::array& expected_digest, + const ObservedBootstrapIdentity& observed) noexcept { + std::shared_ptr current; + { + std::lock_guard lock(state_->mutex); + if (state_->busy) return {state_->committed, BootstrapVisibility::NotVisible, + BootstrapStoreError::Busy, BootstrapError::None}; + if (!state_->writable || state_->storage_uncertain) + return {state_->committed, state_->last_visibility, + BootstrapStoreError::StorageUncertain, BootstrapError::None}; + current = state_->committed; + if (current->revision() != expected_revision || state_->digest != expected_digest) + return {current, BootstrapVisibility::NotVisible, BootstrapStoreError::Conflict, BootstrapError::None}; + state_->busy = true; + } + auto finish_error = [&](BootstrapStoreError error, BootstrapError transition = BootstrapError::None, + BootstrapVisibility visibility = BootstrapVisibility::NotVisible) { + if (error != BootstrapStoreError::Conflict && error != BootstrapStoreError::Busy) + MarkUnwritable(*state_, visibility); + else { std::lock_guard lock(state_->mutex); state_->busy = false; } + return BootstrapStoreUpdate{Snapshot(), visibility, error, transition}; + }; + try { + if (std::holds_alternative(state_->claim.ValidateOwnership())) + return finish_error(BootstrapStoreError::OwnerLost); + const auto applied = current->RecordIdentity(observed); + const auto encoded = EncodeBootstrapInventoryV1(applied.next); + if (const auto* error = std::get_if(&encoded)) + return finish_error(*error == BootstrapError::AllocationFailure ? BootstrapStoreError::AllocationFailure : BootstrapStoreError::InvalidIntent, + applied.status); + const auto bytes = std::get(encoded); + const auto digest_result = BootstrapDigestV1(applied.next); + if (const auto* error = std::get_if(&digest_result)) + return finish_error(*error == BootstrapError::AllocationFailure ? BootstrapStoreError::AllocationFailure : BootstrapStoreError::InvalidIntent, + applied.status); + const auto digest = std::get>(digest_result); + if (bytes == state_->committed_bytes) { + std::string on_disk; + const auto read = ReadIntent(*state_, on_disk); + if (read != BootstrapStoreError::None || on_disk != bytes) + return finish_error(read == BootstrapStoreError::None ? BootstrapStoreError::StorageUncertain : read, + applied.status, BootstrapVisibility::NotVisible); + std::lock_guard lock(state_->mutex); + state_->busy = false; + state_->last_visibility = BootstrapVisibility::Durable; + return {current, BootstrapVisibility::Durable, BootstrapStoreError::None, applied.status}; + } + auto next = std::make_shared(applied.next); + auto published = next; + std::string committed_bytes = bytes; + const auto written = AtomicReplace(*state_, bytes, true); + if (written.error != BootstrapStoreError::None) + return finish_error(written.error, applied.status, written.visibility); + { + std::lock_guard lock(state_->mutex); + state_->committed = std::move(next); + state_->digest = digest; + state_->committed_bytes = std::move(committed_bytes); + state_->last_visibility = BootstrapVisibility::Durable; + state_->busy = false; + } + return {std::move(published), BootstrapVisibility::Durable, BootstrapStoreError::None, applied.status}; + } catch (...) { return finish_error(BootstrapStoreError::StorageUncertain); } +} + +BootstrapCandidateResult BootstrapStore::ReadyCandidate() noexcept { + { + std::lock_guard lock(state_->mutex); + if (state_->busy) return BootstrapStoreError::Busy; + if (!state_->writable || state_->storage_uncertain) return BootstrapStoreError::StorageUncertain; + state_->busy = true; + } + auto finish = [&](BootstrapStoreError error) -> BootstrapCandidateResult { + if (error == BootstrapStoreError::RecoveryRequired || error == BootstrapStoreError::IncompleteRoster) { + std::lock_guard lock(state_->mutex); + state_->busy = false; + } else if (error != BootstrapStoreError::None) MarkUnwritable(*state_, BootstrapVisibility::NotVisible); + else { std::lock_guard lock(state_->mutex); state_->busy = false; } + return error; + }; + try { + if (state_->committed->recovery_required()) return finish(BootstrapStoreError::RecoveryRequired); + if (std::holds_alternative(state_->claim.ValidateOwnership())) + return finish(BootstrapStoreError::OwnerLost); + std::string on_disk; + const auto read = ReadIntent(*state_, on_disk); + if (read != BootstrapStoreError::None) return finish(read); + if (on_disk != state_->committed_bytes) return finish(BootstrapStoreError::StorageUncertain); + const auto decoded = DecodeBootstrapInventoryV1(on_disk); + if (const auto* error = std::get_if(&decoded)) { + (void)error; return finish(BootstrapStoreError::InvalidIntent); + } + const auto& disk = std::get(decoded); + const auto disk_digest = BootstrapDigestV1(disk); + if (const auto* error = std::get_if(&disk_digest)) { + (void)error; return finish(BootstrapStoreError::InvalidIntent); + } + if (std::get>(disk_digest) != state_->digest || + disk.domain_id() != state_->claim.domain_id() || disk.epoch_id() != state_->claim.epoch_id()) + return finish(BootstrapStoreError::InvalidIntent); + auto candidate = state_->committed->ReadyCandidate(); + if (const auto* error = std::get_if(&candidate)) { + if (*error == BootstrapError::RecoveryRequired) return finish(BootstrapStoreError::RecoveryRequired); + if (*error == BootstrapError::IncompleteRoster) return finish(BootstrapStoreError::IncompleteRoster); + return finish(BootstrapStoreError::InvalidPlan); + } + auto ready = std::get(std::move(candidate)); + BootstrapCandidateResult result(std::in_place_type, std::move(ready)); + { std::lock_guard lock(state_->mutex); state_->busy = false; } + return result; + } catch (...) { return finish(BootstrapStoreError::StorageUncertain); } +} + +} // namespace rateguard::supervisor diff --git a/src/supervisor/bootstrap_store.h b/src/supervisor/bootstrap_store.h new file mode 100644 index 0000000..58aab67 --- /dev/null +++ b/src/supervisor/bootstrap_store.h @@ -0,0 +1,109 @@ +#pragma once + +#include "supervisor/bootstrap_inventory.h" +#include "supervisor/runtime_owner.h" + +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +enum class BootstrapStoreIoPoint : std::uint8_t { + CheckOwner, + CheckRoot, + CheckChild, + MakeChild, + SyncRootAfterMkdir, + OpenChild, + CheckCurrentFile, + ReadCurrentFile, + CreateTemp, + WriteTemp, + SyncTemp, + CloseTemp, + RenameTemp, + SyncChild, +}; + +class IBootstrapStoreIo { + public: + virtual ~IBootstrapStoreIo() = default; + [[nodiscard]] virtual bool FailAt(BootstrapStoreIoPoint point) noexcept = 0; +}; + +enum class BootstrapStoreError : std::uint8_t { + None, + InvalidClaim, + DomainMismatch, + EpochMismatch, + InvalidPlan, + ExistingEpoch, + InvalidRoot, + InvalidChild, + InvalidIntent, + OwnerLost, + Busy, + Conflict, + RecoveryRequired, + IncompleteRoster, + IoFailure, + DurabilityUncertain, + StorageUncertain, + AllocationFailure, +}; + +enum class BootstrapVisibility : std::uint8_t { NotVisible, Durable, VisibleDurabilityUnknown }; + +struct BootstrapStoreUpdate final { + std::shared_ptr snapshot; + BootstrapVisibility visibility{BootstrapVisibility::NotVisible}; + BootstrapStoreError store_error{BootstrapStoreError::None}; + BootstrapError transition_status{BootstrapError::None}; +}; + +struct BootstrapStoreOpenResult final { + std::unique_ptr store; + BootstrapVisibility visibility{BootstrapVisibility::NotVisible}; + BootstrapStoreError error{BootstrapStoreError::None}; + [[nodiscard]] bool ok() const noexcept { return store != nullptr && error == BootstrapStoreError::None; } +}; +using BootstrapCandidateResult = std::variant; + +// Initial-epoch-only durable bootstrap store. There is intentionally no API to +// open an existing intent for serving or to infer process-start evidence. +class BootstrapStore final { + public: + struct State; // Opaque implementation state; exposed only for private helpers. + BootstrapStore(const BootstrapStore&) = delete; + BootstrapStore& operator=(const BootstrapStore&) = delete; + ~BootstrapStore(); + + // Takes ownership of `claim`; it is consumed on success or failure. + [[nodiscard]] static BootstrapStoreOpenResult CreateNew( + InitialEpochClaim claim, const BootstrapPlan& plan, + IBootstrapStoreIo* test_io = nullptr) noexcept; + + // Returns the last fully durable in-memory snapshot without file I/O. + [[nodiscard]] std::shared_ptr Snapshot() const noexcept; + + // CAS by durable revision and canonical payload digest. A mismatch is a + // conflict and does not poison a healthy store. Store publication follows + // successful atomic replacement and fsync; uncertain writes make it unready. + [[nodiscard]] BootstrapStoreUpdate RecordIdentity( + std::uint64_t expected_revision, const std::array& expected_digest, + const ObservedBootstrapIdentity& observed) noexcept; + + // Pure data handoff after ownership and on-disk validation. This does not + // activate participants or establish actual process-control evidence. + [[nodiscard]] BootstrapCandidateResult ReadyCandidate() noexcept; + + private: + explicit BootstrapStore(std::unique_ptr state) noexcept; + std::unique_ptr state_; +}; + +} // namespace rateguard::supervisor diff --git a/src/supervisor/epoch_artifact_layout.h b/src/supervisor/epoch_artifact_layout.h new file mode 100644 index 0000000..d461d3a --- /dev/null +++ b/src/supervisor/epoch_artifact_layout.h @@ -0,0 +1,90 @@ +#pragma once + +// Pure v1 names and codecs for artifacts inside one supervisor runtime root: +// epoch-/intent.json, optionally epoch-/manifest-store/{owner.lock, +// manifest.json}. `intent.tmp` and `manifest.tmp` are transient artifacts and +// indicate an uncertain/incomplete recovery scan. No witness or journal names +// are recognized in v1. This header performs no filesystem access and grants +// no ownership/fencing authority. + +#include "supervisor/epoch_gate.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor::epoch_layout_v1 { + +inline constexpr char kEpochDirectoryPrefix[] = "epoch-"; +inline constexpr char kIntentFileName[] = "intent.json"; +inline constexpr char kIntentTemporaryFileName[] = "intent.tmp"; +inline constexpr char kManifestStoreDirectoryName[] = "manifest-store"; +inline constexpr char kManifestStoreLockFileName[] = "owner.lock"; +inline constexpr char kManifestFileName[] = "manifest.json"; +inline constexpr char kManifestTemporaryFileName[] = "manifest.tmp"; + +enum class LayoutError : std::uint8_t { + ZeroEpochId, + AllocationFailure, +}; + +[[nodiscard]] inline bool IsZeroEpochId(const EpochId& id) noexcept { + for (const auto byte : id) { + if (byte != 0) return false; + } + return true; +} + +[[nodiscard]] inline int HexNibble(char value) noexcept { + if (value >= '0' && value <= '9') return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + return -1; +} + +// Accepts exactly the shared BootstrapStore/BootstrapRecoveryReader grammar: +// `epoch-` followed by 32 lowercase hexadecimal digits, encoding nonzero ID. +[[nodiscard]] inline std::optional ParseEpochDirectoryName( + std::string_view name) noexcept { + constexpr std::size_t kPrefixLength = sizeof(kEpochDirectoryPrefix) - 1; + constexpr std::size_t kCanonicalLength = kPrefixLength + 32; + if (name.size() != kCanonicalLength || + name.substr(0, kPrefixLength) != kEpochDirectoryPrefix) { + return std::nullopt; + } + + EpochId epoch{}; + for (std::size_t i = 0; i < epoch.size(); ++i) { + const int high = HexNibble(name[kPrefixLength + (2 * i)]); + const int low = HexNibble(name[kPrefixLength + (2 * i) + 1]); + if (high < 0 || low < 0) return std::nullopt; + epoch[i] = static_cast((high << 4) | low); + } + if (IsZeroEpochId(epoch)) return std::nullopt; + return epoch; +} + +[[nodiscard]] inline std::variant FormatEpochDirectoryName( + const EpochId& epoch) noexcept { + if (IsZeroEpochId(epoch)) return LayoutError::ZeroEpochId; + constexpr char kHex[] = "0123456789abcdef"; + constexpr std::size_t kPrefixLength = sizeof(kEpochDirectoryPrefix) - 1; + constexpr std::size_t kCanonicalLength = kPrefixLength + 32; + try { + std::string name; + name.reserve(kCanonicalLength); + name.append(kEpochDirectoryPrefix, kPrefixLength); + for (const auto byte : epoch) { + name.push_back(kHex[(byte >> 4) & 0x0f]); + name.push_back(kHex[byte & 0x0f]); + } + return name; + } catch (...) { + return LayoutError::AllocationFailure; + } +} + +} // namespace rateguard::supervisor::epoch_layout_v1 diff --git a/src/supervisor/epoch_gate.h b/src/supervisor/epoch_gate.h new file mode 100644 index 0000000..12fc033 --- /dev/null +++ b/src/supervisor/epoch_gate.h @@ -0,0 +1,396 @@ +#pragma once + +// Local, single-epoch lifecycle gate. This component is not a durable +// supervisor and cannot authorize a successor epoch by itself. + +#include "platform/clock.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +inline constexpr std::size_t kMaxReplicaSlots = 8; +// Proposed implementation resource cap; not a PRD/SRD participant-count +// guarantee. Inventories above this cap are rejected before internal state allocation. +inline constexpr std::size_t kMaxParticipants = 1024; + +using EpochId = std::array; +using IncarnationId = std::array; +using PolicyDigest = std::array; +using OperationId = std::array; + +enum class ParticipantRole : std::uint8_t { Authority, Replica, Adapter, Witness }; +enum class ProcessState : std::uint8_t { Running, Exited, Unknown }; +enum class EpochPhase : std::uint8_t { PreActivation, Active, Draining, Closed }; +enum class DrainCause : std::uint8_t { Requested, AuthorityFailure, IntegrityFailure, ClockFailure }; + +struct ProcessIdentity { + // Runtime/container identifier is a canonical lower-case 64-digit hex value. + std::string container_id; + // Host PID, paired with the kernel PID start-time identity below. + std::uint64_t pid{}; + std::uint64_t pid_start_ticks{}; + friend bool operator==(const ProcessIdentity&, const ProcessIdentity&) = default; +}; + +struct Participant { + ParticipantRole role{}; + // Non-replica participants use slot_id == 0. Replica IDs are fixed by policy + // and may be any uint32 value; at most eight replica entries are accepted. + std::uint32_t slot_id{}; + // Stable inventory key within a role; permits multiple fixed adapters. + std::string participant_id; + IncarnationId incarnation{}; + ProcessIdentity process; + platform::ClockIdentity clock_identity{}; + friend bool operator==(const Participant&, const Participant&) = default; +}; + +struct EpochCandidate { + EpochId epoch_id{}; + IncarnationId authority_incarnation{}; + PolicyDigest policy_digest{}; + platform::ClockIdentity clock_identity{}; + std::vector participants; + friend bool operator==(const EpochCandidate&, const EpochCandidate&) = default; +}; + +enum class ControllerError : std::uint8_t { Unavailable, TimedOut, InvalidEvidence, Internal }; +struct StopAck { + OperationId operation_id{}; +}; +struct ProcessObservation { + Participant participant; + ProcessState state{ProcessState::Unknown}; +}; + +class IProcessController { + public: + virtual ~IProcessController() = default; + // Implementations must bind each response to the full expected identity. + // Calls can block or throw; EpochGate never holds its mutex across them. + virtual std::variant RequestStop( + const Participant& expected, const OperationId& operation_id) = 0; + virtual std::variant Inspect( + const Participant& expected) = 0; +}; + +enum class GateError : std::uint8_t { + InvalidCandidate, + TooManyParticipants, + InvalidInventory, + WrongEpoch, + WrongPhase, + Busy, + ControllerFailure, + IdentityMismatch, + NotRunning, + NotExited, + WrongOperation, + InFlightCommit, + AllocationFailure, +}; +using GateResult = std::variant; +using GateCreateResult = std::variant, GateError>; + +namespace detail { +struct GateState { + mutable std::mutex mutex; + EpochPhase phase{EpochPhase::PreActivation}; + std::size_t active_commits{}; + bool lifecycle_io_in_progress{}; + std::optional drain_operation; + DrainCause drain_cause{DrainCause::Requested}; +}; + +inline bool AllZero(const auto& bytes) noexcept { + return std::all_of(bytes.begin(), bytes.end(), [](std::uint8_t b) { return b == 0; }); +} + +inline bool CanonicalContainerId(const std::string& value) noexcept { + if (value.size() != 64) return false; + for (unsigned char c : value) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; + } + return true; +} + +inline bool ValidParticipant(const Participant& p, const EpochCandidate& c) noexcept { + if (p.participant_id.empty() || p.participant_id.size() > 64 || + !std::all_of(p.participant_id.begin(), p.participant_id.end(), [](unsigned char ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_'; + }) || !CanonicalContainerId(p.process.container_id) || p.process.pid == 0 || + p.process.pid_start_ticks == 0 || !(p.clock_identity == c.clock_identity)) return false; + switch (p.role) { + case ParticipantRole::Authority: + return p.slot_id == 0 && p.incarnation == c.authority_incarnation; + case ParticipantRole::Replica: + return !AllZero(p.incarnation); + case ParticipantRole::Adapter: + case ParticipantRole::Witness: + return p.slot_id == 0 && !AllZero(p.incarnation); + } + return false; +} +} // namespace detail + +// Pure bounded validation shared by lifecycle startup and durable manifest decoding. +[[nodiscard]] inline std::optional ValidateEpochCandidate( + const EpochCandidate& candidate) noexcept { + if (candidate.participants.size() > kMaxParticipants) return GateError::TooManyParticipants; + if (detail::AllZero(candidate.epoch_id) || detail::AllZero(candidate.authority_incarnation) || + detail::AllZero(candidate.policy_digest) || candidate.participants.empty()) + return GateError::InvalidCandidate; + std::size_t authorities = 0, witnesses = 0, adapters = 0; + std::size_t replicas = 0; + for (std::size_t i = 0; i < candidate.participants.size(); ++i) { + const auto& p = candidate.participants[i]; + if (!detail::ValidParticipant(p, candidate)) return GateError::InvalidInventory; + if (p.role == ParticipantRole::Authority) ++authorities; + if (p.role == ParticipantRole::Witness) ++witnesses; + if (p.role == ParticipantRole::Adapter) ++adapters; + if (p.role == ParticipantRole::Replica) ++replicas; + for (std::size_t j = 0; j < i; ++j) { + const auto& q = candidate.participants[j]; + if (p.process.container_id == q.process.container_id || p.process.pid == q.process.pid) + return GateError::InvalidInventory; + if (p.role == q.role && p.participant_id == q.participant_id) + return GateError::InvalidInventory; + if (p.role == ParticipantRole::Replica && q.role == ParticipantRole::Replica && + p.slot_id == q.slot_id) return GateError::InvalidInventory; + } + } + if (authorities != 1 || witnesses != 1 || adapters == 0 || replicas == 0 || + replicas > kMaxReplicaSlots) return GateError::InvalidInventory; + return std::nullopt; +} + +class CommitLease { + public: + CommitLease(const CommitLease&) = delete; + CommitLease& operator=(const CommitLease&) = delete; + CommitLease(CommitLease&& other) noexcept : state_(std::move(other.state_)) {} + CommitLease& operator=(CommitLease&& other) noexcept { + if (this != &other) { + Release(); + state_ = std::move(other.state_); + } + return *this; + } + ~CommitLease() { Release(); } + + private: + friend class EpochGate; + explicit CommitLease(std::shared_ptr state) : state_(std::move(state)) {} + void Release() noexcept { + if (!state_) return; + auto owner = std::move(state_); + { + std::lock_guard lock(owner->mutex); + if (owner->active_commits > 0) --owner->active_commits; + } + } + std::shared_ptr state_; +}; + +class EpochGate { + public: + EpochGate(const EpochGate&) = delete; + EpochGate& operator=(const EpochGate&) = delete; + + [[nodiscard]] static GateCreateResult Create(const EpochCandidate& candidate, + IProcessController& controller) noexcept { + if (const auto error = ValidateEpochCandidate(candidate)) return *error; + try { + auto shared_candidate = std::make_shared(candidate); + auto state = std::make_shared(); + return std::shared_ptr(new EpochGate(std::move(shared_candidate), controller, + std::move(state))); + } catch (...) { + return GateError::AllocationFailure; + } + } + + [[nodiscard]] EpochPhase phase() const noexcept { + std::lock_guard lock(state_->mutex); + return state_->phase; + } + [[nodiscard]] const EpochCandidate& candidate() const noexcept { return *candidate_; } + + // Readiness is local to this fixed inventory. Success is not successor-epoch + // authorization and does not establish durable manifest or clock provenance. + [[nodiscard]] GateResult Activate() noexcept { + { + std::lock_guard lock(state_->mutex); + if (state_->phase != EpochPhase::PreActivation) return GateError::WrongPhase; + if (state_->lifecycle_io_in_progress) return GateError::Busy; + state_->lifecycle_io_in_progress = true; + } + GateError failure = GateError::ControllerFailure; + bool ok = true; + for (const auto& p : candidate_->participants) { + try { + auto result = controller_.Inspect(p); + if (auto* err = std::get_if(&result)) { + (void)err; ok = false; break; + } + const auto& obs = std::get(result); + if (!(obs.participant == p)) { failure = GateError::IdentityMismatch; ok = false; break; } + if (obs.state != ProcessState::Running) { failure = GateError::NotRunning; ok = false; break; } + } catch (...) { ok = false; break; } + } + { + std::lock_guard lock(state_->mutex); + state_->lifecycle_io_in_progress = false; + if (ok) state_->phase = EpochPhase::Active; + } + return ok ? GateResult{std::monostate{}} : GateResult{failure}; + } + + [[nodiscard]] std::variant TryAcquireCommitPermit( + const EpochId& expected_epoch) noexcept { + std::lock_guard lock(state_->mutex); + if (expected_epoch != candidate_->epoch_id) return GateError::WrongEpoch; + if (state_->phase != EpochPhase::Active) return GateError::WrongPhase; + if (state_->active_commits == std::numeric_limits::max()) + return GateError::Busy; + ++state_->active_commits; + return CommitLease(state_); + } + + [[nodiscard]] GateResult BeginDrain(const OperationId& operation_id, DrainCause cause) noexcept { + if (detail::AllZero(operation_id)) return GateError::WrongOperation; + std::lock_guard lock(state_->mutex); + if (state_->lifecycle_io_in_progress) return GateError::Busy; + if (state_->phase == EpochPhase::Closed) { + return state_->drain_operation && *state_->drain_operation == operation_id + ? GateResult{std::monostate{}} : GateResult{GateError::WrongOperation}; + } + if (state_->phase == EpochPhase::Draining) { + return state_->drain_operation && *state_->drain_operation == operation_id + ? GateResult{std::monostate{}} : GateResult{GateError::WrongOperation}; + } + if (state_->phase != EpochPhase::Active && state_->phase != EpochPhase::PreActivation) + return GateError::WrongPhase; + state_->phase = EpochPhase::Draining; + state_->drain_operation = operation_id; + state_->drain_cause = cause; + return std::monostate{}; + } + + // Stops adapters and replicas first; authority/witness are untouched unless + // every ingress/replica participant is positively confirmed exited. + [[nodiscard]] GateResult FenceAndClose(const OperationId& operation_id) noexcept { + { + std::lock_guard lock(state_->mutex); + if (state_->phase == EpochPhase::Closed) { + return state_->drain_operation && *state_->drain_operation == operation_id + ? GateResult{std::monostate{}} : GateResult{GateError::WrongOperation}; + } + if (state_->phase != EpochPhase::Draining) return GateError::WrongPhase; + if (!state_->drain_operation || *state_->drain_operation != operation_id) + return GateError::WrongOperation; + if (state_->lifecycle_io_in_progress) return GateError::Busy; + if (state_->active_commits != 0) return GateError::InFlightCommit; + state_->lifecycle_io_in_progress = true; + } + + GateError failure = GateError::ControllerFailure; + bool ok = StopAndConfirmGroup(ParticipantRole::Adapter, ParticipantRole::Replica, + operation_id, failure); + if (ok) ok = StopAndConfirm(ParticipantRole::Authority, operation_id, failure) && + StopAndConfirm(ParticipantRole::Witness, operation_id, failure); + { + std::lock_guard lock(state_->mutex); + state_->lifecycle_io_in_progress = false; + if (ok) state_->phase = EpochPhase::Closed; + } + return ok ? GateResult{std::monostate{}} : GateResult{failure}; + } + + private: + EpochGate(std::shared_ptr candidate, IProcessController& controller, + std::shared_ptr state) + : candidate_(std::move(candidate)), controller_(controller), state_(std::move(state)) {} + + bool StopAndConfirm(ParticipantRole role, const OperationId& operation_id, + GateError& failure) noexcept { + for (const auto& p : candidate_->participants) { + if (p.role != role) continue; + try { + auto stop = controller_.RequestStop(p, operation_id); + if (std::holds_alternative(stop)) return false; + if (!(std::get(stop).operation_id == operation_id)) { + failure = GateError::WrongOperation; return false; + } + auto result = controller_.Inspect(p); + if (std::holds_alternative(result)) return false; + const auto& obs = std::get(result); + if (!(obs.participant == p)) { failure = GateError::IdentityMismatch; return false; } + if (obs.state != ProcessState::Exited) { failure = GateError::NotExited; return false; } + } catch (...) { + // Controller exceptions are evidence failures. The epoch stays draining. + return false; + } + } + return true; + } + + bool StopAndConfirmGroup(ParticipantRole first, ParticipantRole second, + const OperationId& operation_id, GateError& failure) noexcept { + bool requests_ok = true; + for (const auto& p : candidate_->participants) { + if (p.role != first && p.role != second) continue; + try { + auto stop = controller_.RequestStop(p, operation_id); + if (std::holds_alternative(stop)) { + requests_ok = false; + } else if (!(std::get(stop).operation_id == operation_id)) { + failure = GateError::WrongOperation; + requests_ok = false; + } + } catch (...) { + requests_ok = false; + } + } + bool exits_ok = true; + for (const auto& p : candidate_->participants) { + if (p.role != first && p.role != second) continue; + try { + auto result = controller_.Inspect(p); + if (std::holds_alternative(result)) { + exits_ok = false; + continue; + } + const auto& obs = std::get(result); + if (!(obs.participant == p)) { + failure = GateError::IdentityMismatch; + exits_ok = false; + } else if (obs.state != ProcessState::Exited) { + failure = GateError::NotExited; + exits_ok = false; + } + } catch (...) { + exits_ok = false; + } + } + return requests_ok && exits_ok; + } + + const std::shared_ptr candidate_; + IProcessController& controller_; // Must outlive this gate and its operations. + const std::shared_ptr state_; +}; + +} // namespace rateguard::supervisor diff --git a/src/supervisor/http1_parser.cpp b/src/supervisor/http1_parser.cpp new file mode 100644 index 0000000..2deb10d --- /dev/null +++ b/src/supervisor/http1_parser.cpp @@ -0,0 +1,246 @@ +#include "supervisor/http1_parser.h" + +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor::detail { +namespace { + +constexpr std::string_view kHeaderEnd = "\r\n\r\n"; +constexpr std::string_view kCrlf = "\r\n"; + +enum class BodyFraming { ContentLength, Chunked, CloseDelimited }; + +bool IsTokenChar(unsigned char c) noexcept { + if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z')) { + return true; + } + constexpr std::string_view punctuation = "!#$%&'*+-.^_`|~"; + return punctuation.find(static_cast(c)) != std::string_view::npos; +} + +char LowerAscii(char c) noexcept { + if (c >= 'A' && c <= 'Z') return static_cast(c + ('a' - 'A')); + return c; +} + +bool EqualAsciiInsensitive(std::string_view lhs, + std::string_view rhs) noexcept { + if (lhs.size() != rhs.size()) return false; + for (std::size_t i = 0; i < lhs.size(); ++i) { + if (LowerAscii(lhs[i]) != LowerAscii(rhs[i])) return false; + } + return true; +} + +std::string_view TrimOws(std::string_view value) noexcept { + while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) + value.remove_prefix(1); + while (!value.empty() && (value.back() == ' ' || value.back() == '\t')) + value.remove_suffix(1); + return value; +} + +bool ParseUnsignedDecimal(std::string_view text, + std::uint64_t& value) noexcept { + if (text.empty()) return false; + value = 0; + for (char c : text) { + if (c < '0' || c > '9') return false; + const auto digit = static_cast(c - '0'); + if (value > (std::numeric_limits::max() - digit) / 10) + return false; + value = value * 10 + digit; + } + return true; +} + +bool ParseHex(std::string_view text, std::uint64_t& value) noexcept { + if (text.empty()) return false; + value = 0; + for (char c : text) { + std::uint64_t digit; + if (c >= '0' && c <= '9') digit = static_cast(c - '0'); + else if (c >= 'a' && c <= 'f') digit = static_cast(c - 'a' + 10); + else if (c >= 'A' && c <= 'F') digit = static_cast(c - 'A' + 10); + else return false; + if (value > (std::numeric_limits::max() - digit) / 16) + return false; + value = value * 16 + digit; + } + return true; +} + +HttpParseResult Malformed() noexcept { return HttpParseError::Malformed; } +HttpParseResult TooLarge() noexcept { return HttpParseError::TooLarge; } + +} // namespace + +bool IsValidOriginFormTarget(std::string_view target) noexcept { + if (target.empty() || target.size() > kUnixHttpMaxTargetBytes || + target.front() != '/' || (target.size() > 1 && target[1] == '/')) { + return false; + } + for (unsigned char c : target) { + if (c < 0x21 || c > 0x7e || c == '#' || c == '\\') return false; + } + return true; +} + +HttpParseResult ParseHttpResponse( + std::span wire) noexcept { + try { + if (wire.size() > kUnixHttpMaxWireResponseBytes) return TooLarge(); + if (wire.empty()) return Malformed(); + const std::string_view bytes(reinterpret_cast(wire.data()), + wire.size()); + const auto header_end = bytes.find(kHeaderEnd); + if (header_end == std::string_view::npos) + return bytes.size() >= kUnixHttpMaxHeaderBytes ? TooLarge() : Malformed(); + const std::size_t header_bytes = header_end + kHeaderEnd.size(); + if (header_bytes > kUnixHttpMaxHeaderBytes) return TooLarge(); + + const auto first_line_end = bytes.find(kCrlf); + if (first_line_end == std::string_view::npos || first_line_end > header_end) + return Malformed(); + const std::string_view status_line = bytes.substr(0, first_line_end); + if (!(status_line.starts_with("HTTP/1.0 ") || + status_line.starts_with("HTTP/1.1 ")) || status_line.size() < 13) { + return Malformed(); + } + const std::size_t code_pos = 9; + if (status_line[code_pos] < '0' || status_line[code_pos] > '9' || + status_line[code_pos + 1] < '0' || status_line[code_pos + 1] > '9' || + status_line[code_pos + 2] < '0' || status_line[code_pos + 2] > '9' || + status_line[code_pos + 3] != ' ') { + return Malformed(); + } + for (std::size_t i = code_pos + 4; i < status_line.size(); ++i) { + const auto c = static_cast(status_line[i]); + if ((c < 0x20 && c != '\t') || c == 0x7f) return Malformed(); + } + const auto status = static_cast( + (status_line[code_pos] - '0') * 100 + + (status_line[code_pos + 1] - '0') * 10 + + (status_line[code_pos + 2] - '0')); + if (status < 100 || status > 599 || (status >= 100 && status < 200)) + return Malformed(); + + bool has_content_length = false; + std::uint64_t content_length = 0; + bool has_transfer_encoding = false; + bool has_content_encoding = false; + std::size_t field_count = 0; + std::size_t cursor = first_line_end + kCrlf.size(); + while (cursor < header_end) { + const auto line_end = bytes.find(kCrlf, cursor); + if (line_end == std::string_view::npos || line_end > header_end) + return Malformed(); + const auto line = bytes.substr(cursor, line_end - cursor); + if (line.empty() || line.front() == ' ' || line.front() == '\t') + return Malformed(); + const auto colon = line.find(':'); + if (colon == std::string_view::npos || colon == 0) return Malformed(); + for (unsigned char c : line.substr(0, colon)) + if (!IsTokenChar(c)) return Malformed(); + const auto value = TrimOws(line.substr(colon + 1)); + for (unsigned char c : value) + if ((c < 0x20 && c != '\t') || c == 0x7f) return Malformed(); + if (++field_count > kUnixHttpMaxHeaderFields) return TooLarge(); + + const auto name = line.substr(0, colon); + if (EqualAsciiInsensitive(name, "content-length")) { + if (has_content_length || !ParseUnsignedDecimal(value, content_length)) + return Malformed(); + has_content_length = true; + } else if (EqualAsciiInsensitive(name, "transfer-encoding")) { + if (has_transfer_encoding || !EqualAsciiInsensitive(value, "chunked")) + return Malformed(); + has_transfer_encoding = true; + } else if (EqualAsciiInsensitive(name, "content-encoding")) { + if (has_content_encoding || !EqualAsciiInsensitive(value, "identity")) + return Malformed(); + has_content_encoding = true; + } + cursor = line_end + kCrlf.size(); + } + if (has_content_length && has_transfer_encoding) return Malformed(); + + const bool bodyless_status = status == 204 || status == 304; + if (bodyless_status) { + if (has_transfer_encoding || (has_content_length && content_length != 0) || + bytes.size() != header_bytes) { + return Malformed(); + } + return UnixHttpResponse{status, {}}; + } + + BodyFraming framing = BodyFraming::CloseDelimited; + if (has_transfer_encoding) framing = BodyFraming::Chunked; + else if (has_content_length) framing = BodyFraming::ContentLength; + + UnixHttpResponse response; + response.status = status; + if (framing == BodyFraming::ContentLength) { + if (content_length > kUnixHttpMaxDecodedBodyBytes) return TooLarge(); + if (content_length != bytes.size() - header_bytes) return Malformed(); + response.body.assign(wire.begin() + static_cast(header_bytes), + wire.end()); + return response; + } + if (framing == BodyFraming::CloseDelimited) { + const std::size_t body_size = bytes.size() - header_bytes; + if (body_size > kUnixHttpMaxDecodedBodyBytes) return TooLarge(); + response.body.assign(wire.begin() + static_cast(header_bytes), + wire.end()); + return response; + } + + cursor = header_bytes; + std::size_t chunks = 0; + for (;;) { + const auto line_end = bytes.find(kCrlf, cursor); + if (line_end == std::string_view::npos) + return bytes.size() - cursor > kUnixHttpMaxChunkLineBytes + ? TooLarge() : Malformed(); + const auto line_size = line_end - cursor; + if (line_size > kUnixHttpMaxChunkLineBytes) return TooLarge(); + const auto line = bytes.substr(cursor, line_size); + if (line.find(';') != std::string_view::npos) return Malformed(); + std::uint64_t chunk_size = 0; + if (!ParseHex(line, chunk_size)) return Malformed(); + cursor = line_end + kCrlf.size(); + if (chunk_size == 0) { + if (cursor + kCrlf.size() > bytes.size() || + bytes.substr(cursor, kCrlf.size()) != kCrlf) { + return Malformed(); // Empty trailers only. + } + cursor += kCrlf.size(); + if (cursor != bytes.size()) return Malformed(); + return response; + } + if (++chunks > kUnixHttpMaxChunks || + chunk_size > kUnixHttpMaxDecodedBodyBytes - response.body.size()) + return TooLarge(); + if (chunk_size > bytes.size() - cursor || + bytes.size() - cursor - static_cast(chunk_size) < kCrlf.size()) + return Malformed(); + const auto chunk_end = cursor + static_cast(chunk_size); + response.body.insert(response.body.end(), wire.begin() + static_cast(cursor), + wire.begin() + static_cast(chunk_end)); + if (bytes.substr(chunk_end, kCrlf.size()) != kCrlf) return Malformed(); + cursor = chunk_end + kCrlf.size(); + } + } catch (const std::bad_alloc&) { + return HttpParseError::AllocationFailure; + } catch (...) { + return HttpParseError::Malformed; + } +} + +} // namespace rateguard::supervisor::detail diff --git a/src/supervisor/http1_parser.h b/src/supervisor/http1_parser.h new file mode 100644 index 0000000..d409b0c --- /dev/null +++ b/src/supervisor/http1_parser.h @@ -0,0 +1,24 @@ +#pragma once + +#include "supervisor/unix_http_transport.h" + +#include +#include + +namespace rateguard::supervisor::detail { + +enum class HttpParseError : std::uint8_t { + Malformed, + TooLarge, + AllocationFailure, +}; + +using HttpParseResult = std::variant; + +// Parses a complete response after EOF on the Connection: close exchange. +[[nodiscard]] HttpParseResult ParseHttpResponse( + std::span wire) noexcept; + +[[nodiscard]] bool IsValidOriginFormTarget(std::string_view target) noexcept; + +} // namespace rateguard::supervisor::detail diff --git a/src/supervisor/manifest_codec.cpp b/src/supervisor/manifest_codec.cpp new file mode 100644 index 0000000..7958114 --- /dev/null +++ b/src/supervisor/manifest_codec.cpp @@ -0,0 +1,380 @@ +#include "supervisor/manifest_codec.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { +namespace { + +using Json = nlohmann::json; +constexpr std::size_t kMaxJsonDepth = 6; +constexpr std::uint32_t kNanosPerSecond = 1'000'000'000U; +constexpr std::int32_t kClockMonotonic = 1; + +struct Failure final { ManifestCodecError error; }; +[[noreturn]] void Fail(ManifestCodecError error) { throw Failure{error}; } + +bool AllZero(const auto& bytes) noexcept { + return std::all_of(bytes.begin(), bytes.end(), [](std::uint8_t b) { return b == 0; }); +} + +class StrictJsonGuard final : public nlohmann::json_sax { + public: + using string_t = Json::string_t; + using binary_t = Json::binary_t; + using number_integer_t = Json::number_integer_t; + using number_unsigned_t = Json::number_unsigned_t; + using number_float_t = Json::number_float_t; + bool null() override { return true; } + bool boolean(bool) override { return true; } + bool number_integer(number_integer_t) override { return true; } + bool number_unsigned(number_unsigned_t) override { return true; } + bool number_float(number_float_t, const string_t&) override { return Reject(ManifestCodecError::InvalidJson); } + bool string(string_t&) override { return true; } + bool binary(binary_t&) override { return Reject(ManifestCodecError::InvalidJson); } + bool start_object(std::size_t) override { + if (frames_.size() >= kMaxJsonDepth) return Reject(ManifestCodecError::InvalidJson); + frames_.push_back(Frame{true, {}}); return true; + } + bool key(string_t& value) override { + if (frames_.empty() || !frames_.back().object) return Reject(ManifestCodecError::InvalidJson); + if (!frames_.back().keys.insert(value).second) return Reject(ManifestCodecError::DuplicateKey); + return true; + } + bool end_object() override { + if (frames_.empty() || !frames_.back().object) return Reject(ManifestCodecError::InvalidJson); + frames_.pop_back(); return true; + } + bool start_array(std::size_t) override { + if (frames_.size() >= kMaxJsonDepth) return Reject(ManifestCodecError::InvalidJson); + frames_.push_back(Frame{false, {}}); return true; + } + bool end_array() override { + if (frames_.empty() || frames_.back().object) return Reject(ManifestCodecError::InvalidJson); + frames_.pop_back(); return true; + } + bool parse_error(std::size_t, const std::string&, const nlohmann::detail::exception&) override { + if (!error_) error_ = ManifestCodecError::InvalidJson; + return false; + } + [[nodiscard]] ManifestCodecError error() const noexcept { + return error_.value_or(ManifestCodecError::InvalidJson); + } + [[nodiscard]] bool has_error() const noexcept { return error_.has_value(); } + private: + struct Frame { bool object; std::set> keys; }; + bool Reject(ManifestCodecError error) { + if (!error_) error_ = error; + return false; + } + std::vector frames_; + std::optional error_; +}; + +void CheckKeys(const Json& value, std::initializer_list keys) { + if (!value.is_object()) Fail(ManifestCodecError::InvalidValue); + for (const auto& item : value.items()) { + if (std::find(keys.begin(), keys.end(), std::string_view(item.key())) == keys.end()) + Fail(ManifestCodecError::UnknownKey); + } + for (const auto key : keys) if (!value.contains(std::string(key))) Fail(ManifestCodecError::MissingKey); +} + +std::string Hex(const auto& bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string result; + result.resize(bytes.size() * 2); + for (std::size_t i = 0; i < bytes.size(); ++i) { + result[2 * i] = digits[bytes[i] >> 4]; + result[2 * i + 1] = digits[bytes[i] & 0x0f]; + } + return result; +} + +template +std::array ParseHex(const Json& value) { + if (!value.is_string()) Fail(ManifestCodecError::InvalidValue); + const auto text = value.get(); + if (text.size() != N * 2) Fail(ManifestCodecError::InvalidValue); + auto nibble = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return -1; + }; + std::array out{}; + for (std::size_t i = 0; i < N; ++i) { + const int hi = nibble(text[2 * i]), lo = nibble(text[2 * i + 1]); + if (hi < 0 || lo < 0) Fail(ManifestCodecError::InvalidValue); + out[i] = static_cast((hi << 4) | lo); + } + return out; +} + +std::string U64(std::uint64_t value) { return std::to_string(value); } +std::string I64(std::int64_t value) { return std::to_string(value); } + +std::uint64_t ParseU64(const Json& value) { + if (!value.is_string()) Fail(ManifestCodecError::InvalidValue); + const auto text = value.get(); + if (text.empty() || (text.size() > 1 && text.front() == '0')) Fail(ManifestCodecError::InvalidValue); + for (unsigned char c : text) if (c < '0' || c > '9') Fail(ManifestCodecError::InvalidValue); + std::uint64_t out{}; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), out, 10); + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) Fail(ManifestCodecError::InvalidValue); + return out; +} + +std::int64_t ParseI64(const Json& value) { + if (!value.is_string()) Fail(ManifestCodecError::InvalidValue); + const auto text = value.get(); + if (text.empty() || text == "-0" || (text.size() > 1 && text[0] == '0') || + (text.size() > 2 && text[0] == '-' && text[1] == '0')) Fail(ManifestCodecError::InvalidValue); + const std::size_t start = text.front() == '-' ? 1 : 0; + if (start == text.size()) Fail(ManifestCodecError::InvalidValue); + for (std::size_t i = start; i < text.size(); ++i) + if (text[i] < '0' || text[i] > '9') Fail(ManifestCodecError::InvalidValue); + std::int64_t out{}; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), out, 10); + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) Fail(ManifestCodecError::InvalidValue); + return out; +} + +std::uint32_t U32(const Json& value) { + if (value.is_number_unsigned()) { + const auto n = value.get(); + if (n <= std::numeric_limits::max()) return static_cast(n); + } else if (value.is_number_integer()) { + const auto n = value.get(); + if (n >= 0 && static_cast(n) <= std::numeric_limits::max()) + return static_cast(n); + } + Fail(ManifestCodecError::InvalidValue); +} + +std::int32_t I32(const Json& value) { + if (value.is_number_unsigned()) { + const auto n = value.get(); + if (n <= static_cast(std::numeric_limits::max())) + return static_cast(n); + } else if (value.is_number_integer()) { + const auto n = value.get(); + if (n >= std::numeric_limits::min() && n <= std::numeric_limits::max()) + return static_cast(n); + } + Fail(ManifestCodecError::InvalidValue); +} + +const char* RoleName(ParticipantRole role) { + switch (role) { + case ParticipantRole::Authority: return "AUTHORITY"; + case ParticipantRole::Replica: return "REPLICA"; + case ParticipantRole::Adapter: return "ADAPTER"; + case ParticipantRole::Witness: return "WITNESS"; + } + Fail(ManifestCodecError::InvalidValue); +} +ParticipantRole ParseRole(const Json& value) { + if (!value.is_string()) Fail(ManifestCodecError::InvalidValue); + const auto role = value.get(); + if (role == "AUTHORITY") return ParticipantRole::Authority; + if (role == "REPLICA") return ParticipantRole::Replica; + if (role == "ADAPTER") return ParticipantRole::Adapter; + if (role == "WITNESS") return ParticipantRole::Witness; + Fail(ManifestCodecError::InvalidValue); +} + +const char* PhaseName(ManifestPhase phase) { + switch (phase) { + case ManifestPhase::Prepared: return "PREPARED"; + case ManifestPhase::Active: return "ACTIVE"; + case ManifestPhase::Draining: return "DRAINING"; + case ManifestPhase::Closed: return "CLOSED"; + } + Fail(ManifestCodecError::InvalidValue); +} +ManifestPhase ParsePhase(const Json& value) { + if (!value.is_string()) Fail(ManifestCodecError::InvalidValue); + const auto phase = value.get(); + if (phase == "PREPARED") return ManifestPhase::Prepared; + if (phase == "ACTIVE") return ManifestPhase::Active; + if (phase == "DRAINING") return ManifestPhase::Draining; + if (phase == "CLOSED") return ManifestPhase::Closed; + Fail(ManifestCodecError::InvalidValue); +} + +Json ClockJson(const platform::ClockIdentity& c) { + return Json{{"boot_uuid", Hex(c.boot_uuid)}, + {"boottime_offset_nanoseconds", c.boottime_offset_nanoseconds}, + {"boottime_offset_seconds", I64(c.boottime_offset_seconds)}, + {"clock_id", c.clock_id}, + {"monotonic_offset_nanoseconds", c.monotonic_offset_nanoseconds}, + {"monotonic_offset_seconds", I64(c.monotonic_offset_seconds)}, + {"namespace_device", U64(c.namespace_device)}, + {"namespace_inode", U64(c.namespace_inode)}}; +} +platform::ClockIdentity ParseClock(const Json& j) { + CheckKeys(j, {"boot_uuid", "boottime_offset_nanoseconds", "boottime_offset_seconds", "clock_id", + "monotonic_offset_nanoseconds", "monotonic_offset_seconds", "namespace_device", "namespace_inode"}); + platform::ClockIdentity c{}; + c.boot_uuid = ParseHex<16>(j.at("boot_uuid")); + c.namespace_device = ParseU64(j.at("namespace_device")); + c.namespace_inode = ParseU64(j.at("namespace_inode")); + c.monotonic_offset_seconds = ParseI64(j.at("monotonic_offset_seconds")); + c.monotonic_offset_nanoseconds = U32(j.at("monotonic_offset_nanoseconds")); + c.boottime_offset_seconds = ParseI64(j.at("boottime_offset_seconds")); + c.boottime_offset_nanoseconds = U32(j.at("boottime_offset_nanoseconds")); + c.clock_id = I32(j.at("clock_id")); + if (AllZero(c.boot_uuid) || c.namespace_device == 0 || c.namespace_inode == 0 || + c.clock_id != kClockMonotonic || c.monotonic_offset_nanoseconds >= kNanosPerSecond || + c.boottime_offset_nanoseconds >= kNanosPerSecond) Fail(ManifestCodecError::InvalidValue); + return c; +} + +Json ParticipantJson(const Participant& p) { + return Json{{"clock_identity", ClockJson(p.clock_identity)}, + {"incarnation", Hex(p.incarnation)}, + {"participant_id", p.participant_id}, + {"process", Json{{"container_id", p.process.container_id}, + {"pid", U64(p.process.pid)}, + {"pid_start_ticks", U64(p.process.pid_start_ticks)}}}, + {"role", RoleName(p.role)}, + {"slot_id", p.slot_id}}; +} +Participant ParseParticipant(const Json& j) { + CheckKeys(j, {"clock_identity", "incarnation", "participant_id", "process", "role", "slot_id"}); + Participant p{}; + p.role = ParseRole(j.at("role")); + p.slot_id = U32(j.at("slot_id")); + if (!j.at("participant_id").is_string()) Fail(ManifestCodecError::InvalidValue); + p.participant_id = j.at("participant_id").get(); + p.incarnation = ParseHex<16>(j.at("incarnation")); + CheckKeys(j.at("process"), {"container_id", "pid", "pid_start_ticks"}); + const auto& proc = j.at("process"); + if (!proc.at("container_id").is_string()) Fail(ManifestCodecError::InvalidValue); + p.process.container_id = proc.at("container_id").get(); + p.process.pid = ParseU64(proc.at("pid")); + p.process.pid_start_ticks = ParseU64(proc.at("pid_start_ticks")); + p.clock_identity = ParseClock(j.at("clock_identity")); + return p; +} + +Json PayloadJson(const ManifestV1& m) { + if (m.generation == 0 || AllZero(m.transition_operation_id)) Fail(ManifestCodecError::InvalidValue); + if (m.candidate.participants.size() > kMaxParticipants || ValidateEpochCandidate(m.candidate)) + Fail(ManifestCodecError::InvalidValue); + const auto& c = m.candidate.clock_identity; + if (AllZero(c.boot_uuid) || c.namespace_device == 0 || c.namespace_inode == 0 || c.clock_id != kClockMonotonic || + c.monotonic_offset_nanoseconds >= kNanosPerSecond || c.boottime_offset_nanoseconds >= kNanosPerSecond) + Fail(ManifestCodecError::InvalidValue); + std::vector participants = m.candidate.participants; + std::sort(participants.begin(), participants.end(), [](const Participant& a, const Participant& b) { + if (a.role != b.role) return static_cast(a.role) < static_cast(b.role); + if (a.participant_id != b.participant_id) return a.participant_id < b.participant_id; + return a.slot_id < b.slot_id; + }); + Json participant_json = Json::array(); + for (const auto& p : participants) participant_json.push_back(ParticipantJson(p)); + return Json{{"authority_incarnation", Hex(m.candidate.authority_incarnation)}, + {"clock_identity", ClockJson(c)}, + {"epoch_id", Hex(m.candidate.epoch_id)}, + {"generation", U64(m.generation)}, + {"participants", std::move(participant_json)}, + {"phase", PhaseName(m.phase)}, + {"policy_digest", Hex(m.candidate.policy_digest)}, + {"schema_version", 1}, + {"transition_operation_id", Hex(m.transition_operation_id)}}; +} + +std::array Sha256(std::string_view data) { + std::array digest{}; + unsigned int length = 0; + if (EVP_Digest(data.data(), data.size(), digest.data(), &length, EVP_sha256(), nullptr) != 1 || length != digest.size()) + Fail(ManifestCodecError::DigestFailure); + return digest; +} + +Json ParseJson(std::string_view input) { + StrictJsonGuard guard; + if (!Json::sax_parse(input.begin(), input.end(), &guard)) Fail(guard.error()); + try { return Json::parse(input); } + catch (...) { Fail(ManifestCodecError::InvalidJson); } +} + +ManifestV1 ParsePayload(const Json& j) { + CheckKeys(j, {"authority_incarnation", "clock_identity", "epoch_id", "generation", "participants", + "phase", "policy_digest", "schema_version", "transition_operation_id"}); + const auto& schema = j.at("schema_version"); + const bool schema_one = schema.is_number_unsigned() ? schema.get() == 1 + : schema.is_number_integer() && schema.get() == 1; + if (!schema_one) Fail(ManifestCodecError::UnsupportedSchema); + ManifestV1 m; + m.candidate.epoch_id = ParseHex<16>(j.at("epoch_id")); + m.candidate.authority_incarnation = ParseHex<16>(j.at("authority_incarnation")); + m.candidate.policy_digest = ParseHex<32>(j.at("policy_digest")); + m.candidate.clock_identity = ParseClock(j.at("clock_identity")); + m.phase = ParsePhase(j.at("phase")); + m.generation = ParseU64(j.at("generation")); + m.transition_operation_id = ParseHex<16>(j.at("transition_operation_id")); + if (m.generation == 0 || AllZero(m.transition_operation_id)) Fail(ManifestCodecError::InvalidValue); + const auto& ps = j.at("participants"); + if (!ps.is_array() || ps.empty() || ps.size() > kMaxParticipants) Fail(ManifestCodecError::InvalidValue); + m.candidate.participants.reserve(ps.size()); + for (const auto& item : ps) m.candidate.participants.push_back(ParseParticipant(item)); + if (ValidateEpochCandidate(m.candidate)) Fail(ManifestCodecError::InvalidValue); + return m; +} + +} // namespace + +ManifestEncodeResult EncodeManifestV1(const ManifestV1& manifest) noexcept { + try { + const auto payload = PayloadJson(manifest).dump(-1, ' ', false, Json::error_handler_t::strict); + if (payload.size() > kMaxManifestBytes) return ManifestCodecError::TooLarge; + const auto digest = Sha256(payload); + const Json envelope{{"manifest", Json::parse(payload)}, {"sha256", Hex(digest)}}; + auto encoded = envelope.dump(-1, ' ', false, Json::error_handler_t::strict); + if (encoded.size() > kMaxManifestBytes) return ManifestCodecError::TooLarge; + return encoded; + } catch (const Failure& f) { return f.error; } + catch (...) { return ManifestCodecError::AllocationFailure; } +} + +ManifestDecodeResult DecodeManifestV1(std::string_view envelope) noexcept { + if (envelope.size() > kMaxManifestBytes) return ManifestCodecError::TooLarge; + try { + const auto root = ParseJson(envelope); + CheckKeys(root, {"manifest", "sha256"}); + const auto& digest_field = root.at("sha256"); + if (!digest_field.is_string()) return ManifestCodecError::InvalidValue; + const auto expected = ParseHex<32>(digest_field); + const auto manifest = ParsePayload(root.at("manifest")); + const auto payload_text = PayloadJson(manifest).dump(-1, ' ', false, Json::error_handler_t::strict); + if (Sha256(payload_text) != expected) return ManifestCodecError::DigestMismatch; + const auto canonical = EncodeManifestV1(manifest); + if (const auto* error = std::get_if(&canonical)) return *error; + if (std::get(canonical) != envelope) return ManifestCodecError::NonCanonical; + return manifest; + } catch (const Failure& f) { return f.error; } + catch (...) { return ManifestCodecError::AllocationFailure; } +} + +ManifestDigestResult ManifestDigestV1(const ManifestV1& manifest) noexcept { + try { + const auto payload = PayloadJson(manifest).dump(-1, ' ', false, Json::error_handler_t::strict); + if (payload.size() > kMaxManifestBytes) return ManifestCodecError::TooLarge; + return Sha256(payload); + } catch (const Failure& f) { return f.error; } + catch (...) { return ManifestCodecError::AllocationFailure; } +} + +} // namespace rateguard::supervisor diff --git a/src/supervisor/manifest_codec.h b/src/supervisor/manifest_codec.h new file mode 100644 index 0000000..cab9881 --- /dev/null +++ b/src/supervisor/manifest_codec.h @@ -0,0 +1,52 @@ +#pragma once + +// Strict, bounded codec for the supervisor's version-1 epoch manifest. +// A valid digest detects accidental modification; it does not authenticate a +// writer or prove that an older valid manifest was not rolled back. + +#include "supervisor/epoch_gate.h" + +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +inline constexpr std::size_t kMaxManifestBytes = 4U * 1024U * 1024U; + +enum class ManifestPhase : std::uint8_t { Prepared = 1, Active = 2, Draining = 3, Closed = 4 }; +enum class ManifestCodecError : std::uint8_t { + InvalidValue, + TooLarge, + InvalidJson, + DuplicateKey, + UnknownKey, + MissingKey, + UnsupportedSchema, + NonCanonical, + DigestMismatch, + DigestFailure, + AllocationFailure, +}; + +struct ManifestV1 { + EpochCandidate candidate; + ManifestPhase phase{ManifestPhase::Prepared}; + std::uint64_t generation{1}; + OperationId transition_operation_id{}; +}; + +using ManifestEncodeResult = std::variant; +using ManifestDecodeResult = std::variant; +using ManifestDigestResult = std::variant, ManifestCodecError>; + +// The payload is canonical compact JSON with sorted object keys. The envelope +// contains exactly {"manifest": payload, "sha256": lowercase_hex_digest}; +// SHA-256 covers the compact canonical payload bytes only. +[[nodiscard]] ManifestEncodeResult EncodeManifestV1(const ManifestV1& manifest) noexcept; +[[nodiscard]] ManifestDecodeResult DecodeManifestV1(std::string_view envelope) noexcept; +[[nodiscard]] ManifestDigestResult ManifestDigestV1(const ManifestV1& manifest) noexcept; + +} // namespace rateguard::supervisor diff --git a/src/supervisor/manifest_store.cpp b/src/supervisor/manifest_store.cpp new file mode 100644 index 0000000..97f726e --- /dev/null +++ b/src/supervisor/manifest_store.cpp @@ -0,0 +1,523 @@ +#include "supervisor/manifest_store.h" + +#include "supervisor/epoch_gate.h" +#include "supervisor/epoch_artifact_layout.h" +#include "platform/file_io.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { +namespace { + +constexpr auto& kLockName = epoch_layout_v1::kManifestStoreLockFileName; +constexpr auto& kManifestName = epoch_layout_v1::kManifestFileName; +constexpr auto& kTempName = epoch_layout_v1::kManifestTemporaryFileName; +constexpr std::size_t kMaxDirectoryPathBytes = 4096; + +bool ValidPath(const std::string& path) noexcept; + +using platform::file::UniqueFd; +using platform::file::WriteAll; +using platform::file::ReadAll; +using platform::file::Sync; + +struct ParentLocation { + UniqueFd fd; + std::string leaf; +}; + +std::optional OpenParent(const std::string& path) { + if (!ValidPath(path) || path.back() == '/') return std::nullopt; + const auto slash = path.find_last_of('/'); + const std::string parent = slash == std::string::npos ? "." : + slash == 0 ? "/" : path.substr(0, slash); + const std::string leaf = slash == std::string::npos ? path : path.substr(slash + 1); + if (leaf.empty() || leaf == "." || leaf == "..") return std::nullopt; + const int fd = ::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (fd < 0) return std::nullopt; + return ParentLocation{UniqueFd(fd), leaf}; +} + +bool Fail(IManifestFileOps* hooks, ManifestIoPoint point) noexcept { + return hooks != nullptr && hooks->FailAt(point); +} + +bool ValidPath(const std::string& path) noexcept { + return !path.empty() && path.size() < kMaxDirectoryPathBytes && + path.find('\0') == std::string::npos; +} + +bool ExactMode(const struct stat& st, mode_t mode) noexcept { + return (st.st_mode & 07777) == mode; +} + +bool ValidDirectory(int fd) noexcept { + struct stat st {}; + return ::fstat(fd, &st) == 0 && S_ISDIR(st.st_mode) && st.st_uid == ::geteuid() && + ExactMode(st, 0700); +} + +bool SameInode(const struct stat& a, const struct stat& b) noexcept { + return a.st_dev == b.st_dev && a.st_ino == b.st_ino; +} + +bool ValidRegularFile(const struct stat& st, mode_t mode) noexcept { + return S_ISREG(st.st_mode) && st.st_uid == ::geteuid() && ExactMode(st, mode) && + st.st_nlink == 1; +} + +bool NormalizeManifest(const ManifestV1& input, ManifestV1& output) noexcept { + try { + auto encoded = EncodeManifestV1(input); + if (std::holds_alternative(encoded)) return false; + const auto& bytes = std::get(encoded); + if (bytes.size() > kMaxManifestBytes) return false; + auto decoded = DecodeManifestV1(bytes); + if (std::holds_alternative(decoded)) return false; + output = std::get(std::move(decoded)); + return true; + } catch (...) { + return false; + } +} + +ManifestStoreError CodecError(ManifestCodecError) noexcept { + return ManifestStoreError::CodecFailure; +} + +bool ValidOperation(const OperationId& id) noexcept { + return std::any_of(id.begin(), id.end(), [](std::uint8_t v) { return v != 0; }); +} + +bool LegalTransition(ManifestPhase from, ManifestPhase to) noexcept { + return (from == ManifestPhase::Prepared && + (to == ManifestPhase::Active || to == ManifestPhase::Draining)) || + (from == ManifestPhase::Active && to == ManifestPhase::Draining) || + (from == ManifestPhase::Draining && to == ManifestPhase::Closed); +} + +std::variant>, ManifestStoreError> +ReadManifest(int dirfd, IManifestFileOps* hooks) { + if (Fail(hooks, ManifestIoPoint::OpenManifest)) return ManifestStoreError::ReadFailure; + const int fd = ::openat(dirfd, kManifestName, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK); + if (fd < 0) { + if (errno == ENOENT) return ManifestStoreError::MissingManifest; + return ManifestStoreError::ReadFailure; + } + struct FdGuard { int fd; ~FdGuard() { if (fd >= 0) ::close(fd); } } guard{fd}; + struct stat st {}; + if (::fstat(fd, &st) != 0 || !ValidRegularFile(st, 0600) || st.st_size < 0) + return ManifestStoreError::InvalidManifestFile; + struct stat named {}; + if (::fstatat(dirfd, kManifestName, &named, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(st, named) || !ValidRegularFile(named, 0600)) + return ManifestStoreError::InvalidManifestFile; + if (static_cast(st.st_size) > kMaxManifestBytes) + return ManifestStoreError::ManifestTooLarge; + if (Fail(hooks, ManifestIoPoint::ReadManifest)) return ManifestStoreError::ReadFailure; + std::string bytes; + if (!ReadAll(fd, bytes, static_cast(st.st_size))) + return ManifestStoreError::ReadFailure; + auto decoded = DecodeManifestV1(bytes); + if (auto* error = std::get_if(&decoded)) return CodecError(*error); + auto manifest = std::get(std::move(decoded)); + auto digest_result = ManifestDigestV1(manifest); + if (auto* error = std::get_if(&digest_result)) return CodecError(*error); + return std::pair>{ + std::move(manifest), std::get>(std::move(digest_result))}; +} + +bool ValidateLock(int dirfd, int lockfd, IManifestFileOps* hooks) noexcept { + if (Fail(hooks, ManifestIoPoint::CheckLockIdentity)) + return false; + struct stat opened {}, named {}; + if (::fstat(lockfd, &opened) != 0 || + ::fstatat(dirfd, kLockName, &named, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(opened, named) || !ValidRegularFile(opened, 0600) || + !ValidRegularFile(named, 0600)) return false; + return true; +} + +bool LockValid(int dirfd, int lockfd, IManifestFileOps* hooks) noexcept { + return ValidateLock(dirfd, lockfd, hooks); +} + +int OpenDirectory(const std::string& path, IManifestFileOps* hooks) noexcept { + if (Fail(hooks, ManifestIoPoint::OpenDirectory)) { errno = EIO; return -1; } + return ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); +} + +int CreateAndLock(int dirfd, IManifestFileOps* hooks, + ManifestStoreError& error) noexcept { + if (Fail(hooks, ManifestIoPoint::CreateLock)) { + error = ManifestStoreError::InvalidLock; return -1; + } + const int fd = ::openat(dirfd, kLockName, + O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC | O_NOFOLLOW, 0600); + if (fd < 0) { error = ManifestStoreError::InvalidLock; return -1; } + if (::fchmod(fd, 0600) != 0) { + error = ManifestStoreError::InvalidLock; ::close(fd); return -1; + } + struct stat st {}; + if (::fstat(fd, &st) != 0 || !ValidRegularFile(st, 0600)) { + error = ManifestStoreError::InvalidLock; ::close(fd); return -1; + } + if (Fail(hooks, ManifestIoPoint::AcquireLock)) { + errno = EIO; + error = ManifestStoreError::InvalidLock; + ::close(fd); + return -1; + } + if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { + error = (errno == EWOULDBLOCK || errno == EAGAIN) ? ManifestStoreError::LockBusy + : ManifestStoreError::InvalidLock; + ::close(fd); return -1; + } + if (!LockValid(dirfd, fd, hooks)) { + error = ManifestStoreError::LockIdentityChanged; ::close(fd); return -1; + } + if (Fail(hooks, ManifestIoPoint::SyncLock) || !Sync(fd)) { + error = ManifestStoreError::FileSyncFailure; ::close(fd); return -1; + } + return fd; +} + +std::optional WriteNewManifest(int dirfd, int lockfd, + const ManifestV1& manifest, + IManifestFileOps* hooks) { + if (!LockValid(dirfd, lockfd, hooks)) return ManifestStoreError::LockIdentityChanged; + auto encoded = EncodeManifestV1(manifest); + if (auto* error = std::get_if(&encoded)) return CodecError(*error); + auto& bytes = std::get(encoded); + if (bytes.size() > kMaxManifestBytes) return ManifestStoreError::ManifestTooLarge; + if (Fail(hooks, ManifestIoPoint::CreateTemp)) return ManifestStoreError::WriteFailure; + UniqueFd tempfd(::openat(dirfd, kTempName, + O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC | O_NOFOLLOW, 0600)); + if (tempfd.get() < 0) return ManifestStoreError::WriteFailure; + struct stat temp_stat {}; + if (::fchmod(tempfd.get(), 0600) != 0 || ::fstat(tempfd.get(), &temp_stat) != 0 || + !ValidRegularFile(temp_stat, 0600)) { + if (!Fail(hooks, ManifestIoPoint::CleanupTemp)) (void)::unlinkat(dirfd, kTempName, 0); + return ManifestStoreError::WriteFailure; + } + if (Fail(hooks, ManifestIoPoint::WriteTemp) || !WriteAll(tempfd.get(), bytes.data(), bytes.size())) { + if (!Fail(hooks, ManifestIoPoint::CleanupTemp)) (void)::unlinkat(dirfd, kTempName, 0); + return ManifestStoreError::WriteFailure; + } + if (Fail(hooks, ManifestIoPoint::SyncTemp) || !Sync(tempfd.get())) { + if (!Fail(hooks, ManifestIoPoint::CleanupTemp)) (void)::unlinkat(dirfd, kTempName, 0); + return ManifestStoreError::FileSyncFailure; + } + const int closed_fd = tempfd.release(); + if (::close(closed_fd) != 0) { + if (!Fail(hooks, ManifestIoPoint::CleanupTemp)) (void)::unlinkat(dirfd, kTempName, 0); + return ManifestStoreError::WriteFailure; + } + if (!LockValid(dirfd, lockfd, hooks)) { + if (!Fail(hooks, ManifestIoPoint::CleanupTemp)) (void)::unlinkat(dirfd, kTempName, 0); + return ManifestStoreError::LockIdentityChanged; + } + if (Fail(hooks, ManifestIoPoint::RenameManifest) || + ::renameat(dirfd, kTempName, dirfd, kManifestName) != 0) { + if (!Fail(hooks, ManifestIoPoint::CleanupTemp)) (void)::unlinkat(dirfd, kTempName, 0); + return ManifestStoreError::RenameFailure; + } + if (Fail(hooks, ManifestIoPoint::SyncDirectory) || !Sync(dirfd)) + return ManifestStoreError::DurabilityUncertain; + return std::nullopt; +} + +struct PersistResult { + ManifestVisibility visibility{ManifestVisibility::NotVisible}; + std::optional error; +}; + +PersistResult PersistReplacement(int dirfd, int lockfd, + const ManifestV1& current, + const std::array& current_digest, + std::string_view bytes, + IManifestFileOps* hooks) { + if (!LockValid(dirfd, lockfd, hooks)) + return {ManifestVisibility::NotVisible, ManifestStoreError::LockIdentityChanged}; + auto on_disk = ReadManifest(dirfd, hooks); + if (auto* error = std::get_if(&on_disk)) + return {ManifestVisibility::NotVisible, *error}; + auto disk = std::get>>(std::move(on_disk)); + if (disk.first.generation != current.generation || disk.second != current_digest) + return {ManifestVisibility::NotVisible, ManifestStoreError::CompareAndSwapMismatch}; + + if (Fail(hooks, ManifestIoPoint::CreateTemp)) + return {ManifestVisibility::NotVisible, ManifestStoreError::WriteFailure}; + UniqueFd tempfd(::openat(dirfd, kTempName, + O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC | O_NOFOLLOW, 0600)); + if (tempfd.get() < 0) + return {ManifestVisibility::NotVisible, ManifestStoreError::WriteFailure}; + const auto cleanup = [&] { + if (!Fail(hooks, ManifestIoPoint::CleanupTemp)) (void)::unlinkat(dirfd, kTempName, 0); + }; + struct stat temp_stat {}; + if (::fchmod(tempfd.get(), 0600) != 0 || ::fstat(tempfd.get(), &temp_stat) != 0 || + !ValidRegularFile(temp_stat, 0600)) { + cleanup(); + return {ManifestVisibility::NotVisible, ManifestStoreError::WriteFailure}; + } + if (Fail(hooks, ManifestIoPoint::WriteTemp) || !WriteAll(tempfd.get(), bytes.data(), bytes.size())) { + cleanup(); + return {ManifestVisibility::NotVisible, ManifestStoreError::WriteFailure}; + } + if (Fail(hooks, ManifestIoPoint::SyncTemp) || !Sync(tempfd.get())) { + cleanup(); + return {ManifestVisibility::NotVisible, ManifestStoreError::FileSyncFailure}; + } + const int closed_fd = tempfd.release(); + if (::close(closed_fd) != 0) { + cleanup(); + return {ManifestVisibility::NotVisible, ManifestStoreError::WriteFailure}; + } + if (!LockValid(dirfd, lockfd, hooks)) { + cleanup(); + return {ManifestVisibility::NotVisible, ManifestStoreError::LockIdentityChanged}; + } + if (Fail(hooks, ManifestIoPoint::RenameManifest) || + ::renameat(dirfd, kTempName, dirfd, kManifestName) != 0) { + cleanup(); + return {ManifestVisibility::NotVisible, ManifestStoreError::RenameFailure}; + } + if (Fail(hooks, ManifestIoPoint::SyncDirectory) || !Sync(dirfd)) + return {ManifestVisibility::VisibleDurabilityUnknown, + ManifestStoreError::DurabilityUncertain}; + return {ManifestVisibility::Durable, std::nullopt}; +} + +} // namespace + +struct ManifestStore::Impl { + int directory_fd{-1}; + int lock_fd{-1}; + std::string directory; + ManifestV1 manifest; + std::array digest{}; + bool recovery_only{}; + bool writable{true}; + bool transition_in_progress{}; + IManifestFileOps* test_hooks{}; // Non-owning test seam; caller outlives store. + mutable std::mutex mutex; +}; + +ManifestStore::ManifestStore(int directory_fd, int lock_fd, std::string directory, + ManifestV1 manifest, + std::array digest, + bool recovery_only, IManifestFileOps* test_hooks) + : impl_(std::make_unique()) { + impl_->directory_fd = directory_fd; + impl_->lock_fd = lock_fd; + impl_->directory = std::move(directory); + impl_->manifest = std::move(manifest); + impl_->digest = digest; + impl_->recovery_only = recovery_only; + impl_->writable = !recovery_only; + impl_->test_hooks = test_hooks; +} + +ManifestStore::~ManifestStore() { + if (!impl_) return; + if (impl_->lock_fd >= 0) ::close(impl_->lock_fd); + if (impl_->directory_fd >= 0) ::close(impl_->directory_fd); +} + +ManifestStoreOpenResult ManifestStore::CreateNew( + const std::string& directory, const EpochCandidate& candidate, + const OperationId& creation_operation_id, IManifestFileOps* hooks) noexcept { + try { + if (!ValidPath(directory)) return ManifestStoreError::InvalidPath; + if (const auto invalid = ValidateEpochCandidate(candidate); invalid.has_value()) + return ManifestStoreError::InvalidManifestFile; + if (!ValidOperation(creation_operation_id)) return ManifestStoreError::OperationIdInvalid; + ManifestV1 unnormalized{candidate, ManifestPhase::Prepared, 1, creation_operation_id}; + ManifestV1 manifest; + if (!NormalizeManifest(unnormalized, manifest)) return ManifestStoreError::CodecFailure; + auto initial_digest = ManifestDigestV1(manifest); + if (std::holds_alternative(initial_digest)) + return ManifestStoreError::CodecFailure; + auto parent = OpenParent(directory); + if (!parent) return ManifestStoreError::InvalidPath; + if (Fail(hooks, ManifestIoPoint::Mkdir)) return ManifestStoreError::InvalidPath; + if (::mkdirat(parent->fd.get(), parent->leaf.c_str(), 0700) != 0) + return errno == EEXIST ? ManifestStoreError::AlreadyExists : ManifestStoreError::InvalidPath; + if (Fail(hooks, ManifestIoPoint::SyncParentDirectory) || !Sync(parent->fd.get())) + return ManifestStoreError::DurabilityUncertain; + if (Fail(hooks, ManifestIoPoint::OpenDirectory)) return ManifestStoreError::InvalidDirectory; + UniqueFd dirfd(::openat(parent->fd.get(), parent->leaf.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)); + if (dirfd.get() < 0) return ManifestStoreError::InvalidDirectory; + if (::fchmod(dirfd.get(), 0700) != 0) return ManifestStoreError::InvalidDirectory; + if (Fail(hooks, ManifestIoPoint::ValidateDirectory) || !ValidDirectory(dirfd.get())) + return ManifestStoreError::InvalidDirectory; + ManifestStoreError lock_error = ManifestStoreError::InvalidLock; + UniqueFd lockfd(CreateAndLock(dirfd.get(), hooks, lock_error)); + if (lockfd.get() < 0) return lock_error; + if (Fail(hooks, ManifestIoPoint::SyncDirectory) || !Sync(dirfd.get())) + return ManifestStoreError::DirectorySyncFailure; + auto created = std::unique_ptr(new ManifestStore( + dirfd.get(), lockfd.get(), directory, std::move(manifest), + std::get>(std::move(initial_digest)), false, hooks)); + (void)dirfd.release(); + (void)lockfd.release(); + const auto write_result = WriteNewManifest(created->impl_->directory_fd, + created->impl_->lock_fd, + created->impl_->manifest, hooks); + if (write_result.has_value()) return *write_result; + return created; + } catch (...) { + return ManifestStoreError::AllocationFailure; + } +} + +ManifestStoreOpenResult ManifestStore::OpenExisting( + const std::string& directory, IManifestFileOps* hooks) noexcept { + try { + if (!ValidPath(directory)) return ManifestStoreError::InvalidPath; + UniqueFd dirfd(OpenDirectory(directory, hooks)); + if (dirfd.get() < 0) return errno == ENOENT ? ManifestStoreError::NotFound + : ManifestStoreError::InvalidDirectory; + if (Fail(hooks, ManifestIoPoint::ValidateDirectory) || !ValidDirectory(dirfd.get())) + return ManifestStoreError::InvalidDirectory; + if (Fail(hooks, ManifestIoPoint::OpenLock)) { + return ManifestStoreError::InvalidLock; + } + UniqueFd lockfd(::openat(dirfd.get(), kLockName, O_RDWR | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (lockfd.get() < 0) return ManifestStoreError::InvalidLock; + struct stat st {}; + if (::fstat(lockfd.get(), &st) != 0 || !ValidRegularFile(st, 0600)) + return ManifestStoreError::InvalidLock; + if (Fail(hooks, ManifestIoPoint::AcquireLock)) { + return ManifestStoreError::InvalidLock; + } + if (::flock(lockfd.get(), LOCK_EX | LOCK_NB) != 0) { + const auto error = (errno == EWOULDBLOCK || errno == EAGAIN) + ? ManifestStoreError::LockBusy : ManifestStoreError::InvalidLock; + return error; + } + if (!LockValid(dirfd.get(), lockfd.get(), hooks)) return ManifestStoreError::LockIdentityChanged; + auto loaded = ReadManifest(dirfd.get(), hooks); + if (auto* error = std::get_if(&loaded)) return *error; + if (!LockValid(dirfd.get(), lockfd.get(), hooks)) return ManifestStoreError::LockIdentityChanged; + auto pair = std::get>>(std::move(loaded)); + auto opened = std::unique_ptr(new ManifestStore( + dirfd.get(), lockfd.get(), directory, std::move(pair.first), pair.second, true, hooks)); + (void)dirfd.release(); + (void)lockfd.release(); + return opened; + } catch (...) { + return ManifestStoreError::AllocationFailure; + } +} + +bool ManifestStore::recovery_only() const noexcept { return impl_->recovery_only; } +bool ManifestStore::writable() const noexcept { + std::lock_guard lock(impl_->mutex); + return impl_->writable && !impl_->recovery_only; +} + +ManifestV1 ManifestStore::snapshot() const { + std::lock_guard lock(impl_->mutex); + return impl_->manifest; +} + +std::array ManifestStore::digest() const { + std::lock_guard lock(impl_->mutex); + return impl_->digest; +} + +ManifestWriteResult ManifestStore::Transition( + std::uint64_t expected_generation, const std::array& expected_digest, + ManifestPhase next_phase, const OperationId& operation_id) { + ManifestV1 current; + std::array current_digest{}; + { + std::lock_guard lock(impl_->mutex); + if (impl_->transition_in_progress) + return {ManifestVisibility::NotVisible, ManifestStoreError::Busy, + impl_->manifest.generation, impl_->manifest.phase, impl_->digest}; + if (impl_->recovery_only) + return {ManifestVisibility::NotVisible, ManifestStoreError::RecoveryReadOnly, + impl_->manifest.generation, impl_->manifest.phase, impl_->digest}; + if (!impl_->writable) + return {ManifestVisibility::NotVisible, ManifestStoreError::WriterLatched, + impl_->manifest.generation, impl_->manifest.phase, impl_->digest}; + if (impl_->manifest.generation != expected_generation || impl_->digest != expected_digest) + return {ManifestVisibility::NotVisible, ManifestStoreError::CompareAndSwapMismatch, + impl_->manifest.generation, impl_->manifest.phase, impl_->digest}; + if (!LegalTransition(impl_->manifest.phase, next_phase)) + return {ManifestVisibility::NotVisible, ManifestStoreError::IllegalTransition, + impl_->manifest.generation, impl_->manifest.phase, impl_->digest}; + if (!ValidOperation(operation_id)) + return {ManifestVisibility::NotVisible, ManifestStoreError::OperationIdInvalid, + impl_->manifest.generation, impl_->manifest.phase, impl_->digest}; + const auto next_generation = TryNextManifestGeneration(impl_->manifest.generation); + if (!next_generation) + return {ManifestVisibility::NotVisible, ManifestStoreError::GenerationExhausted, + impl_->manifest.generation, impl_->manifest.phase, impl_->digest}; + try { + current = impl_->manifest; + } catch (...) { + return {ManifestVisibility::NotVisible, ManifestStoreError::AllocationFailure, + impl_->manifest.generation, impl_->manifest.phase, impl_->digest}; + } + current_digest = impl_->digest; + impl_->transition_in_progress = true; + } + + const auto complete = [&](ManifestVisibility visibility, + std::optional error, + bool latch, ManifestV1* committed, + const std::array* new_digest) { + std::lock_guard lock(impl_->mutex); + if (committed != nullptr) { + impl_->manifest = std::move(*committed); + impl_->digest = *new_digest; + } + if (latch) impl_->writable = false; + impl_->transition_in_progress = false; + ManifestWriteResult out{visibility, error, impl_->manifest.generation, + impl_->manifest.phase, impl_->digest}; + return out; + }; + + try { + ManifestV1 next = current; + next.generation = current.generation + 1; // Non-wrapping check happened before reservation. + next.phase = next_phase; + next.transition_operation_id = operation_id; + auto encoded = EncodeManifestV1(next); + auto next_digest_result = ManifestDigestV1(next); + if (std::holds_alternative(encoded) || + std::holds_alternative(next_digest_result)) + return complete(ManifestVisibility::NotVisible, ManifestStoreError::CodecFailure, + true, nullptr, nullptr); + auto& bytes = std::get(encoded); + if (bytes.size() > kMaxManifestBytes) + return complete(ManifestVisibility::NotVisible, ManifestStoreError::ManifestTooLarge, + true, nullptr, nullptr); + const auto next_digest = std::get>( + std::move(next_digest_result)); + auto persisted = PersistReplacement(impl_->directory_fd, impl_->lock_fd, current, + current_digest, bytes, impl_->test_hooks); + if (persisted.visibility == ManifestVisibility::NotVisible) + return complete(persisted.visibility, persisted.error, true, nullptr, nullptr); + const bool uncertain = persisted.visibility == ManifestVisibility::VisibleDurabilityUnknown; + return complete(persisted.visibility, persisted.error, uncertain, &next, &next_digest); + } catch (...) { + return complete(ManifestVisibility::NotVisible, ManifestStoreError::AllocationFailure, + true, nullptr, nullptr); + } +} + +} // namespace rateguard::supervisor diff --git a/src/supervisor/manifest_store.h b/src/supervisor/manifest_store.h new file mode 100644 index 0000000..439093c --- /dev/null +++ b/src/supervisor/manifest_store.h @@ -0,0 +1,137 @@ +#pragma once + +// POSIX durable store for one immutable epoch manifest. Directory locking is +// local to this path; it is not global supervisor ownership or epoch fencing. + +#include "supervisor/manifest_codec.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +enum class ManifestIoPoint : std::uint8_t { + Mkdir, + SyncParentDirectory, + OpenDirectory, + ValidateDirectory, + CreateLock, + OpenLock, + AcquireLock, + SyncLock, + CheckLockIdentity, + CreateTemp, + WriteTemp, + SyncTemp, + RenameManifest, + SyncDirectory, + OpenManifest, + ReadManifest, + CleanupTemp, +}; + +// Internal deterministic fault-injection seam. Returning true makes the +// corresponding operation fail before its POSIX syscall is attempted. +class IManifestFileOps { + public: + virtual ~IManifestFileOps() = default; + [[nodiscard]] virtual bool FailAt(ManifestIoPoint point) noexcept = 0; +}; + +enum class ManifestStoreError : std::uint8_t { + AlreadyExists, + NotFound, + InvalidPath, + InvalidDirectory, + InvalidLock, + LockBusy, + LockIdentityChanged, + Busy, + InvalidManifestFile, + MissingManifest, + ManifestTooLarge, + CodecFailure, + ReadFailure, + WriteFailure, + FileSyncFailure, + RenameFailure, + DirectorySyncFailure, + DurabilityUncertain, + RecoveryReadOnly, + WriterLatched, + CompareAndSwapMismatch, + IllegalTransition, + OperationIdInvalid, + GenerationExhausted, + AllocationFailure, +}; + +enum class ManifestVisibility : std::uint8_t { + NotVisible, + Durable, + VisibleDurabilityUnknown, +}; + +struct ManifestWriteResult { + ManifestVisibility visibility{ManifestVisibility::NotVisible}; + std::optional error; + std::uint64_t generation{}; + ManifestPhase phase{ManifestPhase::Prepared}; + std::array digest{}; +}; + +using ManifestStoreOpenResult = + std::variant, ManifestStoreError>; + +[[nodiscard]] inline std::optional TryNextManifestGeneration( + std::uint64_t current) noexcept { + if (current == 0 || current == UINT64_MAX) return std::nullopt; + return current + 1; +} + +class ManifestStore { + public: + ManifestStore(const ManifestStore&) = delete; + ManifestStore& operator=(const ManifestStore&) = delete; + ~ManifestStore(); + + // Creates a new private directory; EEXIST is always an error. The supplied + // inventory is validated and persisted in Prepared phase before success. + [[nodiscard]] static ManifestStoreOpenResult CreateNew( + const std::string& directory, const EpochCandidate& candidate, + const OperationId& creation_operation_id, + IManifestFileOps* test_hooks = nullptr) noexcept; + + // Recovery-only. Opens and locks existing files without creating or + // promoting anything. A persisted ACTIVE epoch is never adopted. + [[nodiscard]] static ManifestStoreOpenResult OpenExisting( + const std::string& directory, IManifestFileOps* test_hooks = nullptr) noexcept; + + [[nodiscard]] bool recovery_only() const noexcept; + [[nodiscard]] bool writable() const noexcept; + // Returns the last complete in-memory snapshot immediately. During a write + // it may reflect the prior durable generation until the write outcome lands. + [[nodiscard]] ManifestV1 snapshot() const; + [[nodiscard]] std::array digest() const; + + // CAS transition in this store's already-owned epoch. OpenExisting handles + // are always read-only. Post-rename directory-sync failure is reported as + // VisibleDurabilityUnknown and permanently disables writes on this handle. + [[nodiscard]] ManifestWriteResult Transition( + std::uint64_t expected_generation, const std::array& expected_digest, + ManifestPhase next_phase, const OperationId& operation_id); + + private: + ManifestStore(int directory_fd, int lock_fd, std::string directory, + ManifestV1 manifest, std::array digest, + bool recovery_only, IManifestFileOps* test_hooks); + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace rateguard::supervisor diff --git a/src/supervisor/runtime_owner.cpp b/src/supervisor/runtime_owner.cpp new file mode 100644 index 0000000..5e4331a --- /dev/null +++ b/src/supervisor/runtime_owner.cpp @@ -0,0 +1,704 @@ +#include "supervisor/runtime_owner.h" + +#include "platform/file_io.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { +namespace { + +using Json = nlohmann::json; +constexpr char kLockName[] = "owner.lock"; +constexpr char kAnchorName[] = "runtime-anchor.json"; +constexpr char kAnchorTempName[] = "runtime-anchor.tmp"; +constexpr std::size_t kMaxRuntimeAnchorBytes = 4U * 1024U * 1024U; +constexpr std::size_t kMaxRootPathBytes = 4096; + +class AnchorJsonGuard final : public nlohmann::json_sax { + public: + using string_t = Json::string_t; + using binary_t = Json::binary_t; + using number_integer_t = Json::number_integer_t; + using number_unsigned_t = Json::number_unsigned_t; + using number_float_t = Json::number_float_t; + bool null() override { return true; } + bool boolean(bool) override { return true; } + bool number_integer(number_integer_t) override { return true; } + bool number_unsigned(number_unsigned_t) override { return true; } + bool number_float(number_float_t, const string_t&) override { return false; } + bool string(string_t&) override { return true; } + bool binary(binary_t&) override { return false; } + bool start_object(std::size_t) override { + if (depth_ >= 2) return false; + ++depth_; + seen_keys_.push_back(0); + return true; + } + bool key(string_t& value) override { + if (seen_keys_.empty()) return false; + std::uint8_t bit = 0; + if (depth_ == 1) { + if (value == "anchor") bit = 1; + else if (value == "sha256") bit = 2; + } else if (depth_ == 2) { + if (value == "domain_id") bit = 1; + else if (value == "root_path") bit = 2; + else if (value == "schema_version") bit = 4; + } + if (bit == 0 || (seen_keys_.back() & bit) != 0) return false; + seen_keys_.back() = static_cast(seen_keys_.back() | bit); + return true; + } + bool end_object() override { + if (seen_keys_.empty() || depth_ == 0) return false; + seen_keys_.pop_back(); + --depth_; + return true; + } + bool start_array(std::size_t) override { return false; } + bool end_array() override { return false; } + bool parse_error(std::size_t, const std::string&, const nlohmann::detail::exception&) override { + return false; + } + private: + std::size_t depth_{}; + std::vector seen_keys_; +}; + +using platform::file::Sync; +using platform::file::UniqueFd; +using platform::file::WriteAll; + +bool Fail(IRuntimeOwnerIo* io, RuntimeOwnerIoPoint point) noexcept { + return io != nullptr && io->FailAt(point); +} + +bool AllZero(const auto& data) noexcept { + return std::all_of(data.begin(), data.end(), [](std::uint8_t b) { return b == 0; }); +} + +bool ReadAllAt(int fd, std::string& out, std::size_t size) { + out.resize(size); + std::size_t offset = 0; + while (offset < size) { + const auto n = ::pread(fd, out.data() + offset, size - offset, + static_cast(offset)); + if (n < 0) { + if (errno == EINTR) continue; + return false; + } + if (n == 0) return false; + offset += static_cast(n); + } + char extra = 0; + ssize_t n; + do { n = ::pread(fd, &extra, 1, static_cast(size)); } while (n < 0 && errno == EINTR); + return n == 0; +} + +bool ValidAbsoluteInput(const std::string& path) noexcept { + return !path.empty() && path.front() == '/' && path.size() < kMaxRootPathBytes && + path.back() != '/' && path.find('\0') == std::string::npos; +} + +bool ValidModeOwner(const struct stat& st, mode_t mode) noexcept { + return st.st_uid == ::geteuid() && (st.st_mode & 07777) == mode; +} + +bool ValidRegular(const struct stat& st, mode_t mode) noexcept { + return S_ISREG(st.st_mode) && ValidModeOwner(st, mode) && st.st_nlink == 1; +} + +bool ValidLockFile(const struct stat& st) noexcept { + return ValidRegular(st, 0600) && st.st_size == 0; +} + +bool SameInode(const struct stat& a, const struct stat& b) noexcept { + return a.st_dev == b.st_dev && a.st_ino == b.st_ino; +} + +bool AnchorTempAbsent(int root_fd) noexcept { + struct stat st {}; + if (::fstatat(root_fd, kAnchorTempName, &st, AT_SYMLINK_NOFOLLOW) == 0) return false; + return errno == ENOENT; +} + +std::string Hex(const auto& bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string result; + result.reserve(bytes.size() * 2); + for (std::uint8_t b : bytes) { + result.push_back(digits[b >> 4]); + result.push_back(digits[b & 0x0f]); + } + return result; +} + +template +bool ParseHex(std::string_view input, std::array& output) noexcept { + if (input.size() != N * 2) return false; + const auto nibble = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return -1; + }; + for (std::size_t i = 0; i < N; ++i) { + const int hi = nibble(input[i * 2]); + const int lo = nibble(input[i * 2 + 1]); + if (hi < 0 || lo < 0) return false; + output[i] = static_cast((hi << 4) | lo); + } + return true; +} + +using Digest = std::array; +bool Sha256(std::string_view input, Digest& output) noexcept { + unsigned int length = 0; + return EVP_Digest(input.data(), static_cast(input.size()), output.data(), + &length, EVP_sha256(), nullptr) == 1 && output.size() == length; +} + +struct AnchorRecord { + RuntimeDomainId domain_id{}; + std::string root_path; + Digest digest{}; +}; + +bool EncodeAnchor(const RuntimeDomainId& domain_id, const std::string& root_path, + std::string& envelope, Digest& digest) { + Json payload = Json::object(); + payload["domain_id"] = Hex(domain_id); + payload["root_path"] = root_path; + payload["schema_version"] = 1; + const std::string payload_bytes = payload.dump(); + if (!Sha256(payload_bytes, digest)) return false; + Json whole = Json::object(); + whole["anchor"] = std::move(payload); + whole["sha256"] = Hex(digest); + envelope = whole.dump(); + return envelope.size() <= kMaxRuntimeAnchorBytes; +} + +bool DecodeAnchor(std::string_view envelope, AnchorRecord& out) { + if (envelope.empty() || envelope.size() > kMaxRuntimeAnchorBytes) return false; + AnchorJsonGuard guard; + if (!Json::sax_parse(envelope.begin(), envelope.end(), &guard)) return false; + Json whole = Json::parse(envelope.begin(), envelope.end(), nullptr, false); + if (whole.is_discarded() || !whole.is_object() || whole.size() != 2 || + !whole.contains("anchor") || !whole.contains("sha256")) return false; + const Json& payload = whole.at("anchor"); + if (!payload.is_object() || payload.size() != 3 || + !payload.contains("domain_id") || !payload.contains("root_path") || + !payload.contains("schema_version") || !payload.at("domain_id").is_string() || + !payload.at("root_path").is_string() || + !payload.at("schema_version").is_number_unsigned() || + payload.at("schema_version").get() != 1 || + !whole.at("sha256").is_string()) return false; + if (!ParseHex<16>(payload.at("domain_id").get_ref(), out.domain_id)) + return false; + out.root_path = payload.at("root_path").get(); + if (!ValidAbsoluteInput(out.root_path)) return false; + const std::string payload_bytes = payload.dump(); + Digest computed{}; + if (!Sha256(payload_bytes, computed) || + !ParseHex<32>(whole.at("sha256").get_ref(), out.digest) || + computed != out.digest) return false; + Json canonical = Json::object(); + canonical["anchor"] = payload; + canonical["sha256"] = Hex(computed); + if (canonical.dump() != envelope) return false; + return true; +} + +struct CanonicalLocation { + UniqueFd parent_fd; + struct stat parent_stat {}; + std::string parent_path; + std::string leaf; + std::string full_path; +}; + +std::optional ResolveLocation(const std::string& input, + IRuntimeOwnerIo* io) { + if (!ValidAbsoluteInput(input)) return std::nullopt; + const auto split = input.find_last_of('/'); + const std::string parent_input = split == 0 ? "/" : input.substr(0, split); + const std::string leaf = input.substr(split + 1); + if (leaf.empty() || leaf == "." || leaf == "..") return std::nullopt; + if (Fail(io, RuntimeOwnerIoPoint::ResolveParent)) return std::nullopt; + std::unique_ptr resolved(::realpath(parent_input.c_str(), nullptr), + &std::free); + if (!resolved) return std::nullopt; + std::string parent_path(resolved.get()); + UniqueFd parent_fd(::open(parent_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)); + if (parent_fd.get() < 0) return std::nullopt; + struct stat parent_stat {}; + if (::fstat(parent_fd.get(), &parent_stat) != 0 || !S_ISDIR(parent_stat.st_mode)) + return std::nullopt; + const std::string full = parent_path == "/" ? "/" + leaf : parent_path + "/" + leaf; + if (full.size() >= kMaxRootPathBytes) return std::nullopt; + return CanonicalLocation{std::move(parent_fd), parent_stat, std::move(parent_path), + leaf, full}; +} + +bool RootEntryMatches(int parent_fd, const std::string& leaf, int root_fd, + const struct stat& expected_root) noexcept { + struct stat fd_stat {}, entry_stat {}; + return ::fstat(root_fd, &fd_stat) == 0 && ::fstatat(parent_fd, leaf.c_str(), &entry_stat, + AT_SYMLINK_NOFOLLOW) == 0 && SameInode(fd_stat, expected_root) && + SameInode(entry_stat, expected_root) && S_ISDIR(entry_stat.st_mode); +} + +std::variant ReadAnchor(int root_fd, int anchor_fd, + IRuntimeOwnerIo* io) { + if (!AnchorTempAbsent(root_fd)) return RuntimeOwnerError::InvalidAnchor; + if (Fail(io, RuntimeOwnerIoPoint::CheckAnchorIdentity)) + return RuntimeOwnerError::AnchorIdentityChanged; + struct stat fd_stat {}, entry_stat {}; + if (::fstat(anchor_fd, &fd_stat) != 0 || + ::fstatat(root_fd, kAnchorName, &entry_stat, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(fd_stat, entry_stat) || !ValidRegular(fd_stat, 0600)) + return RuntimeOwnerError::AnchorIdentityChanged; + if (fd_stat.st_size < 0 || static_cast(fd_stat.st_size) > kMaxRuntimeAnchorBytes) + return RuntimeOwnerError::InvalidAnchor; + if (Fail(io, RuntimeOwnerIoPoint::ReadAnchor)) return RuntimeOwnerError::IoFailure; + std::string bytes; + if (!ReadAllAt(anchor_fd, bytes, static_cast(fd_stat.st_size))) + return RuntimeOwnerError::IoFailure; + AnchorRecord record; + if (!DecodeAnchor(bytes, record)) return RuntimeOwnerError::InvalidAnchor; + return record; +} + +bool RootHasOnlyAnchorAndLock(int root_fd, IRuntimeOwnerIo* io) noexcept { + if (Fail(io, RuntimeOwnerIoPoint::EnumerateRoot)) return false; + const int scan_fd = ::openat(root_fd, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (scan_fd < 0) return false; + DIR* directory = ::fdopendir(scan_fd); + if (directory == nullptr) { ::close(scan_fd); return false; } + std::size_t count = 0; + bool valid = true; + errno = 0; + while (dirent* entry = ::readdir(directory)) { + const std::string_view name(entry->d_name); + if (name == "." || name == "..") continue; + ++count; + if (name != kLockName && name != kAnchorName) valid = false; + if (count > 2) valid = false; + } + if (errno != 0) valid = false; + ::closedir(directory); + return valid && count == 2; +} + +std::optional CheckState(const detail::RuntimeOwnerState& state, + IRuntimeOwnerIo* io) noexcept; + +} // namespace + +namespace detail { +struct RuntimeOwnerState { + int parent_fd{-1}; + int root_fd{-1}; + int lock_fd{-1}; + int anchor_fd{-1}; + pid_t owner_pid{}; + RuntimeOwnerMode mode{RuntimeOwnerMode::RecoveryRequired}; + mutable std::atomic latched_error{}; + RuntimeDomainId domain_id{}; + Digest anchor_digest{}; + struct stat parent_stat {}; + struct stat root_stat {}; + struct stat lock_stat {}; + struct stat anchor_stat {}; + std::string parent_path; + std::string leaf; + std::string root_path; + IRuntimeOwnerIo* test_io{}; + std::mutex claim_mutex; + bool initial_claimed{}; + bool claim_in_progress{}; + ~RuntimeOwnerState() { + if (anchor_fd >= 0) ::close(anchor_fd); + if (lock_fd >= 0) ::close(lock_fd); + if (root_fd >= 0) ::close(root_fd); + if (parent_fd >= 0) ::close(parent_fd); + } +}; +} // namespace detail + +namespace { + +std::optional Latched(const detail::RuntimeOwnerState& state) noexcept { + const auto value = state.latched_error.load(std::memory_order_acquire); + if (value == 0) return std::nullopt; + return static_cast(value - 1); +} + +RuntimeOwnerError Latch(const detail::RuntimeOwnerState& state, RuntimeOwnerError error) noexcept { + const auto desired = static_cast(error) + 1; + std::uint16_t expected = 0; + if (state.latched_error.compare_exchange_strong(expected, desired, + std::memory_order_acq_rel, std::memory_order_acquire)) return error; + return static_cast(expected - 1); +} + +std::optional CheckState(const detail::RuntimeOwnerState& state, + IRuntimeOwnerIo* io) noexcept { + try { + if (const auto previous = Latched(state)) return previous; + const auto invalid = [&](RuntimeOwnerError error) -> std::optional { + return Latch(state, error); + }; + if (::getpid() != state.owner_pid) return invalid(RuntimeOwnerError::OwnerProcessChanged); + if (Fail(io, RuntimeOwnerIoPoint::CheckRootIdentity) || + !RootEntryMatches(state.parent_fd, state.leaf, state.root_fd, state.root_stat)) + return invalid(RuntimeOwnerError::RootIdentityChanged); + struct stat root_stat {}, parent_stat {}, lock_fd_stat {}, lock_entry_stat {}; + if (::fstat(state.root_fd, &root_stat) != 0 || !S_ISDIR(root_stat.st_mode) || + !ValidModeOwner(root_stat, 0700) || !SameInode(root_stat, state.root_stat)) + return invalid(RuntimeOwnerError::RootIdentityChanged); + if (::fstat(state.parent_fd, &parent_stat) != 0 || !S_ISDIR(parent_stat.st_mode) || + !SameInode(parent_stat, state.parent_stat)) return invalid(RuntimeOwnerError::RootIdentityChanged); + auto current = ResolveLocation(state.root_path, io); + if (!current || !SameInode(current->parent_stat, state.parent_stat) || + current->leaf != state.leaf || current->full_path != state.root_path) + return invalid(RuntimeOwnerError::RootPathMismatch); + if (Fail(io, RuntimeOwnerIoPoint::CheckLockIdentity) || + ::fstat(state.lock_fd, &lock_fd_stat) != 0 || + ::fstatat(state.root_fd, kLockName, &lock_entry_stat, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(lock_fd_stat, state.lock_stat) || !SameInode(lock_entry_stat, state.lock_stat) || + !ValidLockFile(lock_fd_stat) || !ValidLockFile(lock_entry_stat)) + return invalid(RuntimeOwnerError::LockIdentityChanged); + if (::flock(state.lock_fd, LOCK_EX | LOCK_NB) != 0) return invalid(RuntimeOwnerError::LockBusy); + auto anchor = ReadAnchor(state.root_fd, state.anchor_fd, io); + if (auto* error = std::get_if(&anchor)) return invalid(*error); + const auto& record = std::get(anchor); + if (record.domain_id != state.domain_id) return invalid(RuntimeOwnerError::DomainMismatch); + if (record.root_path != state.root_path) return invalid(RuntimeOwnerError::RootPathMismatch); + if (record.digest != state.anchor_digest) return invalid(RuntimeOwnerError::InvalidAnchor); + return std::nullopt; + } catch (...) { + return Latch(state, RuntimeOwnerError::AllocationFailure); + } +} + +std::variant DupRoot(const detail::RuntimeOwnerState& state, + IRuntimeOwnerIo* io) noexcept { + const auto checked = CheckState(state, io); + if (checked.has_value()) return *checked; + if (Fail(io, RuntimeOwnerIoPoint::DuplicateRoot)) + return Latch(state, RuntimeOwnerError::IoFailure); + const int duplicate = ::fcntl(state.root_fd, F_DUPFD_CLOEXEC, 0); + if (duplicate < 0) + return Latch(state, RuntimeOwnerError::IoFailure); + const auto after_dup = CheckState(state, io); + if (after_dup.has_value()) { + ::close(duplicate); + return *after_dup; + } + return duplicate; +} + +bool DurableWriteAnchor(int root_fd, int lock_fd, const std::string& bytes, + IRuntimeOwnerIo* io, RuntimeOwnerError& error) noexcept { + if (Fail(io, RuntimeOwnerIoPoint::CreateAnchorTemp)) { + error = RuntimeOwnerError::IoFailure; + return false; + } + UniqueFd temp(::openat(root_fd, kAnchorTempName, + O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC | O_NOFOLLOW, 0600)); + if (temp.get() < 0) { error = RuntimeOwnerError::IoFailure; return false; } + struct stat st {}; + if (::fchmod(temp.get(), 0600) != 0 || ::fstat(temp.get(), &st) != 0 || + !ValidRegular(st, 0600)) { + error = RuntimeOwnerError::IoFailure; + if (!Fail(io, RuntimeOwnerIoPoint::CleanupTemp)) (void)::unlinkat(root_fd, kAnchorTempName, 0); + return false; + } + if (Fail(io, RuntimeOwnerIoPoint::WriteAnchor) || !WriteAll(temp.get(), bytes.data(), bytes.size()) || + Fail(io, RuntimeOwnerIoPoint::SyncAnchor) || !Sync(temp.get())) { + error = RuntimeOwnerError::IoFailure; + if (!Fail(io, RuntimeOwnerIoPoint::CleanupTemp)) (void)::unlinkat(root_fd, kAnchorTempName, 0); + return false; + } + const int temp_fd = temp.release(); + if (::close(temp_fd) != 0) { + error = RuntimeOwnerError::IoFailure; + if (!Fail(io, RuntimeOwnerIoPoint::CleanupTemp)) (void)::unlinkat(root_fd, kAnchorTempName, 0); + return false; + } + struct stat lock_fd_stat {}, lock_entry_stat {}; + if (Fail(io, RuntimeOwnerIoPoint::CheckLockIdentity) || + ::fstat(lock_fd, &lock_fd_stat) != 0 || + ::fstatat(root_fd, kLockName, &lock_entry_stat, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(lock_fd_stat, lock_entry_stat) || !ValidLockFile(lock_fd_stat)) { + error = RuntimeOwnerError::LockIdentityChanged; + if (!Fail(io, RuntimeOwnerIoPoint::CleanupTemp)) (void)::unlinkat(root_fd, kAnchorTempName, 0); + return false; + } + if (Fail(io, RuntimeOwnerIoPoint::RenameAnchor) || + ::renameat(root_fd, kAnchorTempName, root_fd, kAnchorName) != 0) { + error = RuntimeOwnerError::IoFailure; + if (!Fail(io, RuntimeOwnerIoPoint::CleanupTemp)) (void)::unlinkat(root_fd, kAnchorTempName, 0); + return false; + } + if (Fail(io, RuntimeOwnerIoPoint::SyncRoot) || !Sync(root_fd)) { + error = RuntimeOwnerError::DurabilityUncertain; + return false; + } + return true; +} + +} // namespace + +RuntimeOwner::~RuntimeOwner() = default; + +RuntimeOwnerOpenResult RuntimeOwner::CreateNew(const std::string& absolute_root, + const RuntimeDomainId& domain_id, + IRuntimeOwnerIo* io) noexcept { + try { + if (AllZero(domain_id)) return RuntimeOwnerError::InvalidDomainId; + auto location = ResolveLocation(absolute_root, io); + if (!location) return RuntimeOwnerError::InvalidPath; + std::string anchor_bytes; + Digest anchor_digest{}; + if (!EncodeAnchor(domain_id, location->full_path, anchor_bytes, anchor_digest)) + return RuntimeOwnerError::InvalidAnchor; + if (Fail(io, RuntimeOwnerIoPoint::MkdirRoot)) return RuntimeOwnerError::IoFailure; + if (::mkdirat(location->parent_fd.get(), location->leaf.c_str(), 0700) != 0) + return errno == EEXIST ? RuntimeOwnerError::AlreadyExists : RuntimeOwnerError::IoFailure; + if (Fail(io, RuntimeOwnerIoPoint::SyncParent) || !Sync(location->parent_fd.get())) + return RuntimeOwnerError::DurabilityUncertain; + if (Fail(io, RuntimeOwnerIoPoint::OpenRoot)) return RuntimeOwnerError::InvalidRoot; + UniqueFd root_fd(::openat(location->parent_fd.get(), location->leaf.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)); + if (root_fd.get() < 0 || ::fchmod(root_fd.get(), 0700) != 0 || + Fail(io, RuntimeOwnerIoPoint::ValidateRoot)) return RuntimeOwnerError::InvalidRoot; + struct stat root_stat {}; + if (::fstat(root_fd.get(), &root_stat) != 0 || !S_ISDIR(root_stat.st_mode) || + !ValidModeOwner(root_stat, 0700)) return RuntimeOwnerError::InvalidRoot; + if (Fail(io, RuntimeOwnerIoPoint::CreateLock)) return RuntimeOwnerError::InvalidLock; + UniqueFd lock_fd(::openat(root_fd.get(), kLockName, + O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC | O_NOFOLLOW, 0600)); + if (lock_fd.get() < 0 || ::fchmod(lock_fd.get(), 0600) != 0) + return RuntimeOwnerError::InvalidLock; + struct stat lock_stat {}; + if (::fstat(lock_fd.get(), &lock_stat) != 0 || !ValidLockFile(lock_stat)) + return RuntimeOwnerError::InvalidLock; + if (Fail(io, RuntimeOwnerIoPoint::AcquireLock)) return RuntimeOwnerError::LockBusy; + if (::flock(lock_fd.get(), LOCK_EX | LOCK_NB) != 0) + return RuntimeOwnerError::LockBusy; + if (Fail(io, RuntimeOwnerIoPoint::SyncLock) || !Sync(lock_fd.get()) || + Fail(io, RuntimeOwnerIoPoint::SyncRoot) || !Sync(root_fd.get())) + return RuntimeOwnerError::DurabilityUncertain; + + auto state = std::make_shared(); + state->owner_pid = ::getpid(); + state->mode = RuntimeOwnerMode::Fresh; + state->domain_id = domain_id; + state->anchor_digest = anchor_digest; + state->parent_stat = location->parent_stat; + state->root_stat = root_stat; + state->lock_stat = lock_stat; + state->parent_path = location->parent_path; + state->leaf = location->leaf; + state->root_path = location->full_path; + state->test_io = io; + auto owner = std::unique_ptr(new RuntimeOwner(state)); + state->parent_fd = location->parent_fd.release(); + state->root_fd = root_fd.release(); + state->lock_fd = lock_fd.release(); + RuntimeOwnerError write_error = RuntimeOwnerError::IoFailure; + if (!DurableWriteAnchor(state->root_fd, state->lock_fd, anchor_bytes, io, write_error)) + return write_error; + UniqueFd anchor_fd(::openat(state->root_fd, kAnchorName, + O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW)); + if (anchor_fd.get() < 0) return RuntimeOwnerError::DurabilityUncertain; + struct stat anchor_stat {}; + if (::fstat(anchor_fd.get(), &anchor_stat) != 0 || !ValidRegular(anchor_stat, 0600)) + return RuntimeOwnerError::DurabilityUncertain; + state->anchor_stat = anchor_stat; + state->anchor_fd = anchor_fd.release(); + const auto final_check = owner->ValidateOwnership(); + if (auto* error = std::get_if(&final_check)) return *error; + return owner; + } catch (...) { + return RuntimeOwnerError::AllocationFailure; + } +} + +RuntimeOwnerOpenResult RuntimeOwner::OpenExisting(const std::string& absolute_root, + const RuntimeDomainId& expected_domain_id, + IRuntimeOwnerIo* io) noexcept { + try { + if (AllZero(expected_domain_id)) return RuntimeOwnerError::InvalidDomainId; + auto location = ResolveLocation(absolute_root, io); + if (!location) return RuntimeOwnerError::InvalidPath; + if (Fail(io, RuntimeOwnerIoPoint::OpenRoot)) return RuntimeOwnerError::InvalidRoot; + UniqueFd root_fd(::openat(location->parent_fd.get(), location->leaf.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)); + if (root_fd.get() < 0) return errno == ENOENT ? RuntimeOwnerError::NotFound + : RuntimeOwnerError::InvalidRoot; + if (Fail(io, RuntimeOwnerIoPoint::ValidateRoot)) return RuntimeOwnerError::InvalidRoot; + struct stat root_stat {}; + if (::fstat(root_fd.get(), &root_stat) != 0 || !S_ISDIR(root_stat.st_mode) || + !ValidModeOwner(root_stat, 0700)) return RuntimeOwnerError::InvalidRoot; + if (Fail(io, RuntimeOwnerIoPoint::OpenLock)) return RuntimeOwnerError::InvalidLock; + UniqueFd lock_fd(::openat(root_fd.get(), kLockName, + O_RDWR | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW)); + if (lock_fd.get() < 0) return RuntimeOwnerError::InvalidLock; + struct stat lock_stat {}; + if (::fstat(lock_fd.get(), &lock_stat) != 0 || !ValidLockFile(lock_stat)) + return RuntimeOwnerError::InvalidLock; + if (Fail(io, RuntimeOwnerIoPoint::AcquireLock)) return RuntimeOwnerError::LockBusy; + if (::flock(lock_fd.get(), LOCK_EX | LOCK_NB) != 0) return RuntimeOwnerError::LockBusy; + if (Fail(io, RuntimeOwnerIoPoint::CheckLockIdentity)) return RuntimeOwnerError::LockIdentityChanged; + struct stat lock_entry {}; + if (::fstatat(root_fd.get(), kLockName, &lock_entry, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(lock_stat, lock_entry) || !ValidLockFile(lock_entry)) + return RuntimeOwnerError::LockIdentityChanged; + if (Fail(io, RuntimeOwnerIoPoint::OpenAnchor)) return RuntimeOwnerError::AnchorMissing; + UniqueFd anchor_fd(::openat(root_fd.get(), kAnchorName, + O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW)); + if (anchor_fd.get() < 0) return errno == ENOENT ? RuntimeOwnerError::AnchorMissing + : RuntimeOwnerError::InvalidAnchor; + struct stat anchor_stat {}; + if (::fstat(anchor_fd.get(), &anchor_stat) != 0 || !ValidRegular(anchor_stat, 0600)) + return RuntimeOwnerError::InvalidAnchor; + if (anchor_stat.st_size < 0 || + static_cast(anchor_stat.st_size) > kMaxRuntimeAnchorBytes) + return RuntimeOwnerError::InvalidAnchor; + if (Fail(io, RuntimeOwnerIoPoint::ReadAnchor)) return RuntimeOwnerError::IoFailure; + std::string bytes; + if (!ReadAllAt(anchor_fd.get(), bytes, static_cast(anchor_stat.st_size))) + return RuntimeOwnerError::IoFailure; + AnchorRecord anchor; + if (!DecodeAnchor(bytes, anchor)) return RuntimeOwnerError::InvalidAnchor; + if (anchor.domain_id != expected_domain_id) return RuntimeOwnerError::DomainMismatch; + if (anchor.root_path != location->full_path) return RuntimeOwnerError::RootPathMismatch; + struct stat anchor_entry {}; + if (Fail(io, RuntimeOwnerIoPoint::CheckAnchorIdentity) || + ::fstatat(root_fd.get(), kAnchorName, &anchor_entry, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(anchor_stat, anchor_entry)) return RuntimeOwnerError::AnchorIdentityChanged; + + auto state = std::make_shared(); + state->owner_pid = ::getpid(); + state->mode = RuntimeOwnerMode::RecoveryRequired; + state->domain_id = anchor.domain_id; + state->anchor_digest = anchor.digest; + state->parent_stat = location->parent_stat; + state->root_stat = root_stat; + state->lock_stat = lock_stat; + state->anchor_stat = anchor_stat; + state->parent_path = location->parent_path; + state->leaf = location->leaf; + state->root_path = location->full_path; + state->test_io = io; + state->parent_fd = location->parent_fd.release(); + state->root_fd = root_fd.release(); + state->lock_fd = lock_fd.release(); + state->anchor_fd = anchor_fd.release(); + auto owner = std::unique_ptr(new RuntimeOwner(std::move(state))); + const auto final_check = owner->ValidateOwnership(); + if (auto* error = std::get_if(&final_check)) return *error; + return owner; + } catch (...) { + return RuntimeOwnerError::AllocationFailure; + } +} + +RuntimeOwnerMode RuntimeOwner::mode() const noexcept { + // A forked child must not inherit the parent's Fresh capability, even if + // the parent happened to fork while another thread held claim_mutex. + if (::getpid() != state_->owner_pid) return RuntimeOwnerMode::RecoveryRequired; + return Latched(*state_).has_value() ? RuntimeOwnerMode::RecoveryRequired : state_->mode; +} +const RuntimeDomainId& RuntimeOwner::domain_id() const noexcept { return state_->domain_id; } +const std::string& RuntimeOwner::root_path() const noexcept { return state_->root_path; } + +RuntimeOwnerCheck RuntimeOwner::ValidateOwnership() const noexcept { + const auto error = CheckState(*state_, state_->test_io); + return error.has_value() ? RuntimeOwnerCheck{*error} + : RuntimeOwnerCheck{std::monostate{}}; +} + +DuplicateFdResult RuntimeOwner::DuplicateRootFd() const noexcept { + return DupRoot(*state_, state_->test_io); +} + +InitialClaimResult RuntimeOwner::ClaimInitialEpoch(const EpochId& epoch_id) noexcept { + // Check process ownership before consulting mode or touching claim_mutex: + // after a multithreaded fork that mutex may be permanently locked in child. + if (::getpid() != state_->owner_pid) return RuntimeOwnerError::OwnerProcessChanged; + if (mode() != RuntimeOwnerMode::Fresh) return RuntimeOwnerError::RecoveryRequired; + if (AllZero(epoch_id)) return RuntimeOwnerError::InvalidEpochId; + { + std::lock_guard lock(state_->claim_mutex); + if (const auto previous = Latched(*state_)) return *previous; + if (state_->initial_claimed) return RuntimeOwnerError::InitialClaimAlreadyUsed; + if (state_->claim_in_progress) return RuntimeOwnerError::Busy; + state_->claim_in_progress = true; + } + const auto finish = [&](RuntimeOwnerError error, bool latch) -> InitialClaimResult { + std::lock_guard lock(state_->claim_mutex); + if (latch) error = Latch(*state_, error); + state_->claim_in_progress = false; + return error; + }; + const auto checked = CheckState(*state_, state_->test_io); + if (checked.has_value()) return finish(*checked, false); + if (!RootHasOnlyAnchorAndLock(state_->root_fd, state_->test_io)) + return finish(RuntimeOwnerError::UnexpectedRootEntry, true); + const auto final_check = CheckState(*state_, state_->test_io); + if (final_check.has_value()) return finish(*final_check, false); + std::lock_guard lock(state_->claim_mutex); + if (const auto previous = Latched(*state_)) { + state_->claim_in_progress = false; + return *previous; + } + state_->initial_claimed = true; + state_->claim_in_progress = false; + return InitialEpochClaim(state_, epoch_id); +} + +RuntimeOwnerCheck InitialEpochClaim::ValidateOwnership() const noexcept { + if (!state_) return RuntimeOwnerError::RecoveryRequired; + const auto error = CheckState(*state_, state_->test_io); + return error.has_value() ? RuntimeOwnerCheck{*error} + : RuntimeOwnerCheck{std::monostate{}}; +} + +RuntimeDomainId InitialEpochClaim::domain_id() const noexcept { + return state_ ? state_->domain_id : RuntimeDomainId{}; +} + +const std::string& InitialEpochClaim::root_path() const noexcept { + static const std::string kEmpty; + return state_ ? state_->root_path : kEmpty; +} + +DuplicateFdResult InitialEpochClaim::DuplicateRootFd() const noexcept { + if (!state_) return RuntimeOwnerError::RecoveryRequired; + return DupRoot(*state_, state_->test_io); +} + +} // namespace rateguard::supervisor diff --git a/src/supervisor/runtime_owner.h b/src/supervisor/runtime_owner.h new file mode 100644 index 0000000..4777e2d --- /dev/null +++ b/src/supervisor/runtime_owner.h @@ -0,0 +1,144 @@ +#pragma once + +// Exclusive ownership of one configured runtime root. This is not a process +// controller, durable epoch-fencing proof, or global lock across other paths. + +#include "supervisor/epoch_gate.h" + +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +using RuntimeDomainId = std::array; + +enum class RuntimeOwnerMode : std::uint8_t { Fresh, RecoveryRequired }; +enum class RuntimeOwnerIoPoint : std::uint8_t { + ResolveParent, + MkdirRoot, + SyncParent, + OpenRoot, + ValidateRoot, + CreateLock, + OpenLock, + OpenAnchor, + AcquireLock, + SyncLock, + SyncRoot, + CreateAnchorTemp, + WriteAnchor, + SyncAnchor, + RenameAnchor, + CheckRootIdentity, + CheckLockIdentity, + CheckAnchorIdentity, + ReadAnchor, + EnumerateRoot, + DuplicateRoot, + CleanupTemp, +}; + +class IRuntimeOwnerIo { + public: + virtual ~IRuntimeOwnerIo() = default; + [[nodiscard]] virtual bool FailAt(RuntimeOwnerIoPoint point) noexcept = 0; +}; + +enum class RuntimeOwnerError : std::uint8_t { + InvalidPath, + InvalidDomainId, + AlreadyExists, + NotFound, + InvalidRoot, + InvalidLock, + LockBusy, + InvalidAnchor, + AnchorMissing, + DomainMismatch, + RootPathMismatch, + OwnerProcessChanged, + RootIdentityChanged, + LockIdentityChanged, + AnchorIdentityChanged, + UnexpectedRootEntry, + RecoveryRequired, + InitialClaimAlreadyUsed, + Busy, + InvalidEpochId, + IoFailure, + DurabilityUncertain, + AllocationFailure, +}; + +using RuntimeOwnerOpenResult = + std::variant, RuntimeOwnerError>; +using RuntimeOwnerCheck = std::variant; +using DuplicateFdResult = std::variant; + +namespace detail { +struct RuntimeOwnerState; +} + +class InitialEpochClaim { + public: + InitialEpochClaim(const InitialEpochClaim&) = delete; + InitialEpochClaim& operator=(const InitialEpochClaim&) = delete; + InitialEpochClaim(InitialEpochClaim&&) noexcept = default; + InitialEpochClaim& operator=(InitialEpochClaim&&) noexcept = default; + + [[nodiscard]] const EpochId& epoch_id() const noexcept { return epoch_id_; } + // Use after ValidateOwnership(); a moved-from claim returns default metadata. + [[nodiscard]] RuntimeDomainId domain_id() const noexcept; + [[nodiscard]] const std::string& root_path() const noexcept; + [[nodiscard]] RuntimeOwnerCheck ValidateOwnership() const noexcept; + // Caller owns the returned CLOEXEC descriptor and must close it. + [[nodiscard]] DuplicateFdResult DuplicateRootFd() const noexcept; + + private: + friend class RuntimeOwner; + InitialEpochClaim(std::shared_ptr state, EpochId epoch_id) noexcept + : state_(std::move(state)), epoch_id_(epoch_id) {} + std::shared_ptr state_; + EpochId epoch_id_{}; +}; + +using InitialClaimResult = std::variant; + +class RuntimeOwner { + public: + RuntimeOwner(const RuntimeOwner&) = delete; + RuntimeOwner& operator=(const RuntimeOwner&) = delete; + ~RuntimeOwner(); + + // Must be an absolute, new path. EEXIST never initializes an existing root. + [[nodiscard]] static RuntimeOwnerOpenResult CreateNew( + const std::string& absolute_root, const RuntimeDomainId& domain_id, + IRuntimeOwnerIo* test_io = nullptr) noexcept; + + // Opens existing files only. Every successful OpenExisting handle is + // RecoveryRequired and has no initial-bootstrap claim capability. + [[nodiscard]] static RuntimeOwnerOpenResult OpenExisting( + const std::string& absolute_root, const RuntimeDomainId& expected_domain_id, + IRuntimeOwnerIo* test_io = nullptr) noexcept; + + [[nodiscard]] RuntimeOwnerMode mode() const noexcept; + [[nodiscard]] const RuntimeDomainId& domain_id() const noexcept; + [[nodiscard]] const std::string& root_path() const noexcept; + [[nodiscard]] RuntimeOwnerCheck ValidateOwnership() const noexcept; + // Caller owns the returned CLOEXEC descriptor and must close it. + [[nodiscard]] DuplicateFdResult DuplicateRootFd() const noexcept; + // A new root can issue exactly one in-process bootstrap claim. This only + // proves fresh-root ownership, not that a process has launched safely. + [[nodiscard]] InitialClaimResult ClaimInitialEpoch(const EpochId& epoch_id) noexcept; + + private: + explicit RuntimeOwner(std::shared_ptr state) noexcept + : state_(std::move(state)) {} + std::shared_ptr state_; +}; + +} // namespace rateguard::supervisor diff --git a/src/supervisor/unix_http_transport.cpp b/src/supervisor/unix_http_transport.cpp new file mode 100644 index 0000000..fed7d7b --- /dev/null +++ b/src/supervisor/unix_http_transport.cpp @@ -0,0 +1,333 @@ +#include "supervisor/unix_http_transport.h" + +#include "supervisor/http1_parser.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#include +#include +#include +#include +#endif + +namespace rateguard::supervisor { +namespace { + +UnixHttpFailure Failure(UnixHttpFailureReason reason, + bool request_possibly_sent = false) noexcept { + return UnixHttpFailure{reason, request_possibly_sent}; +} + +#if defined(__linux__) + +class ScopedFd { + public: + explicit ScopedFd(int fd = -1) noexcept : fd_(fd) {} + ~ScopedFd() { if (fd_ >= 0) (void)::close(fd_); } + ScopedFd(const ScopedFd&) = delete; + ScopedFd& operator=(const ScopedFd&) = delete; + [[nodiscard]] int get() const noexcept { return fd_; } + private: + int fd_; +}; + +struct SocketIdentity { + dev_t device{}; + ino_t inode{}; + uid_t owner{}; +}; + +bool SameSocketIdentity(const char* path, + const SocketIdentity& expected) noexcept { + struct stat st {}; + return ::lstat(path, &st) == 0 && S_ISSOCK(st.st_mode) && + st.st_dev == expected.device && st.st_ino == expected.inode && + st.st_uid == expected.owner; +} + +class NativeUnixHttpTransport final : public IUnixHttpTransport { + public: + NativeUnixHttpTransport(std::string canonical_path, SocketIdentity identity, + std::uint32_t expected_peer_uid, + platform::IClock& clock) noexcept + : path_(std::move(canonical_path)), identity_(identity), + expected_peer_uid_(expected_peer_uid), clock_(clock) {} + + UnixHttpResult RoundTrip( + UnixHttpMethod method, std::string_view target, + platform::MonoNanos absolute_deadline, + const std::atomic_bool& cancel_requested) noexcept override { + bool sent = false; + try { + if (!detail::IsValidOriginFormTarget(target)) + return Failure(UnixHttpFailureReason::InvalidTarget); + if (method != UnixHttpMethod::Get && method != UnixHttpMethod::Post) + return Failure(UnixHttpFailureReason::InvalidTarget); + + const auto initial_now = SafeNow(false); + if (std::holds_alternative(initial_now)) + return std::get(initial_now); + const auto now = std::get(initial_now).value; + if (absolute_deadline.value <= now || + absolute_deadline.value - now > kUnixHttpMaxCallDurationNs) { + return Failure(UnixHttpFailureReason::InvalidDeadline); + } + if (cancel_requested.load(std::memory_order_relaxed)) + return Failure(UnixHttpFailureReason::Cancelled); + + std::size_t active = active_calls_.load(std::memory_order_relaxed); + for (;;) { + if (active >= kUnixHttpMaxConcurrentCalls) + return Failure(UnixHttpFailureReason::Overloaded); + if (active_calls_.compare_exchange_weak(active, active + 1, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + break; + } + } + struct ActiveCallGuard { + std::atomic_size_t& count; + ~ActiveCallGuard() { count.fetch_sub(1, std::memory_order_release); } + } active_guard{active_calls_}; + + if (!SameSocketIdentity(path_.c_str(), identity_)) + return Failure(UnixHttpFailureReason::NotConfigured); + + ScopedFd socket(::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, + 0)); + if (socket.get() < 0) + return Failure(UnixHttpFailureReason::SocketFailure); + + sockaddr_un address{}; + address.sun_family = AF_UNIX; + if (path_.size() >= sizeof(address.sun_path)) + return Failure(UnixHttpFailureReason::NotConfigured); + std::memcpy(address.sun_path, path_.c_str(), path_.size() + 1); + const auto address_len = static_cast( + offsetof(sockaddr_un, sun_path) + path_.size() + 1); + const auto pre_connect = CheckBeforeIo(absolute_deadline, cancel_requested, sent); + if (std::holds_alternative(pre_connect)) + return std::get(pre_connect); + int connect_result = ::connect(socket.get(), + reinterpret_cast(&address), + address_len); + if (connect_result != 0 && errno != EINPROGRESS) + return Failure(UnixHttpFailureReason::SocketFailure); + if (connect_result != 0) { + const auto wait = Wait(socket.get(), POLLOUT, absolute_deadline, + cancel_requested, sent); + if (std::holds_alternative(wait)) + return std::get(wait); + int socket_error = 0; + socklen_t error_len = sizeof(socket_error); + if (::getsockopt(socket.get(), SOL_SOCKET, SO_ERROR, &socket_error, + &error_len) != 0 || socket_error != 0) { + return Failure(UnixHttpFailureReason::SocketFailure); + } + } + + if (!SameSocketIdentity(path_.c_str(), identity_)) + return Failure(UnixHttpFailureReason::NotConfigured, sent); + ucred peer{}; + socklen_t peer_len = sizeof(peer); + if (::getsockopt(socket.get(), SOL_SOCKET, SO_PEERCRED, &peer, + &peer_len) != 0 || peer_len != sizeof(peer) || + static_cast(peer.uid) != expected_peer_uid_) { + return Failure(UnixHttpFailureReason::PeerCredentialMismatch, sent); + } + + std::string request; + request.reserve(target.size() + 128); + request.append(method == UnixHttpMethod::Get ? "GET " : "POST "); + request.append(target); + request.append(" HTTP/1.1\r\nHost: docker\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); + if (request.size() > kUnixHttpMaxRequestBytes) + return Failure(UnixHttpFailureReason::InvalidTarget, sent); + + std::size_t written = 0; + while (written < request.size()) { + if (cancel_requested.load(std::memory_order_relaxed)) + return Failure(UnixHttpFailureReason::Cancelled, sent); + const auto wait = Wait(socket.get(), POLLOUT, absolute_deadline, + cancel_requested, sent); + if (std::holds_alternative(wait)) + return std::get(wait); + const auto ready = CheckBeforeIo(absolute_deadline, cancel_requested, sent); + if (std::holds_alternative(ready)) + return std::get(ready); + const auto count = ::send(socket.get(), request.data() + written, + request.size() - written, MSG_NOSIGNAL); + if (count > 0) { + sent = true; + written += static_cast(count); + continue; + } + if (count < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) + continue; + return Failure(UnixHttpFailureReason::SocketFailure, sent); + } + + std::vector wire; + wire.reserve(4'096); + std::array buffer{}; + for (;;) { + if (cancel_requested.load(std::memory_order_relaxed)) + return Failure(UnixHttpFailureReason::Cancelled, sent); + const auto wait = Wait(socket.get(), POLLIN, absolute_deadline, + cancel_requested, sent); + if (std::holds_alternative(wait)) + return std::get(wait); + const auto ready = CheckBeforeIo(absolute_deadline, cancel_requested, sent); + if (std::holds_alternative(ready)) + return std::get(ready); + const auto count = ::recv(socket.get(), buffer.data(), buffer.size(), 0); + if (count == 0) break; // EOF proves Connection: close framing complete. + if (count < 0) { + if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) continue; + return Failure(UnixHttpFailureReason::SocketFailure, sent); + } + const auto amount = static_cast(count); + if (amount > kUnixHttpMaxWireResponseBytes - wire.size()) + return Failure(UnixHttpFailureReason::ResponseTooLarge, sent); + wire.insert(wire.end(), buffer.begin(), + buffer.begin() + static_cast(amount)); + } + + auto parsed = detail::ParseHttpResponse(wire); + if (std::holds_alternative(parsed)) { + const auto error = std::get(parsed); + UnixHttpFailureReason reason = UnixHttpFailureReason::ProtocolError; + if (error == detail::HttpParseError::TooLarge) + reason = UnixHttpFailureReason::ResponseTooLarge; + else if (error == detail::HttpParseError::AllocationFailure) + reason = UnixHttpFailureReason::AllocationFailure; + return Failure(reason, sent); + } + const auto final_gate = CheckBeforeIo(absolute_deadline, cancel_requested, sent); + if (std::holds_alternative(final_gate)) + return std::get(final_gate); + return std::move(std::get(parsed)); + } catch (const std::bad_alloc&) { + return Failure(UnixHttpFailureReason::AllocationFailure, sent); + } catch (...) { + return Failure(UnixHttpFailureReason::SocketFailure, sent); + } + } + + private: + using WaitResult = std::variant; + + using ClockSample = std::variant; + + ClockSample SafeNow(bool sent) noexcept { + try { + if (!clock_.Healthy()) return Failure(UnixHttpFailureReason::ClockFailure, sent); + const auto sample = clock_.Now(); + if (!std::holds_alternative(sample) || !clock_.Healthy()) + return Failure(UnixHttpFailureReason::ClockFailure, sent); + return std::get(sample); + } catch (...) { + return Failure(UnixHttpFailureReason::ClockFailure, sent); + } + } + + WaitResult CheckBeforeIo(platform::MonoNanos deadline, + const std::atomic_bool& cancel_requested, + bool sent) noexcept { + if (cancel_requested.load(std::memory_order_relaxed)) + return Failure(UnixHttpFailureReason::Cancelled, sent); + const auto now_result = SafeNow(sent); + if (std::holds_alternative(now_result)) + return std::get(now_result); + if (std::get(now_result).value >= deadline.value) + return Failure(UnixHttpFailureReason::DeadlineExpired, sent); + return static_cast(0); + } + + WaitResult Wait(int fd, short events, platform::MonoNanos deadline, + const std::atomic_bool& cancel_requested, + bool sent) noexcept { + for (;;) { + if (cancel_requested.load(std::memory_order_relaxed)) + return Failure(UnixHttpFailureReason::Cancelled, sent); + const auto now_result = SafeNow(sent); + if (std::holds_alternative(now_result)) + return std::get(now_result); + const auto now = std::get(now_result).value; + if (now >= deadline.value) + return Failure(UnixHttpFailureReason::DeadlineExpired, sent); + const auto remaining_ns = deadline.value - now; + const auto remaining_ms = (remaining_ns + 999'999) / 1'000'000; + const int timeout_ms = static_cast(std::min( + remaining_ms, 100)); // Bound cancellation observation latency. + pollfd pfd{fd, events, 0}; + const int result = ::poll(&pfd, 1, timeout_ms); + if (result > 0) { + if ((pfd.revents & POLLNVAL) != 0) + return Failure(UnixHttpFailureReason::SocketFailure, sent); + return pfd.revents; + } + if (result == 0 || (result < 0 && errno == EINTR)) continue; + return Failure(UnixHttpFailureReason::SocketFailure, sent); + } + } + + std::string path_; + SocketIdentity identity_; + std::uint32_t expected_peer_uid_; + platform::IClock& clock_; + std::atomic_size_t active_calls_{0}; +}; + +#endif // __linux__ + +} // namespace + +UnixHttpTransportCreateResult CreateUnixHttpTransport( + const UnixHttpTransportConfig& config, platform::IClock& clock) noexcept { +#if defined(__linux__) + try { + if (config.socket_path.empty() || config.socket_path.find('\0') != std::string::npos || + config.socket_path.size() >= sizeof(sockaddr_un::sun_path)) { + return Failure(UnixHttpFailureReason::NotConfigured); + } + char* resolved_raw = ::realpath(config.socket_path.c_str(), nullptr); + if (resolved_raw == nullptr) + return Failure(UnixHttpFailureReason::NotConfigured); + std::unique_ptr resolved_owner(resolved_raw, &std::free); + std::string resolved(resolved_owner.get()); + if (resolved.empty() || resolved.size() >= sizeof(sockaddr_un::sun_path)) + return Failure(UnixHttpFailureReason::NotConfigured); + struct stat st {}; + if (::lstat(resolved.c_str(), &st) != 0 || !S_ISSOCK(st.st_mode) || + static_cast(st.st_uid) != config.expected_socket_owner_uid) { + return Failure(UnixHttpFailureReason::NotConfigured); + } + const SocketIdentity identity{st.st_dev, st.st_ino, st.st_uid}; + auto transport = std::make_unique( + std::move(resolved), identity, config.expected_peer_uid, clock); + return std::unique_ptr(std::move(transport)); + } catch (const std::bad_alloc&) { + return Failure(UnixHttpFailureReason::AllocationFailure); + } catch (...) { + return Failure(UnixHttpFailureReason::NotConfigured); + } +#else + (void)config; + (void)clock; + return Failure(UnixHttpFailureReason::UnsupportedPlatform); +#endif +} + +} // namespace rateguard::supervisor diff --git a/src/supervisor/unix_http_transport.h b/src/supervisor/unix_http_transport.h new file mode 100644 index 0000000..877d7da --- /dev/null +++ b/src/supervisor/unix_http_transport.h @@ -0,0 +1,91 @@ +#pragma once + +#include "platform/clock.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor { + +inline constexpr std::size_t kUnixHttpMaxTargetBytes = 2'048; +inline constexpr std::size_t kUnixHttpMaxRequestBytes = 4'096; +inline constexpr std::size_t kUnixHttpMaxHeaderBytes = 8'192; +inline constexpr std::size_t kUnixHttpMaxHeaderFields = 64; +inline constexpr std::size_t kUnixHttpMaxWireResponseBytes = 512 * 1'024; +inline constexpr std::size_t kUnixHttpMaxDecodedBodyBytes = 256 * 1'024; +inline constexpr std::size_t kUnixHttpMaxChunks = 4'096; +inline constexpr std::size_t kUnixHttpMaxChunkLineBytes = 128; +inline constexpr std::size_t kUnixHttpMaxConcurrentCalls = 4; +inline constexpr std::uint64_t kUnixHttpMaxCallDurationNs = 30'000'000'000ULL; +inline constexpr std::uint32_t kDockerRootUid = 0; +inline constexpr std::size_t kUnixHttpNativeSocketPathMaxBytes = 107; + +enum class UnixHttpMethod : std::uint8_t { Get, Post }; + +enum class UnixHttpFailureReason : std::uint8_t { + InvalidTarget, + InvalidDeadline, + NotConfigured, + UnsupportedPlatform, + PeerCredentialMismatch, + Overloaded, + Cancelled, + DeadlineExpired, + ClockFailure, + SocketFailure, + ProtocolError, + ResponseTooLarge, + AllocationFailure, +}; + +struct UnixHttpResponse { + std::uint16_t status{}; + std::vector body; +}; + +// `request_possibly_sent` is false until the first request byte is written. +// Once any byte is written, every later failure is reported as possibly sent. +struct UnixHttpFailure { + UnixHttpFailureReason reason{}; + bool request_possibly_sent{}; +}; + +using UnixHttpResult = std::variant; + +struct UnixHttpTransportConfig { + std::string socket_path; + std::uint32_t expected_peer_uid{kDockerRootUid}; + std::uint32_t expected_socket_owner_uid{kDockerRootUid}; +}; + +// Internal seam for one bounded HTTP exchange over a configured local socket. +// It has no retry, redirect, arbitrary header, or request-body facility. +class IUnixHttpTransport { + public: + virtual ~IUnixHttpTransport() = default; + + // Target is an origin-form path and optional query. The caller owns API + // version selection and must pass either a fixed endpoint (for example, + // /version) or an explicitly version-qualified endpoint (/vX/...). + [[nodiscard]] virtual UnixHttpResult RoundTrip( + UnixHttpMethod method, std::string_view origin_form_target, + platform::MonoNanos absolute_deadline, + const std::atomic_bool& cancel_requested) noexcept = 0; +}; + +using UnixHttpTransportCreateResult = + std::variant, UnixHttpFailure>; + +// Resolves and validates the socket once, then binds calls to its canonical +// path and device/inode/owner identity. Production controller config must keep +// both expected UID values at root (0). +[[nodiscard]] UnixHttpTransportCreateResult CreateUnixHttpTransport( + const UnixHttpTransportConfig& config, platform::IClock& clock) noexcept; + +} // namespace rateguard::supervisor diff --git a/tests/aggregate_metrics_test.cpp b/tests/aggregate_metrics_test.cpp new file mode 100644 index 0000000..6a08cfb --- /dev/null +++ b/tests/aggregate_metrics_test.cpp @@ -0,0 +1,101 @@ +#include "src/events/event_recorder.h" +#include "src/events/aggregate_metrics.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::events; +using namespace rateguard::events::metrics; + +void Check(bool condition, const char* name) { + if (!condition) { + std::cerr << "FAIL " << name << '\n'; + std::exit(1); + } +} + +void TestConcurrentUpdates() { + AggregateMetrics metrics; + constexpr std::size_t kThreads = 8; + constexpr std::uint64_t kPerThread = 20'000; + std::array local_errors{}; + std::vector workers; + workers.reserve(kThreads); + for (std::size_t i = 0; i < kThreads; ++i) { + workers.emplace_back([&metrics, &local_errors, i] { + for (std::uint64_t j = 0; j < kPerThread; ++j) { + if (metrics.Record(ProducerOwner::Authority, Stage::StrictDecision, + Outcome::Allow) != RecordResult::Counted) + ++local_errors[i]; + } + }); + } + for (auto& worker : workers) worker.join(); + + std::uint64_t errors = 0; + for (const auto count : local_errors) errors += count; + Check(errors == 0, "concurrent_records_all_counted"); + const auto snapshot = metrics.Snapshot(); + constexpr std::size_t allow_index = ((2 - 1) * kStageCount + (2 - 1)) * kOutcomeCount + 1; + Check(snapshot.counts[allow_index] == kThreads * kPerThread, + "concurrent_counter_is_exact"); + Check(snapshot.exact(), "no_overflow_on_normal_concurrency"); +} + +void TestDimensionsAndRejects() { + AggregateMetrics metrics; + Check(metrics.Record(ProducerOwner::WorkloadGenerator, Stage::Offered, + Outcome::None) == RecordResult::Counted, + "offered_none_counted"); + Check(metrics.Record(ProducerOwner::Backend, Stage::Completed, + Outcome::Allow) == RecordResult::Counted, + "completed_allow_counted"); + Check(metrics.Record(static_cast(0), Stage::Offered, + Outcome::None) == RecordResult::InvalidOwner, + "unknown_owner_rejected"); + Check(metrics.Record(ProducerOwner::Authority, static_cast(99), + Outcome::Allow) == RecordResult::InvalidStage, + "unknown_stage_rejected"); + Check(metrics.Record(ProducerOwner::Authority, Stage::StrictDecision, + static_cast(99)) == RecordResult::InvalidOutcome, + "unknown_outcome_rejected"); + Check(metrics.Record(ProducerOwner::Replica, Stage::StrictDecision, + Outcome::Allow) == RecordResult::InvalidOwnerStagePair, + "wrong_owner_stage_rejected"); + const auto snapshot = metrics.Snapshot(); + Check(snapshot.counts[((1 - 1) * kStageCount + (1 - 1)) * kOutcomeCount] == 1, + "offered_none_has_fixed_dimension"); + Check(snapshot.counts[((5 - 1) * kStageCount + (6 - 1)) * kOutcomeCount + 1] == 1, + "completed_allow_has_fixed_dimension"); + Check(snapshot.exact(), "invalid_records_do_not_overflow_or_increment"); +} + +void TestSaturationHelper() { + std::atomic counter{UINT64_MAX - 1}; + std::atomic overflow{false}; + Check(metrics::detail::SaturatingIncrement(counter, overflow), "increment_to_max_succeeds"); + Check(counter.load() == UINT64_MAX && !overflow.load(), + "max_value_is_reached_without_wrap"); + Check(!metrics::detail::SaturatingIncrement(counter, overflow), "increment_at_max_reports_overflow"); + Check(counter.load() == UINT64_MAX && overflow.load(), + "saturation_is_sticky_without_wrap"); + Check(!metrics::detail::SaturatingIncrement(counter, overflow), + "repeated_overflow_remains_explicit"); + Check(metrics::detail::NextCounterValue(UINT64_MAX).saturated, + "pure_saturation_boundary_helper"); +} + +} // namespace + +int main() { + TestConcurrentUpdates(); + TestDimensionsAndRejects(); + TestSaturationHelper(); + std::cout << "RG-005 aggregate metrics cases passed\n"; +} diff --git a/tests/bucket_math_driver.cpp b/tests/bucket_math_driver.cpp new file mode 100644 index 0000000..09f3bbf --- /dev/null +++ b/tests/bucket_math_driver.cpp @@ -0,0 +1,68 @@ +#include "authority/bucket_math.h" + +#include +#include +#include +#include +#include + +namespace authority = rateguard::authority; +using authority::BucketDecision; +using authority::BucketMath; +using authority::BucketPolicy; +using authority::BucketState; +using authority::MathResult; +using authority::ServiceError; + +namespace { +void PrintError(const ServiceError& error) { + std::cout << "ERR " << static_cast(error.category) << ' ' + << static_cast(error.code) << ' ' + << static_cast(error.retry) << ' ' + << static_cast(error.commitment) << '\n'; +} +void PrintState(const BucketState& state) { + std::cout << "OK " << state.balance_subunits << ' ' + << state.last_refill_ns << '\n'; +} +void PrintDecision(const BucketDecision& decision) { + std::cout << "OK "; + if (decision.outcome == authority::DecisionOutcome::Allow) std::cout << "ALLOW "; + else if (decision.outcome == authority::DecisionOutcome::Limited) std::cout << "LIMITED "; + else std::cout << "OTHER "; + std::cout << decision.next.balance_subunits << ' ' + << decision.next.last_refill_ns << ' '; + if (decision.retry_delay_ns) std::cout << *decision.retry_delay_ns; + else std::cout << '-'; + std::cout << '\n'; +} +template +void PrintResult(const MathResult& result, Printer printer) { + if (const auto* error = std::get_if(&result)) PrintError(*error); + else printer(std::get(result)); +} +} // namespace + +int main() { + char op = 0; + while (std::cin >> op) { + if (op == 'R') { + std::uint64_t capacity, rate, balance, last, now; + if (!(std::cin >> capacity >> rate >> balance >> last >> now)) return 2; + PrintResult(BucketMath::Refill({capacity, rate}, {balance, last}, now), PrintState); + } else if (op == 'D') { + std::uint64_t capacity, rate, balance, last, cost, now; + if (!(std::cin >> capacity >> rate >> balance >> last >> cost >> now)) return 2; + PrintResult(BucketMath::Decide({capacity, rate}, {balance, last}, cost, now), PrintDecision); + } else if (op == 'T') { + std::uint64_t deficit, rate; + if (!(std::cin >> deficit >> rate)) return 2; + PrintResult(BucketMath::RetryDelay(deficit, rate), + [](std::uint64_t ns) { std::cout << "OK " << ns << '\n'; }); + } else { + std::cerr << "unknown operation: " << op << '\n'; + return 2; + } + } + return 0; +} diff --git a/tests/bucket_math_test.cpp b/tests/bucket_math_test.cpp new file mode 100644 index 0000000..c02b963 --- /dev/null +++ b/tests/bucket_math_test.cpp @@ -0,0 +1,135 @@ +#include "authority/bucket_math.h" + +#include +#include +#include +#include +#include + +using rateguard::authority::BucketDecision; +using rateguard::authority::BucketMath; +using rateguard::authority::BucketPolicy; +using rateguard::authority::BucketState; +using rateguard::authority::MathResult; +using rateguard::v1::contract::Commitment; +using rateguard::v1::contract::DecisionOutcome; +using rateguard::v1::contract::ErrorCategory; +using rateguard::v1::contract::ErrorCode; + +namespace { +constexpr std::uint64_t S = 1'000'000'000ULL; +int failures = 0; +void Check(bool condition, const char* label) { + if (!condition) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} +template +const T* Value(const MathResult& result) { + return std::get_if(&result); +} +template +const rateguard::authority::ServiceError* Error(const MathResult& result) { + return std::get_if(&result); +} +} // namespace + +int main() { + // Exact threshold: available == cost*S admits, one subunit below limits. + const BucketPolicy unit{1, 1}; + auto at_boundary = BucketMath::Decide(unit, {S - 1, 0}, 1, 1); + Check(Value(at_boundary) != nullptr, "boundary returns decision"); + if (const auto* d = Value(at_boundary)) { + Check(d->outcome == DecisionOutcome::Allow, "exactly cost admits"); + Check(d->next.balance_subunits == 0 && d->next.last_refill_ns == 1, + "boundary debit and timestamp"); + Check(!d->retry_delay_ns.has_value(), "allow has no retry estimate"); + } + auto below_boundary = BucketMath::Decide(unit, {S - 2, 0}, 1, 1); + if (const auto* d = Value(below_boundary)) { + Check(d->outcome == DecisionOutcome::Limited, "one subunit short limits"); + Check(d->next.balance_subunits == S - 1 && d->next.last_refill_ns == 1, + "limited advances refill but does not debit"); + Check(d->retry_delay_ns == 1, "ceil retry estimate in ns"); + } else { + Check(false, "one subunit short returns decision"); + } + + // A 1 ns interval at rate 3 produces exactly 3 subunits (no float rounding). + auto fractional = BucketMath::Refill({4, 3}, {0, 100}, 101); + if (const auto* s = Value(fractional)) + Check(s->balance_subunits == 3 && s->last_refill_ns == 101, + "fractional 1 ns refill"); + else + Check(false, "fractional refill succeeds"); + + // Refill saturates at capacity, including with maximum legal rate/time. + auto saturated = BucketMath::Refill({3, 2}, {2 * S, 10}, 1'000'000'010ULL); + if (const auto* s = Value(saturated)) + Check(s->balance_subunits == 3 * S && s->last_refill_ns == 1'000'000'010ULL, + "capacity saturation"); + else + Check(false, "saturation succeeds"); + auto maximum = BucketMath::Refill( + {1'000'000'000ULL, 1'000'000'000ULL}, + {0, 0}, std::numeric_limits::max()); + if (const auto* s = Value(maximum)) + Check(s->balance_subunits == 1'000'000'000ULL * S && + s->last_refill_ns == std::numeric_limits::max(), + "maximum policy and elapsed time safely saturate"); + else + Check(false, "maximum legal values succeed"); + + // Weighted costs and full capacity debit. + auto weighted = BucketMath::Decide({5, 7}, {5 * S, 20}, 5, 20); + if (const auto* d = Value(weighted)) + Check(d->outcome == DecisionOutcome::Allow && d->next.balance_subunits == 0, + "weighted full-capacity debit"); + else + Check(false, "weighted debit succeeds"); + + // Invalid inputs are rejected before state mutation with NotCommitted status. + const auto bad_policy = BucketMath::Refill({0, 1}, {0, 0}, 0); + const auto bad_rate = BucketMath::Refill({1, 0}, {0, 0}, 0); + const auto bad_capacity = BucketMath::Decide({1'000'000'001ULL, 1}, {0, 0}, 1, 0); + const auto zero_cost = BucketMath::Decide(unit, {S, 0}, 0, 0); + const auto oversized_cost = BucketMath::Decide(unit, {S, 0}, 2, 0); + const auto zero_retry_rate = BucketMath::RetryDelay(1, 0); + for (const auto* e : {Error(bad_policy), Error(bad_rate), Error(bad_capacity), + Error(zero_cost), Error(oversized_cost), + Error(zero_retry_rate)}) { + Check(e != nullptr, "invalid input returns typed error"); + if (e) { + Check(e->category == ErrorCategory::Input && + e->code == ErrorCode::InvalidArgument && + e->commitment == Commitment::NotCommitted, + "invalid input error classification"); + } + } + + // Broken state and nonmonotonic time are internal integrity failures. + const auto bad_balance = BucketMath::Refill(unit, {S + 1, 0}, 1); + const auto backwards = BucketMath::Refill(unit, {0, 2}, 1); + for (const auto* e : {Error(bad_balance), Error(backwards)}) { + Check(e != nullptr, "state integrity failure returns typed error"); + if (e) + Check(e->category == ErrorCategory::Internal && + e->code == ErrorCode::Internal && + e->commitment == Commitment::NotCommitted, + "integrity error classification"); + } + + // Integer ceiling is exact at integral and nonintegral ratios. + auto exact_retry = BucketMath::RetryDelay(12, 3); + auto rounded_retry = BucketMath::RetryDelay(13, 3); + auto max_retry = BucketMath::RetryDelay(std::numeric_limits::max(), 1); + Check(Value(exact_retry) && *Value(exact_retry) == 4, "exact retry division"); + Check(Value(rounded_retry) && *Value(rounded_retry) == 5, "ceil retry division"); + Check(Value(max_retry) && *Value(max_retry) == std::numeric_limits::max(), + "maximum retry delay without overflow"); + + if (failures != 0) return EXIT_FAILURE; + std::cout << "bucket math contract checks passed\n"; + return EXIT_SUCCESS; +} diff --git a/tests/channel_policy_test.cpp b/tests/channel_policy_test.cpp new file mode 100644 index 0000000..ba4b3b2 --- /dev/null +++ b/tests/channel_policy_test.cpp @@ -0,0 +1,50 @@ +#include "rateguard/v1/channel_policy.h" + +#include + +#include +#include +#include + +namespace { +bool HasIntegerArg(const grpc_channel_args& args, const char* key, int expected) { + for (std::size_t i = 0; i < args.num_args; ++i) { + const grpc_arg& arg = args.args[i]; + if (arg.key != nullptr && std::string_view(arg.key) == key) { + return arg.type == GRPC_ARG_INTEGER && arg.value.integer == expected; + } + } + return false; +} +} + +int main() { + const auto args = rateguard::v1::transport::EnforcementChannelArguments(); + const grpc_channel_args raw = args.c_channel_args(); + if (!HasIntegerArg(raw, GRPC_ARG_ENABLE_RETRIES, 0)) { + std::cerr << "enforcement channel must disable retries\n"; + return EXIT_FAILURE; + } +#if defined(GRPC_ARG_EXPERIMENTAL_ENABLE_HEDGING) + if (!HasIntegerArg(raw, GRPC_ARG_EXPERIMENTAL_ENABLE_HEDGING, 0)) { + std::cerr << "enforcement channel must explicitly disable hedging\n"; + return EXIT_FAILURE; + } +#endif + + const std::shared_ptr no_credentials; + if (rateguard::v1::transport::CreateEnforcementChannel("dns:///127.0.0.1:1", no_credentials) || + rateguard::v1::transport::CreateEnforcementChannel("", grpc::InsecureChannelCredentials())) { + std::cerr << "enforcement channel factory must reject invalid arguments\n"; + return EXIT_FAILURE; + } + + const auto channel = rateguard::v1::transport::CreateEnforcementChannel( + "dns:///127.0.0.1:1", grpc::InsecureChannelCredentials()); + if (!channel) { + std::cerr << "enforcement channel factory returned null\n"; + return EXIT_FAILURE; + } + std::cout << "enforcement channel retry/hedging policy checks passed\n"; + return EXIT_SUCCESS; +} diff --git a/tests/clock_linux_smoke_test.cpp b/tests/clock_linux_smoke_test.cpp new file mode 100644 index 0000000..c96454f --- /dev/null +++ b/tests/clock_linux_smoke_test.cpp @@ -0,0 +1,224 @@ +#include "platform/clock_linux.h" +#include "platform/clock_linux_detail.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#endif + +using namespace rateguard::platform; +namespace detail = rateguard::platform::detail; + +namespace { +#if defined(__linux__) +struct DirectNamespace { + std::uint64_t device; + std::uint64_t inode; + friend bool operator==(const DirectNamespace&, const DirectNamespace&) = default; +}; + +bool StatPath(const char* path, DirectNamespace& out) { + struct stat st {}; + if (::stat(path, &st) != 0 || st.st_ino == 0) return false; + out = {static_cast(st.st_dev), + static_cast(st.st_ino)}; + return true; +} + +bool ReadText(const char* path, std::size_t limit, std::string& out) { + std::ifstream input(path, std::ios::binary); + if (!input) return false; + out.resize(limit + 1); + input.read(out.data(), static_cast(out.size())); + const auto n = input.gcount(); + if (n < 0 || static_cast(n) > limit || input.bad()) return false; + out.resize(static_cast(n)); + return true; +} + +bool DirectProbe(ClockIdentity& identity) { + std::string boot_text; + if (!ReadText("/proc/sys/kernel/random/boot_id", 64, boot_text)) return false; + auto boot = detail::ParseBootUuid(boot_text); + if (auto* failure = std::get_if(&boot)) { + (void)failure; + return false; + } + DirectNamespace current_before{}, children_before{}, current_after{}, children_after{}; + if (!StatPath("/proc/self/ns/time", current_before) || + !StatPath("/proc/self/ns/time_for_children", children_before)) return false; + std::string offsets; + if (!ReadText("/proc/self/timens_offsets", 512, offsets)) return false; + if (!StatPath("/proc/self/ns/time", current_after) || + !StatPath("/proc/self/ns/time_for_children", children_after)) return false; + if (current_before != children_before || current_before != current_after || + current_before != children_after) return false; + + std::istringstream lines(offsets); + std::string name1, name2, extra; + std::int64_t sec1 = 0, sec2 = 0; + std::uint64_t ns1 = 0, ns2 = 0; + if (!(lines >> name1 >> sec1 >> ns1 >> name2 >> sec2 >> ns2) || + (lines >> extra) || ns1 > 999'999'999ULL || ns2 > 999'999'999ULL) + return false; + std::int64_t mono_sec = 0, boot_sec = 0; + std::uint32_t mono_ns = 0, boot_ns = 0; + if (name1 == "monotonic" && name2 == "boottime") { + mono_sec = sec1; mono_ns = static_cast(ns1); + boot_sec = sec2; boot_ns = static_cast(ns2); + } else if (name1 == "boottime" && name2 == "monotonic") { + boot_sec = sec1; boot_ns = static_cast(ns1); + mono_sec = sec2; mono_ns = static_cast(ns2); + } else { + return false; + } + identity = {std::get>(boot), + current_before.device, current_before.inode, + mono_sec, mono_ns, boot_sec, boot_ns, + static_cast(CLOCK_MONOTONIC)}; + return true; +} + +std::string Format(const ClockIdentity& id, std::uint64_t sample) { + std::ostringstream out; + out << std::hex << std::setfill('0'); + for (auto b : id.boot_uuid) out << std::setw(2) << static_cast(b); + out << std::dec << '|' << id.namespace_device << '|' << id.namespace_inode + << '|' << id.monotonic_offset_seconds << '|' << id.monotonic_offset_nanoseconds + << '|' << id.boottime_offset_seconds << '|' << id.boottime_offset_nanoseconds + << '|' << id.clock_id << '|' << sample << '\n'; + return out.str(); +} + +int ChildMode() { + auto probe = detail::ProbeCurrentLinuxClockIdentity(); + auto* id = std::get_if(&probe); + if (!id) return 10; + auto clock_result = CreateLinuxClock(*id); // smoke-test-only self identity + auto* clock_ptr = std::get_if>(&clock_result); + if (!clock_ptr) return 11; + auto now = (*clock_ptr)->Now(); + auto* stamp = std::get_if(&now); + if (!stamp) return 12; + std::cout << Format(*id, stamp->value); + return 0; +} +#endif +} // namespace + +int main(int argc, char** argv) { +#if !defined(__linux__) + (void)argc; + (void)argv; + std::cout << "UNSUPPORTED: real Linux /proc and CLOCK_MONOTONIC provenance unavailable\n"; + return 77; +#else + if (argc == 2 && std::string(argv[1]) == "--child") return ChildMode(); + + ClockIdentity internal{}; + auto observed = detail::ProbeCurrentLinuxClockIdentity(); + if (const auto* failure = std::get_if(&observed)) { + std::cout << "UNSUPPORTED: Linux clock provenance probe failed reason=" + << static_cast(failure->reason) << '\n'; + return 77; + } + internal = std::get(observed); + ClockIdentity direct{}; + if (!DirectProbe(direct)) { + std::cerr << "FAIL: independent /proc identity read failed\n"; + return EXIT_FAILURE; + } + if (internal != direct) { + std::cerr << "FAIL: internal identity differs from direct kernel/proc reads\n"; + return EXIT_FAILURE; + } + auto clock_result = CreateLinuxClock(internal); + auto* clock_ptr = std::get_if>(&clock_result); + if (!clock_ptr) { + std::cerr << "FAIL: trusted identity did not create Linux clock\n"; + return EXIT_FAILURE; + } + auto parent_now = (*clock_ptr)->Now(); + auto* parent_stamp = std::get_if(&parent_now); + if (!parent_stamp) { + std::cerr << "FAIL: parent monotonic sample failed\n"; + return EXIT_FAILURE; + } + + int pipe_fds[2]; + if (::pipe(pipe_fds) != 0) { + std::cerr << "FAIL: pipe failed\n"; + return EXIT_FAILURE; + } + char resolved[PATH_MAX]; + if (!::realpath(argv[0], resolved)) { + std::cerr << "FAIL: cannot resolve smoke executable path\n"; + return EXIT_FAILURE; + } + const pid_t child = ::fork(); + if (child < 0) { + std::cerr << "FAIL: fork failed\n"; + return EXIT_FAILURE; + } + if (child == 0) { + ::close(pipe_fds[0]); + if (::dup2(pipe_fds[1], STDOUT_FILENO) < 0) _exit(20); + ::close(pipe_fds[1]); + ::execl(resolved, resolved, "--child", static_cast(nullptr)); + _exit(21); + } + ::close(pipe_fds[1]); + std::string child_line; + char chunk[512]; + for (;;) { + const ssize_t n = ::read(pipe_fds[0], chunk, sizeof(chunk)); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) break; + child_line.append(chunk, static_cast(n)); + if (child_line.size() > 1024) break; + } + ::close(pipe_fds[0]); + int status = 0; + if (::waitpid(child, &status, 0) != child || !WIFEXITED(status) || + WEXITSTATUS(status) != 0) { + std::cerr << "FAIL: fork/exec child identity probe failed\n"; + return EXIT_FAILURE; + } + const auto expected_child = Format(internal, 0); + const auto separator = child_line.rfind('|'); + if (separator == std::string::npos || + child_line.substr(0, separator + 1) != expected_child.substr(0, expected_child.rfind('|') + 1)) { + std::cerr << "FAIL: fork/exec child provenance differs from parent\n"; + return EXIT_FAILURE; + } + std::uint64_t child_sample = 0; + try { + child_sample = std::stoull(child_line.substr(separator + 1)); + } catch (...) { + std::cerr << "FAIL: child timestamp is malformed\n"; + return EXIT_FAILURE; + } + if (child_sample < parent_stamp->value) { + std::cerr << "FAIL: child timestamp precedes parent timestamp\n"; + return EXIT_FAILURE; + } + std::cout << "Linux clock provenance and fork/exec smoke checks passed\n"; + return EXIT_SUCCESS; +#endif +} diff --git a/tests/clock_test.cpp b/tests/clock_test.cpp new file mode 100644 index 0000000..b069973 --- /dev/null +++ b/tests/clock_test.cpp @@ -0,0 +1,323 @@ +#include "platform/clock_linux.h" +#include "platform/clock_linux_detail.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::platform; +namespace detail = rateguard::platform::detail; + +namespace { +int failures = 0; +void Check(bool condition, const char* label) { + if (!condition) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} +ClockFailure Fail(ClockFailureReason reason) { + using namespace rateguard::v1::contract; + return {{ErrorCategory::Internal, ErrorCode::Internal, RetryDisposition::Never, + Commitment::NotCommitted}, reason}; +} + +const std::string kBoot = "00112233-4455-6677-8899-aabbccddeeff\n"; +const std::string kOffsets = "monotonic 0 0\nboottime -2 4\n"; +const ClockIdentity kIdentity{{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, + 7, 1234, 0, 0, -2, 4, 1}; + +class FakePlatform final : public IClockPlatform { + public: + bool leader{true}; + std::int32_t clock_id{1}; + std::string boot{kBoot}; + std::string offsets{kOffsets}; + std::deque namespace_sequence{ + {7, 1234}, {7, 1234}, {7, 1234}, {7, 1234}}; + std::deque> readings; + std::atomic clock_calls{0}; + + ClockResult IsProcessLeader() override { return leader; } + ClockResult ReadBootUuidFile() override { return boot; } + ClockResult StatTimeNamespace(bool) override { + if (namespace_sequence.empty()) return Fail(ClockFailureReason::NamespaceStat); + auto value = namespace_sequence.front(); + namespace_sequence.pop_front(); + return value; + } + ClockResult ReadTimeOffsetsFile() override { return offsets; } + ClockResult MonotonicClockId() override { return clock_id; } + ClockResult ReadMonotonic() override { + ++clock_calls; + if (readings.empty()) return ClockReading{0, 0}; + auto result = std::move(readings.front()); + readings.pop_front(); + return result; + } +}; + +ClockResult> MakeClock( + std::unique_ptr platform, const ClockIdentity& expected = kIdentity) { + std::unique_ptr erased(std::move(platform)); + return LinuxMonotonicClock::Create(expected, std::move(erased)); +} + +bool HasFailure(const auto& result, ClockFailureReason reason) { + const auto* failure = std::get_if(&result); + return failure && failure->reason == reason && + failure->service_error.category == rateguard::v1::contract::ErrorCategory::Internal && + failure->service_error.code == rateguard::v1::contract::ErrorCode::Internal && + failure->service_error.commitment == rateguard::v1::contract::Commitment::NotCommitted; +} + +void TestParsers() { + const auto uuid = detail::ParseBootUuid(kBoot); + Check(std::holds_alternative>(uuid), "valid lowercase UUID parses"); + if (const auto* bytes = std::get_if>(&uuid)) + Check(*bytes == kIdentity.boot_uuid, "UUID bytes match expected order"); + Check(HasFailure(detail::ParseBootUuid("00112233-4455-6677-8899-AABBCCDDEEFF\n"), + ClockFailureReason::MalformedBootUuid), "uppercase UUID rejected"); + Check(HasFailure(detail::ParseBootUuid(" 00112233-4455-6677-8899-aabbccddeeff"), + ClockFailureReason::MalformedBootUuid), "UUID leading space rejected"); + Check(HasFailure(detail::ParseBootUuid(kBoot + "\n"), + ClockFailureReason::MalformedBootUuid), "multiple UUID newlines rejected"); + Check(HasFailure(detail::ParseBootUuid(std::string(65, 'a')), + ClockFailureReason::InputTooLong), "UUID overlength rejected"); + + const auto offsets = detail::ParseTimeOffsets(kOffsets); + Check(std::holds_alternative(offsets), "valid offsets parse"); + if (const auto* parsed = std::get_if(&offsets)) + Check(parsed->monotonic_seconds == 0 && parsed->monotonic_nanoseconds == 0 && + parsed->boottime_seconds == -2 && parsed->boottime_nanoseconds == 4, + "both offset rows map to expected fields"); + Check(std::holds_alternative(detail::ParseTimeOffsets( + " boottime\t-2\t4 \nmonotonic 0 0")), + "row order and spaces/tabs accepted"); + std::string embedded_nul = "monotonic 0 0\nboottime 0 0"; + embedded_nul.push_back('\0'); + const std::array invalid_offsets{ + "monotonic +1 0\nboottime 0 0", // plus sign + "monotonic 01 0\nboottime 0 0", // leading zero + "monotonic -0 0\nboottime 0 0", // negative zero + "monotonic 0 00\nboottime 0 0", // nanosecond leading zero + "monotonic 0 1000000000\nboottime 0 0", // nsec bound + "monotonic 0 0\r\nboottime 0 0", // CR rejected + "monotonic 0 0\n\nboottime 0 0", // empty row + "monotonic 0 0\nmonotonic 1 0", // duplicate row + "monotonic 0 0", // missing row + "monotonic 0 0\nboottime 0 0\nother 0 0", // unknown row + "monotonic 0 0 extra\nboottime 0 0", // extra token + std::move(embedded_nul)}; + for (const auto& text : invalid_offsets) + Check(std::holds_alternative(detail::ParseTimeOffsets(text)), + "malformed offsets rejected"); + Check(HasFailure(detail::ParseTimeOffsets(std::string(513, 'x')), + ClockFailureReason::InputTooLong), "offset overlength rejected"); + auto edge_offsets = detail::ParseTimeOffsets( + "monotonic -9223372036854775808 999999999\nboottime 9223372036854775807 0\n"); + Check(std::holds_alternative(edge_offsets), + "signed second extremes and maximum nanoseconds parse"); + if (const auto* edge = std::get_if(&edge_offsets)) + Check(edge->monotonic_seconds == std::numeric_limits::min() && + edge->monotonic_nanoseconds == 999'999'999U && + edge->boottime_seconds == std::numeric_limits::max(), + "offset extremes preserved exactly"); + + char path[] = "/tmp/rateguard-clock-bounded-XXXXXX"; + const int fd = ::mkstemp(path); + Check(fd >= 0, "create bounded-reader temp file"); + if (fd >= 0) { + const std::string contents(65, 'x'); + const auto written = ::write(fd, contents.data(), contents.size()); + Check(written == static_cast(contents.size()), + "write bounded-reader temp file"); + (void)::lseek(fd, 0, SEEK_SET); + Check(HasFailure(detail::ReadBoundedFd(fd, 64), + ClockFailureReason::InputTooLong), + "bounded reader detects one byte over limit"); + Check(::ftruncate(fd, 64) == 0 && ::lseek(fd, 0, SEEK_SET) == 0, + "truncate and rewind bounded-reader file"); + const auto exact = detail::ReadBoundedFd(fd, 64); + Check(std::get_if(&exact) && std::get(exact).size() == 64, + "bounded reader accepts exact limit"); + Check(::ftruncate(fd, 0) == 0 && ::lseek(fd, 0, SEEK_SET) == 0, + "empty bounded-reader file"); + const auto empty = detail::ReadBoundedFd(fd, 0); + Check(std::get_if(&empty) && std::get(empty).empty(), + "bounded reader accepts zero-byte file at zero limit"); + ::close(fd); + ::unlink(path); + } +} + +void TestIdentityProbeAndMismatch() { + auto valid = MakeClock(std::make_unique()); + Check(std::holds_alternative>(valid), + "manifest-matching identity creates clock"); + if (auto* clock = std::get_if>(&valid)) { + auto provenance = (*clock)->Provenance(); + Check(std::get_if(&provenance) && + std::get(provenance) == kIdentity, + "provenance equals captured identity"); + } + + for (int field = 0; field < 8; ++field) { + auto expected = kIdentity; + switch (field) { + case 0: expected.boot_uuid[0] ^= 1; break; + case 1: ++expected.namespace_device; break; + case 2: ++expected.namespace_inode; break; + case 3: ++expected.monotonic_offset_seconds; break; + case 4: ++expected.monotonic_offset_nanoseconds; break; + case 5: ++expected.boottime_offset_seconds; break; + case 6: ++expected.boottime_offset_nanoseconds; break; + case 7: expected.clock_id = 2; break; + } + auto result = MakeClock(std::make_unique(), expected); + Check(HasFailure(result, ClockFailureReason::ExpectedIdentityMismatch), + "each trusted identity field compared exactly"); + } + + auto invalid_clock_id_platform = std::make_unique(); + invalid_clock_id_platform->clock_id = 99; + auto bad_clock = kIdentity; + bad_clock.clock_id = 99; + auto invalid_clock = MakeClock(std::move(invalid_clock_id_platform), bad_clock); + Check(HasFailure(invalid_clock, ClockFailureReason::ExpectedIdentityMismatch), + "non-CLOCK_MONOTONIC ID rejected even if expected matches"); + + auto split = std::make_unique(); + split->namespace_sequence = {{7, 1234}, {7, 1235}, {7, 1234}, {7, 1235}}; + Check(HasFailure(MakeClock(std::move(split)), ClockFailureReason::NamespaceChanged), + "current and child namespaces must match"); + + auto changed = std::make_unique(); + changed->namespace_sequence = {{7, 1234}, {7, 1234}, {7, 1235}, {7, 1234}}; + Check(HasFailure(MakeClock(std::move(changed)), ClockFailureReason::NamespaceChanged), + "all four namespace snapshots must match"); + + auto nonleader = std::make_unique(); + nonleader->leader = false; + Check(HasFailure(MakeClock(std::move(nonleader)), ClockFailureReason::NotProcessLeader), + "nonleader probe rejected"); + + auto malformed = std::make_unique(); + malformed->offsets = "monotonic 0 0\nboottime 0 0\nunknown 0 0"; + Check(HasFailure(MakeClock(std::move(malformed)), ClockFailureReason::MalformedOffsets), + "malformed platform offsets prevent factory success"); +} + +void TestSamplingAndStickyFailure() { + auto fake = std::make_unique(); + fake->readings = {ClockReading{0, 0}, ClockReading{1, 2}, ClockReading{1, 2}}; + auto created = MakeClock(std::move(fake)); + auto& clock = *std::get>(created); + auto first = clock.Now(); + auto equal = clock.Now(); + Check(std::get_if(&first) && std::get(first).value == 1'000'000'002ULL, + "seconds and nanos convert exactly"); + Check(std::get_if(&equal) && std::get(equal).value == 1'000'000'002ULL, + "equal sample is accepted"); + Check(clock.Healthy(), "clock stays healthy after equal samples"); + + auto backwards_fake = std::make_unique(); + backwards_fake->readings = {ClockReading{4, 0}, ClockReading{5, 0}, + ClockReading{4, 999'999'999}, ClockReading{6, 0}}; + auto backwards_created = MakeClock(std::move(backwards_fake)); + auto& backwards_clock = *std::get>(backwards_created); + Check(std::holds_alternative(backwards_clock.Now()), "first sample succeeds"); + auto backwards = backwards_clock.Now(); + Check(HasFailure(backwards, ClockFailureReason::BackwardsSample), "backwards sample latches"); + Check(!backwards_clock.Healthy(), "backwards failure makes clock unhealthy"); + auto sticky = backwards_clock.Now(); + Check(HasFailure(sticky, ClockFailureReason::BackwardsSample), "first failure remains sticky"); + auto provenance_after_failure = backwards_clock.Provenance(); + Check(HasFailure(provenance_after_failure, ClockFailureReason::BackwardsSample), + "provenance fails with first sticky error"); + + const std::array invalid_readings{{{-1, 0}, {0, -1}, {0, 1'000'000'000}}}; + const std::array reasons{{ClockFailureReason::InvalidTimespec, + ClockFailureReason::InvalidTimespec, + ClockFailureReason::InvalidTimespec}}; + for (std::size_t i = 0; i < invalid_readings.size(); ++i) { + auto bad = std::make_unique(); + bad->readings.push_back(ClockReading{0, 0}); + bad->readings.push_back(invalid_readings[i]); + auto result = MakeClock(std::move(bad)); + auto& test_clock = *std::get>(result); + Check(HasFailure(test_clock.Now(), reasons[i]), "invalid timespec rejected"); + Check(!test_clock.Healthy(), "invalid timespec is sticky"); + } + auto overflow_fake = std::make_unique(); + overflow_fake->readings = {ClockReading{0, 0}, + ClockReading{std::numeric_limits::max(), 0}}; + auto overflow_created = MakeClock(std::move(overflow_fake)); + auto& overflow_clock = *std::get>(overflow_created); + Check(HasFailure(overflow_clock.Now(), ClockFailureReason::NanosecondOverflow), + "uint64 nanosecond conversion overflow rejected"); + + auto initial_bad_fake = std::make_unique(); + initial_bad_fake->readings = {ClockReading{0, 1'000'000'000}}; + Check(HasFailure(MakeClock(std::move(initial_bad_fake)), + ClockFailureReason::InvalidTimespec), + "failed initial sample prevents factory from returning a usable clock"); + + auto syscall_fake = std::make_unique(); + syscall_fake->readings = {Fail(ClockFailureReason::ClockSyscall)}; + Check(HasFailure(MakeClock(std::move(syscall_fake)), ClockFailureReason::ClockSyscall), + "initial clock syscall failure prevents factory success"); +} + +void TestConcurrentSerializedSamples() { + constexpr std::size_t n = 32; + auto fake = std::make_unique(); + fake->readings.emplace_back(ClockReading{0, 0}); // successful factory sample + for (std::size_t i = 0; i < n; ++i) + fake->readings.emplace_back(ClockReading{static_cast(i + 1), 0}); + auto created = MakeClock(std::move(fake)); + auto& clock = *std::get>(created); + std::array samples{}; + std::array ok{}; + std::array threads; + for (std::size_t i = 0; i < n; ++i) { + threads[i] = std::thread([&, i] { + auto result = clock.Now(); + if (const auto* value = std::get_if(&result)) { + samples[i] = value->value; + ok[i] = true; + } + }); + } + for (auto& thread : threads) thread.join(); + for (bool success : ok) Check(success, "concurrent sample succeeds"); + std::sort(samples.begin(), samples.end()); + for (std::size_t i = 0; i < n; ++i) + Check(samples[i] == (i + 1) * 1'000'000'000ULL, + "serialized concurrent samples preserve monotonic order"); + Check(clock.Healthy(), "concurrent serialized samples remain healthy"); +} +} // namespace + +int main() { + TestParsers(); + TestIdentityProbeAndMismatch(); + TestSamplingAndStickyFailure(); + TestConcurrentSerializedSamples(); + if (failures != 0) return EXIT_FAILURE; + std::cout << "clock contract checks passed\n"; + return EXIT_SUCCESS; +} diff --git a/tests/contract_test.cpp b/tests/contract_test.cpp new file mode 100644 index 0000000..fe4409f --- /dev/null +++ b/tests/contract_test.cpp @@ -0,0 +1,308 @@ +#include "proto/rateguard/v1/admission.pb.h" +#include "proto/rateguard/v1/authority.pb.h" +#include "rateguard/v1/error_contract.h" +#include "rateguard/v1/request_validation.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rg = rateguard::v1; +namespace contract = rateguard::v1::contract; +namespace validation = rateguard::v1::validation; +using rg::AcquireCreditRequest; +using rg::AcquireCreditResponse; +using rg::AdmissionDecision; +using rg::CheckAdmissionRequest; + +namespace { +int failures = 0; +void Check(bool ok, std::string_view label) { + if (!ok) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} +std::string ReadText(const std::filesystem::path& path) { + std::ifstream in(path); + if (!in) return {}; + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} +std::string ReadHex(const std::filesystem::path& path) { + std::string compact, text = ReadText(path); + for (char c : text) { + if (c == '#' ) break; + if (c != ' ' && c != '\n' && c != '\r' && c != '\t') compact.push_back(c); + } + std::string bytes; + if (compact.size() % 2 != 0) return {}; + for (std::size_t i = 0; i < compact.size(); i += 2) { + const auto digit = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + }; + int hi = digit(compact[i]), lo = digit(compact[i + 1]); + if (hi < 0 || lo < 0) return {}; + bytes.push_back(static_cast((hi << 4) | lo)); + } + return bytes; +} +std::string Seq(unsigned char start, std::size_t size) { + std::string value; + for (std::size_t i = 0; i < size; ++i) + value.push_back(static_cast(start + i)); + return value; +} +template +void RoundTrip(const std::filesystem::path& root, std::string_view fixture, + Message& message, std::string_view label) { + const std::string bytes = ReadHex(root / "tests/fixtures" / fixture); + Check(!bytes.empty(), std::string(label) + " fixture readable"); + Check(message.ParseFromString(bytes), std::string(label) + " generated parser accepts fixture"); + std::string encoded; + Check(message.SerializeToString(&encoded), std::string(label) + " generated serializer succeeds"); + Check(encoded == bytes, std::string(label) + " generated parse/serialize is byte-stable"); +} +struct FakeStatePort { + int calls = 0; + void Apply() { ++calls; } +}; +template +bool ValidateBeforeState(const Request& request, Validator validate, FakeStatePort& port) { + if (validate(request).has_value()) return false; + port.Apply(); + return true; +} +const google::protobuf::FieldDescriptor* Field( + const google::protobuf::Descriptor* message, std::string_view name, int number) { + const auto* field = message->FindFieldByName(std::string(name)); + Check(field != nullptr, std::string(message->name()) + "." + std::string(name) + " exists"); + if (field) Check(field->number() == number, + std::string(message->name()) + "." + std::string(name) + " number"); + return field; +} +} // namespace + +int main(int argc, char** argv) { + const std::filesystem::path root = argc > 1 ? argv[1] : "."; + + const auto* check = CheckAdmissionRequest::descriptor(); + Field(check, "tenant_id", 1); Field(check, "operation_id", 2); + Field(check, "attempt_id", 3); Field(check, "epoch_id", 4); + Field(check, "policy_digest", 5); + Check(check->field_count() == 5, "CheckAdmissionRequest has no client cost/mode/time fields"); + + const auto* decision = AdmissionDecision::descriptor(); + Field(decision, "outcome", 1); Field(decision, "epoch_id", 2); + Field(decision, "policy_digest", 3); Field(decision, "mode", 4); + Field(decision, "attempt_id", 5); Field(decision, "retry_delay_ns", 6); + const auto* acquire = AcquireCreditRequest::descriptor(); + Field(acquire, "tenant_id", 1); Field(acquire, "slot", 2); + Field(acquire, "incarnation_id", 3); Field(acquire, "epoch_id", 4); + Field(acquire, "policy_digest", 5); Field(acquire, "sequence", 6); + Field(acquire, "trigger_cost_units", 7); Field(acquire, "trigger_operation_id", 8); + const auto* grant_response = AcquireCreditResponse::descriptor(); + Field(grant_response, "grant_outcome", 1); Field(grant_response, "sequence", 2); + Field(grant_response, "composite_grant_id", 3); Field(grant_response, "grant_units", 4); + Field(grant_response, "epoch_id", 5); Field(grant_response, "policy_digest", 6); + + Check(static_cast(rg::DECISION_OUTCOME_UNSPECIFIED) == 0 && + static_cast(rg::DECISION_OUTCOME_ALLOW) == 1 && + static_cast(rg::DECISION_OUTCOME_OVERLOADED) == 6, "decision enum numeric contract"); + Check(static_cast(rg::GRANT_OUTCOME_UNSPECIFIED) == 0 && + static_cast(rg::GRANT_OUTCOME_GRANTED) == 1 && + static_cast(rg::GRANT_OUTCOME_OVERLOADED) == 5, "grant enum numeric contract"); + Check(static_cast(rg::ADMISSION_MODE_UNSPECIFIED) == 0 && + static_cast(rg::ADMISSION_MODE_CREDIT) == 2, "mode enum numeric contract"); + Check(!validation::IsKnownDecisionOutcome(0) && !validation::IsKnownDecisionOutcome(7), "reject unspecified/unknown decision"); + Check(!validation::IsKnownGrantOutcome(0) && !validation::IsKnownGrantOutcome(6), "reject unspecified/unknown grant"); + Check(!validation::IsKnownAdmissionMode(0) && !validation::IsKnownAdmissionMode(3), "reject unspecified/unknown mode"); + + Check(contract::StatusFor(contract::ErrorCode::InvalidArgument) == contract::GrpcStatus::InvalidArgument, + "INVALID_ARGUMENT status mapping"); + Check(contract::StatusFor(contract::ErrorCode::Unauthenticated) == contract::GrpcStatus::Unauthenticated, + "UNAUTHENTICATED status mapping"); + Check(contract::StatusFor(contract::ErrorCode::PermissionDenied) == contract::GrpcStatus::PermissionDenied, + "PERMISSION_DENIED status mapping"); + Check(contract::StatusFor(contract::ErrorCode::PayloadTooLarge) == contract::GrpcStatus::ResourceExhausted, + "oversize pre-decode transport status mapping"); + Check(contract::StructuredDecisionStatus(5) == contract::GrpcStatus::Ok && + contract::StructuredDecisionStatus(6) == contract::GrpcStatus::Ok && + contract::StructuredGrantStatus(4) == contract::GrpcStatus::Ok && + contract::StructuredGrantStatus(5) == contract::GrpcStatus::Ok, + "structured UNAVAILABLE/OVERLOADED use transport OK"); + Check(contract::StructuredDecisionStatus(3) == contract::GrpcStatus::Internal && + contract::StructuredDecisionStatus(0) == contract::GrpcStatus::Internal, + "invalid/unspecified decision is not a successful structured response"); + Check(contract::CommitmentForTransportFailure(contract::DispatchPhase::BeforeDispatch) == contract::Commitment::NotCommitted, + "predispatch transport failure is not committed"); + Check(contract::CommitmentForTransportFailure(contract::DispatchPhase::Dispatched) == contract::Commitment::Possible, + "post-dispatch transport failure has possible commitment"); + Check(contract::RetryDispositionFor(contract::RpcOperation::StrictAdmission, contract::DispatchPhase::Dispatched) == + contract::RetryDisposition::NewAttempt && + contract::RetryDispositionFor(contract::RpcOperation::AcquireCredit, contract::DispatchPhase::Dispatched) == + contract::RetryDisposition::SameGrantSequence, + "strict retries are fresh application attempts; uncertain grants reuse same sequence"); + Check(contract::IsAllowOutcome(contract::DecisionOutcome::Allow) && + !contract::IsAllowOutcome(contract::DecisionOutcome::Limited) && + !contract::IsAllowOutcome(contract::DecisionOutcome::Unavailable), + "only ALLOW outcome can authorize forwarding"); + Check(contract::IsValidIdentifier("tenant-1.alpha_2") && !contract::IsValidIdentifier("") && + !contract::IsValidIdentifier("bad tenant") && !contract::IsValidIdentifier("x/y"), + "identifier grammar and 1..128 byte bound"); + + CheckAdmissionRequest req; + RoundTrip(root, "check_admission_request.hex", req, "CheckAdmissionRequest"); + Check(req.tenant_id() == "acct-1" && req.operation_id() == "publish" && + req.attempt_id() == Seq(0x00, 16) && req.epoch_id() == Seq(0x10, 16) && + req.policy_digest() == Seq(0x20, 32), "check request fixture values"); + FakeStatePort admission_port; + Check(ValidateBeforeState(req, [](const auto& x) { return validation::ValidateCheckAdmissionRequest(x, "acct-1", "publish", Seq(0x10,16), Seq(0x20,32)); }, admission_port), + "valid admission request accepted"); + auto bad_req = req; bad_req.set_attempt_id(Seq(0, 15)); + Check(!ValidateBeforeState(bad_req, [](const auto& x) { return validation::ValidateCheckAdmissionRequest(x, "acct-1", "publish", Seq(0x10,16), Seq(0x20,32)); }, admission_port) && + admission_port.calls == 1, "invalid fixed-width ID rejected before state port"); + bad_req = req; bad_req.set_tenant_id(std::string(129, 'x')); + Check(!ValidateBeforeState(bad_req, [](const auto& x) { return validation::ValidateCheckAdmissionRequest(x, "acct-1", "publish", Seq(0x10,16), Seq(0x20,32)); }, admission_port) && + admission_port.calls == 1, "oversized identifier rejected before state port"); + bad_req = req; + bad_req.set_epoch_id(Seq(0x30, 16)); + Check(!ValidateBeforeState(bad_req, [](const auto& x) { return validation::ValidateCheckAdmissionRequest(x, "acct-1", "publish", Seq(0x10,16), Seq(0x20,32)); }, admission_port) && + admission_port.calls == 1, "stale epoch rejected before state port"); + // Unknown protobuf fields are parsed by proto3, but the decoded payload cap + // still applies before any state-port mutation. + std::string oversized_unknown = req.SerializeAsString(); + oversized_unknown.append("\xA2\x06\xE8\x84\x01", 5); // field 100, length-delimited 17000 + oversized_unknown.append(17000, 'z'); + Check(bad_req.ParseFromString(oversized_unknown), "oversized unknown field parses as protobuf"); + Check(!ValidateBeforeState(bad_req, [](const auto& x) { return validation::ValidateCheckAdmissionRequest(x, "acct-1", "publish", Seq(0x10,16), Seq(0x20,32)); }, admission_port) && + admission_port.calls == 1, "oversized decoded payload rejected before state port"); + + AdmissionDecision unknown_decision; + const std::string unknown_enum("\x08\x4d", 2); // outcome value 77 + Check(unknown_decision.ParseFromString(unknown_enum), "proto3 parser retains unknown enum value"); + Check(!validation::IsKnownDecisionOutcome(static_cast(unknown_decision.outcome())), + "unknown enum rejected by contract validator"); + AdmissionDecision unspecified_decision; + Check(unspecified_decision.ParseFromString(std::string("\x08\x00", 2)), + "UNSPECIFIED enum wire value parses"); + Check(!validation::IsKnownDecisionOutcome(static_cast(unspecified_decision.outcome())), + "UNSPECIFIED decision rejected by contract validator"); + + AdmissionDecision allow; + RoundTrip(root, "admission_allow_retry_123.hex", allow, "AdmissionDecision/retry"); + Check(allow.outcome() == rg::DECISION_OUTCOME_ALLOW && allow.mode() == rg::ADMISSION_MODE_STRICT && + allow.has_retry_delay_ns() && allow.retry_delay_ns() == 123, + "decision fields and present retry value"); + AdmissionDecision absent; + RoundTrip(root, "admission_allow_retry_absent.hex", absent, "AdmissionDecision/no-retry"); + Check(!absent.has_retry_delay_ns(), "absent optional retry preserved"); + AdmissionDecision zero; + RoundTrip(root, "admission_allow_retry_zero_present.hex", zero, "AdmissionDecision/zero-retry"); + Check(zero.has_retry_delay_ns() && zero.retry_delay_ns() == 0, + "present zero retry distinct from absent"); + + AcquireCreditRequest credit; + RoundTrip(root, "acquire_credit_request.hex", credit, "AcquireCreditRequest"); + Check(credit.slot() == 3 && credit.sequence() == 7 && + credit.trigger_cost_units() == 5 && credit.trigger_operation_id() == "publish", + "credit request fixture values"); + FakeStatePort grant_port; + const std::string registered_incarnation = Seq(0x40, 16); + const std::array registered_slots{{{3, registered_incarnation}}}; + auto valid_credit = [&](const auto& x) { + return validation::ValidateAcquireCreditRequest(x, registered_slots, "acct-1", "publish", Seq(0x10,16), Seq(0x20,32), 5, 100); + }; + Check(ValidateBeforeState(credit, valid_credit, grant_port), "valid credit request accepted"); + auto bad_credit = credit; bad_credit.set_slot(8); + Check(!ValidateBeforeState(bad_credit, valid_credit, grant_port) && grant_port.calls == 1, + "unregistered slot rejected before state port"); + bad_credit = credit; bad_credit.set_slot(7); + Check(!ValidateBeforeState(bad_credit, valid_credit, grant_port) && grant_port.calls == 1, + "slot cap does not imply slot registration"); + bad_credit = credit; bad_credit.set_incarnation_id(Seq(0x50,16)); + Check(!ValidateBeforeState(bad_credit, valid_credit, grant_port) && grant_port.calls == 1, + "stale incarnation rejected before state port"); + bad_credit = credit; bad_credit.set_sequence(0); + Check(!ValidateBeforeState(bad_credit, valid_credit, grant_port) && grant_port.calls == 1, + "zero grant sequence rejected before state port"); + bad_credit = credit; bad_credit.set_trigger_cost_units(6); + Check(!ValidateBeforeState(bad_credit, valid_credit, grant_port) && grant_port.calls == 1, + "trigger cost/policy mismatch rejected before state port"); + bad_credit = credit; bad_credit.set_trigger_operation_id("other"); + Check(!ValidateBeforeState(bad_credit, valid_credit, grant_port) && grant_port.calls == 1, + "operation mismatch rejected before state port"); + bad_credit = credit; bad_credit.set_policy_digest(Seq(0x20, 31)); + Check(!ValidateBeforeState(bad_credit, valid_credit, grant_port) && grant_port.calls == 1, + "bad digest width rejected before state port"); + + AcquireCreditResponse limited; + RoundTrip(root, "grant_result_limited_zero_units_present.hex", limited, + "AcquireCreditResponse/limited-zero"); + Check(limited.grant_outcome() == rg::GRANT_OUTCOME_LIMITED && + limited.has_grant_units() && limited.grant_units() == 0 && + limited.sequence() == 7, "known LIMITED preserves zero grant-units presence"); + + AcquireCreditResponse granted; + RoundTrip(root, "grant_result_granted_composite.hex", granted, + "AcquireCreditResponse/granted-composite"); + Check(granted.grant_outcome() == rg::GRANT_OUTCOME_GRANTED && + granted.sequence() == 7 && granted.has_composite_grant_id() && + granted.has_grant_units() && granted.grant_units() == 25, + "GRANTED response preserves grant amount and composite identity"); + const auto& grant_id = granted.composite_grant_id(); + Check(grant_id.epoch_id() == Seq(0x10,16) && grant_id.tenant_id() == "acct-1" && + grant_id.slot() == 3 && grant_id.incarnation_id() == Seq(0x40,16) && + grant_id.sequence() == 7 && granted.epoch_id() == grant_id.epoch_id(), + "nested grant ID tuple round-trips exactly"); + + + AcquireCreditResponse unknown_grant; + Check(unknown_grant.ParseFromString(std::string("\x08\x4d", 2)), + "generated parser preserves unknown grant outcome"); + Check(!validation::IsKnownGrantOutcome(static_cast(unknown_grant.grant_outcome())), + "unknown grant outcome rejected"); + AcquireCreditResponse unspecified_grant; + Check(unspecified_grant.ParseFromString(""), "default grant parses"); + Check(!validation::IsKnownGrantOutcome(static_cast(unspecified_grant.grant_outcome())), + "unspecified grant rejected"); + AdmissionDecision unknown_mode; + Check(unknown_mode.ParseFromString(std::string("\x20\x4d", 2)), + "generated parser preserves unknown admission mode"); + Check(!validation::IsKnownAdmissionMode(static_cast(unknown_mode.mode())), + "unknown admission mode rejected"); + AdmissionDecision unspecified_mode; + Check(unspecified_mode.ParseFromString(""), "default decision parses"); + Check(!validation::IsKnownAdmissionMode(static_cast(unspecified_mode.mode())), + "unspecified admission mode rejected"); + + const std::array malformed_requests{ + std::string("\x0a\x05x", 3), // truncated length-delimited tenant + std::string("\x00", 1), // illegal field number zero + std::string("\x08", 1) + std::string(10, static_cast(0x80))}; + FakeStatePort malformed_port; + for (const auto& wire : malformed_requests) { + CheckAdmissionRequest malformed; + const bool parsed = malformed.ParseFromString(wire); + Check(!parsed, "generated parser rejects malformed wire"); + if (parsed) { + (void)ValidateBeforeState(malformed, [](const auto& x) { + return validation::ValidateCheckAdmissionRequest( + x, "acct-1", "publish", Seq(0x10,16), Seq(0x20,32)); + }, malformed_port); + } + } + Check(malformed_port.calls == 0, "malformed wire never reaches test state port"); + + if (failures) return 1; + std::cout << "generated protobuf/error contract checks passed\n"; + return 0; +} diff --git a/tests/contracts/transport_error_test.cpp b/tests/contracts/transport_error_test.cpp new file mode 100644 index 0000000..9964049 --- /dev/null +++ b/tests/contracts/transport_error_test.cpp @@ -0,0 +1,32 @@ +#include "rateguard/v1/error_contract.h" + +#include +#include +using namespace rateguard::v1::contract; + +int main() { + if (CommitmentForTransportFailure(DispatchPhase::BeforeDispatch) != Commitment::NotCommitted) + return EXIT_FAILURE; + if (CommitmentForTransportFailure(DispatchPhase::Dispatched) != Commitment::Possible) + return EXIT_FAILURE; + if (RetryDispositionFor(RpcOperation::StrictAdmission, DispatchPhase::Dispatched) != + RetryDisposition::NewAttempt || + RetryDispositionFor(RpcOperation::AcquireCredit, DispatchPhase::Dispatched) != + RetryDisposition::SameGrantSequence) + return EXIT_FAILURE; + if (StructuredDecisionStatus(5) != GrpcStatus::Ok || + StructuredDecisionStatus(6) != GrpcStatus::Ok || + StructuredGrantStatus(4) != GrpcStatus::Ok || + StructuredGrantStatus(5) != GrpcStatus::Ok) + return EXIT_FAILURE; + if (StatusFor(ErrorCode::InvalidArgument) != GrpcStatus::InvalidArgument || + StatusFor(ErrorCode::Unauthenticated) != GrpcStatus::Unauthenticated || + StatusFor(ErrorCode::PermissionDenied) != GrpcStatus::PermissionDenied || + StatusFor(ErrorCode::PayloadTooLarge) != GrpcStatus::ResourceExhausted) + return EXIT_FAILURE; + if (IsAllowOutcome(DecisionOutcome::Limited) || + IsAllowOutcome(DecisionOutcome::Unavailable)) + return EXIT_FAILURE; + std::cout << "transport error contract checks passed\n"; + return EXIT_SUCCESS; +} diff --git a/tests/event_recorder_test.cpp b/tests/event_recorder_test.cpp new file mode 100644 index 0000000..c6cc927 --- /dev/null +++ b/tests/event_recorder_test.cpp @@ -0,0 +1,323 @@ +#include "src/events/event_recorder.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::events; + +namespace { +int failures = 0; +#define CHECK(expr) do { if (!(expr)) { std::cerr << "FAIL line " << __LINE__ << ": " #expr "\n"; ++failures; } } while (false) + +RunPlan Plan(std::vector producers, std::uint64_t budget = 1ULL << 30) { + RunPlan p; + p.epoch_id[0] = 0x12; + p.policy_digest[0] = 0x34; + p.producers = std::move(producers); + p.budget_bytes = budget; + return p; +} + +EventV1 Event(Stage stage, std::uint64_t seq, Outcome outcome = Outcome::Allow) { + EventV1 e; + e.stage = stage; + e.outcome = outcome; + e.attempt_id[0] = 0xA5; + e.attempt_id[15] = static_cast(seq); + e.timestamp_ns = 100 + seq; + e.cost_units = 5; + return e; +} + +bool IsError(const auto& result, RecorderError error) { + return std::holds_alternative(result) && std::get(result) == error; +} + +EventRecorder MakeRecorder(std::vector producers, + std::uint64_t budget = 1ULL << 30) { + auto made = EventRecorder::Create(Plan(std::move(producers), budget)); + CHECK(std::holds_alternative(made)); + return std::get(std::move(made)); +} + +EventRecorder::ProducerHandle Attach(EventRecorder& recorder, ProducerOwner owner, + std::uint32_t index = 0) { + auto attached = recorder.AttachProducer(owner, index); + CHECK(std::holds_alternative(attached)); + return std::get(std::move(attached)); +} + +EventSnapshotV1 Snapshot(EventRecorder& recorder) { + auto exported = recorder.ExportSnapshotV1(); + CHECK(std::holds_alternative(exported)); + return std::get(std::move(exported)); +} + +void Publish(EventRecorder::ProducerHandle& producer, Stage stage, std::uint64_t seq) { + auto reserved = producer.Reserve(); + CHECK(std::holds_alternative(reserved)); + if (!std::holds_alternative(reserved)) return; + auto reservation = std::get(std::move(reserved)); + CHECK(reservation.producer_sequence() == seq); + CHECK(producer.Publish(std::move(reservation), Event(stage, seq)) == RecorderError::None); +} + +std::uint64_t FnvByte(std::uint64_t h, std::uint8_t b) { + return (h ^ b) * 1099511628211ULL; +} +void FnvU32(std::uint64_t& h, std::uint32_t n) { + for (int s = 24; s >= 0; s -= 8) h = FnvByte(h, static_cast(n >> s)); +} +void FnvU64(std::uint64_t& h, std::uint64_t n) { + for (int s = 56; s >= 0; s -= 8) h = FnvByte(h, static_cast(n >> s)); +} +void FnvText(std::uint64_t& h, const char* s) { while (*s) h = FnvByte(h, static_cast(*s++)); } + +template void FnvArray(std::uint64_t& h, const std::array& a) { + for (std::uint8_t b : a) h = FnvByte(h, b); +} +std::uint64_t IndependentEventChecksum(const EventV1& e) { + std::uint64_t h = 14695981039346656037ULL; + FnvText(h, "RGEV1"); + h = FnvByte(h, static_cast(e.stage)); + h = FnvByte(h, static_cast(e.outcome)); + FnvArray(h, e.attempt_id); + FnvU64(h, e.timestamp_ns); + FnvU64(h, e.cost_units); + return h; +} +std::uint64_t IndependentSealChecksum(const ProducerSnapshotV1& p) { + std::uint64_t h = 14695981039346656037ULL; + FnvText(h, "RGPS1"); + h = FnvByte(h, static_cast(p.owner)); + FnvU32(h, p.producer_index); + FnvU64(h, p.capacity); + FnvU64(h, p.reserved_count); + FnvU64(h, p.published_count); + h = FnvByte(h, p.sealed ? 1 : 0); + h = FnvByte(h, p.incomplete ? 1 : 0); + for (const auto& s : p.slots) { + h = FnvByte(h, static_cast(s.status)); + FnvU64(h, s.producer_sequence); + FnvU64(h, s.checksum64); + } + return h; +} +std::uint64_t IndependentSnapshotChecksum(const EventSnapshotV1& s) { + std::uint64_t h = 14695981039346656037ULL; + FnvText(h, "RGRN1"); + FnvU32(h, s.schema_version); + FnvArray(h, s.epoch_id); + FnvArray(h, s.policy_digest); + FnvU32(h, static_cast(s.producers.size())); + FnvU64(h, s.planned_bytes); + FnvU64(h, s.budget_bytes); + for (const auto& p : s.producers) { + h = FnvByte(h, static_cast(p.owner)); + FnvU32(h, p.producer_index); + FnvU64(h, p.capacity); + FnvU64(h, p.seal_checksum64); + } + h = FnvByte(h, s.complete ? 1 : 0); + return h; +} + +void TestBudgetBoundaries() { + const std::uint64_t exact = kRunHeaderEncodedBytes + kRunTerminalEncodedBytes + + kProducerEnvelopeEncodedBytes + kEventSlotEncodedBytes + kProducerSealEncodedBytes; + auto accepted = EventRecorder::Create(Plan({{ProducerOwner::Authority, 0, 1}}, exact)); + CHECK(std::holds_alternative(accepted)); + if (std::holds_alternative(accepted)) { + auto recorder = std::get(std::move(accepted)); + CHECK(recorder.planned_bytes() == exact); + auto p = Attach(recorder, ProducerOwner::Authority); + Publish(p, Stage::StrictDecision, 1); + CHECK(p.Seal() == RecorderError::None); + auto s = Snapshot(recorder); + CHECK(s.complete && s.planned_bytes == exact && s.budget_bytes == exact); + } + auto below = EventRecorder::Create(Plan({{ProducerOwner::Authority, 0, 1}}, exact - 1)); + CHECK(IsError(below, RecorderError::InvalidPlan)); + // 97 + 7*39 + 21,053,754*51 = 1 GiB. Reject before allocating slots. + std::vector at_cap; + for (unsigned i = 0; i < 7; ++i) + at_cap.push_back({ProducerOwner::Replica, i, i == 0 ? 21053748ULL : 1ULL}); + CHECK(IsError(EventRecorder::Create(Plan(std::move(at_cap))), RecorderError::InvalidPlan)); + auto too_large_budget = EventRecorder::Create(Plan({{ProducerOwner::Authority, 0, 1}}, kMaxRunBudgetBytes + 1)); + CHECK(IsError(too_large_budget, RecorderError::InvalidPlan)); + auto duplicate_roster = EventRecorder::Create(Plan({{ProducerOwner::Authority, 0, 1}, + {ProducerOwner::Authority, 0, 1}})); + CHECK(IsError(duplicate_roster, RecorderError::InvalidPlan)); +} + +void TestOwnerSealAndChecksums() { + auto recorder = MakeRecorder({{ProducerOwner::Authority, 0, 2}}); + auto p = Attach(recorder, ProducerOwner::Authority); + Publish(p, Stage::StrictDecision, 1); + Publish(p, Stage::StrictDecision, 2); + CHECK(p.Seal() == RecorderError::None); + CHECK(p.Reserve().index() == 1); // error alternative + CHECK(std::get(p.Reserve()) == RecorderError::ProducerSealed); + auto s = Snapshot(recorder); + CHECK(s.complete); + CHECK(s.producers.size() == 1); + const auto& row = s.producers[0]; + CHECK(row.reserved_count == 2 && row.published_count == 2 && row.sealed && !row.incomplete); + CHECK(row.slots[0].status == SlotStatus::Published && row.slots[0].producer_sequence == 1); + CHECK(row.slots[1].status == SlotStatus::Published && row.slots[1].producer_sequence == 2); + CHECK(row.slots[0].checksum64 == IndependentEventChecksum(row.slots[0].event)); + CHECK(row.slots[1].checksum64 == IndependentEventChecksum(row.slots[1].event)); + CHECK(row.seal_checksum64 == IndependentSealChecksum(row)); + CHECK(s.checksum64 == IndependentSnapshotChecksum(s)); + + auto wrong = MakeRecorder({{ProducerOwner::Authority, 0, 1}}); + auto authority = Attach(wrong, ProducerOwner::Authority); + auto r = authority.Reserve(); + auto reservation = std::get(std::move(r)); + CHECK(authority.Publish(std::move(reservation), Event(Stage::Responded, 1)) == RecorderError::InvalidEvent); + CHECK(wrong.stopped()); + CHECK(authority.Seal() == RecorderError::None); + CHECK(!Snapshot(wrong).complete); +} + +void TestGapAndStickyStop() { + auto recorder = MakeRecorder({{ProducerOwner::Authority, 0, 2}}); + auto p = Attach(recorder, ProducerOwner::Authority); + { + auto reserved = p.Reserve(); + CHECK(std::holds_alternative(reserved)); + // Destruction without publication must persistently mark the reservation incomplete. + } + CHECK(recorder.stopped()); + CHECK(IsError(p.Reserve(), RecorderError::RunStopped)); + CHECK(p.Seal() == RecorderError::None); + const auto s = Snapshot(recorder); + CHECK(!s.complete); + CHECK(s.producers[0].incomplete); + CHECK(s.producers[0].slots[0].status == SlotStatus::Incomplete); + CHECK(s.producers[0].slots[1].status == SlotStatus::Unused); +} + +void TestPartitionFailureDoesNotBorrow() { + auto recorder = MakeRecorder({{ProducerOwner::Authority, 0, 1}, + {ProducerOwner::Replica, 0, 2}}); + auto authority = Attach(recorder, ProducerOwner::Authority); + auto replica = Attach(recorder, ProducerOwner::Replica); + Publish(authority, Stage::StrictDecision, 1); + CHECK(IsError(authority.Reserve(), RecorderError::ProducerPartitionExhausted)); + CHECK(recorder.stopped()); + auto next = replica.Reserve(); + CHECK(IsError(next, RecorderError::RunStopped)); // remaining replica slots cannot be borrowed after run stop + CHECK(replica.Seal() == RecorderError::None); + const auto s = Snapshot(recorder); + CHECK(!s.complete); + CHECK(s.producers[0].capacity == 1 && s.producers[0].reserved_count == 1); + CHECK(s.producers[1].capacity == 2 && s.producers[1].reserved_count == 0); +} + +void TestOneShotProducerAndAbandonedHandle() { + auto recorder = MakeRecorder({{ProducerOwner::Authority, 3, 1}}); + { + auto p = Attach(recorder, ProducerOwner::Authority, 3); + CHECK(p.Seal() == RecorderError::None); + } + CHECK(IsError(recorder.AttachProducer(ProducerOwner::Authority, 3), RecorderError::ProducerAlreadyAttached)); + auto never = MakeRecorder({{ProducerOwner::Backend, 0, 1}}); + { auto ignored = Attach(never, ProducerOwner::Backend); } + CHECK(never.stopped()); + auto incomplete = Snapshot(never); + CHECK(!incomplete.complete && incomplete.producers[0].incomplete && !incomplete.producers[0].sealed); +} + +void TestTwoProducerIsolationAndCompleteness() { + auto recorder = MakeRecorder({{ProducerOwner::WorkloadGenerator, 0, 1}, + {ProducerOwner::Replica, 7, 1}}); + auto generator = Attach(recorder, ProducerOwner::WorkloadGenerator, 0); + auto replica = Attach(recorder, ProducerOwner::Replica, 7); + Publish(generator, Stage::Offered, 1); + Publish(replica, Stage::Responded, 1); + CHECK(generator.Seal() == RecorderError::None); + CHECK(replica.Seal() == RecorderError::None); + auto s = Snapshot(recorder); + CHECK(s.complete && s.producers.size() == 2); + CHECK(s.producers[0].owner == ProducerOwner::WorkloadGenerator); + CHECK(s.producers[1].owner == ProducerOwner::Replica && s.producers[1].producer_index == 7); +} + +void TestConcurrentLastSlotRace() { + constexpr std::size_t workers = 12; + auto recorder = MakeRecorder({{ProducerOwner::Authority, 0, 1}}); + auto producer = Attach(recorder, ProducerOwner::Authority); + std::barrier start(static_cast(workers)); + std::atomic reserved_count{0}, published_count{0}, exhausted_count{0}, stopped_count{0}; + std::vector threads; + for (std::size_t i = 0; i < workers; ++i) { + threads.emplace_back([&, i] { + start.arrive_and_wait(); + auto attempt = producer.Reserve(); + if (std::holds_alternative(attempt)) { + reserved_count.fetch_add(1, std::memory_order_relaxed); + auto reservation = std::get(std::move(attempt)); + const auto rc = producer.Publish(std::move(reservation), Event(Stage::StrictDecision, i + 1)); + if (rc == RecorderError::None) published_count.fetch_add(1, std::memory_order_relaxed); + } else if (std::get(attempt) == RecorderError::ProducerPartitionExhausted) { + exhausted_count.fetch_add(1, std::memory_order_relaxed); + } else if (std::get(attempt) == RecorderError::RunStopped) { + stopped_count.fetch_add(1, std::memory_order_relaxed); + } + }); + } + for (auto& t : threads) t.join(); + CHECK(reserved_count.load() == 1); + CHECK(published_count.load() == 1); + CHECK(exhausted_count.load() == 1); + CHECK(stopped_count.load() == workers - 2); + CHECK(recorder.stopped()); // full partition is an observable run stop, never a silent drop + CHECK(producer.Seal() == RecorderError::None); + const auto s = Snapshot(recorder); + CHECK(!s.complete); + CHECK(s.producers[0].reserved_count == 1 && s.producers[0].published_count == 1); +} + +void TestSnapshotMutationChecksumsAreObservable() { + auto recorder = MakeRecorder({{ProducerOwner::Backend, 0, 1}}); + auto backend = Attach(recorder, ProducerOwner::Backend); + Publish(backend, Stage::Completed, 1); + CHECK(backend.Seal() == RecorderError::None); + auto s = Snapshot(recorder); + CHECK(s.complete); + auto bad_event = s; + bad_event.producers[0].slots[0].event.cost_units++; + CHECK(bad_event.producers[0].slots[0].checksum64 != IndependentEventChecksum(bad_event.producers[0].slots[0].event)); + auto bad_seal = s; + bad_seal.producers[0].producer_index++; + CHECK(bad_seal.producers[0].seal_checksum64 != IndependentSealChecksum(bad_seal.producers[0])); + auto bad_run = s; + bad_run.budget_bytes++; + CHECK(bad_run.checksum64 != IndependentSnapshotChecksum(bad_run)); +} +} + +int main() { + TestBudgetBoundaries(); + TestOwnerSealAndChecksums(); + TestGapAndStickyStop(); + TestPartitionFailureDoesNotBorrow(); + TestOneShotProducerAndAbandonedHandle(); + TestTwoProducerIsolationAndCompleteness(); + TestConcurrentLastSlotRace(); + TestSnapshotMutationChecksumsAreObservable(); + if (failures != 0) { + std::cerr << "RG005 recorder tests failed: " << failures << "\n"; + return EXIT_FAILURE; + } + std::cout << "RG005 recorder component tests passed\n"; + return EXIT_SUCCESS; +} diff --git a/tests/fixtures/acquire_credit_request.hex b/tests/fixtures/acquire_credit_request.hex new file mode 100644 index 0000000..2372b53 --- /dev/null +++ b/tests/fixtures/acquire_credit_request.hex @@ -0,0 +1,3 @@ +0a 06 61 63 63 74 2d 31 10 03 1a 10 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 22 10 10 11 +12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 2a 20 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f +30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 30 07 38 05 42 07 70 75 62 6c 69 73 68 diff --git a/tests/fixtures/admission_allow_retry_123.hex b/tests/fixtures/admission_allow_retry_123.hex new file mode 100644 index 0000000..d454849 --- /dev/null +++ b/tests/fixtures/admission_allow_retry_123.hex @@ -0,0 +1,3 @@ +08 01 12 10 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 1a 20 20 21 22 23 24 25 26 27 28 29 +2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 20 01 2a 10 00 01 02 03 04 05 +06 07 08 09 0a 0b 0c 0d 0e 0f 30 7b diff --git a/tests/fixtures/admission_allow_retry_absent.hex b/tests/fixtures/admission_allow_retry_absent.hex new file mode 100644 index 0000000..d92d7e4 --- /dev/null +++ b/tests/fixtures/admission_allow_retry_absent.hex @@ -0,0 +1,3 @@ +08 01 12 10 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 1a 20 20 21 22 23 24 25 26 27 28 29 +2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 20 01 2a 10 00 01 02 03 04 05 +06 07 08 09 0a 0b 0c 0d 0e 0f diff --git a/tests/fixtures/admission_allow_retry_zero_present.hex b/tests/fixtures/admission_allow_retry_zero_present.hex new file mode 100644 index 0000000..a2a18df --- /dev/null +++ b/tests/fixtures/admission_allow_retry_zero_present.hex @@ -0,0 +1,3 @@ +08 01 12 10 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 1a 20 20 21 22 23 24 25 26 27 28 29 +2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 20 01 2a 10 00 01 02 03 04 05 +06 07 08 09 0a 0b 0c 0d 0e 0f 30 00 diff --git a/tests/fixtures/check_admission_request.hex b/tests/fixtures/check_admission_request.hex new file mode 100644 index 0000000..5b9a1cf --- /dev/null +++ b/tests/fixtures/check_admission_request.hex @@ -0,0 +1,3 @@ +0a 06 61 63 63 74 2d 31 12 07 70 75 62 6c 69 73 68 1a 10 00 01 02 03 04 05 06 07 08 09 0a 0b 0c +0d 0e 0f 22 10 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 2a 20 20 21 22 23 24 25 26 27 28 +29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f diff --git a/tests/fixtures/grant_result_granted_composite.hex b/tests/fixtures/grant_result_granted_composite.hex new file mode 100644 index 0000000..919b5c6 --- /dev/null +++ b/tests/fixtures/grant_result_granted_composite.hex @@ -0,0 +1,4 @@ +08 01 10 07 1a 30 0a 10 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 12 06 61 63 63 74 2d 31 +18 03 22 10 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 28 07 20 19 2a 10 10 11 12 13 14 15 +16 17 18 19 1a 1b 1c 1d 1e 1f 32 20 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 +34 35 36 37 38 39 3a 3b 3c 3d 3e 3f diff --git a/tests/fixtures/grant_result_limited_zero_units_present.hex b/tests/fixtures/grant_result_limited_zero_units_present.hex new file mode 100644 index 0000000..e659415 --- /dev/null +++ b/tests/fixtures/grant_result_limited_zero_units_present.hex @@ -0,0 +1,2 @@ +08 02 10 07 20 00 2a 10 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 32 20 20 21 22 23 24 25 +26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f diff --git a/tests/fixtures/policy_v1.canonical.hex b/tests/fixtures/policy_v1.canonical.hex new file mode 100644 index 0000000..774e716 --- /dev/null +++ b/tests/fixtures/policy_v1.canonical.hex @@ -0,0 +1 @@ +0000000100000002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1ffee742f3d97b519e6b7a8ee84b88b019cea856aadcd44d0dc2ac113852a6432f0000000200000002202122232425262728292a2b2c2d2e2f00000007303132333435363738393a3b3c3d3e3f0000000200000005616c7068610000000000000064000000000000000a01000000000000000800000002000000047265616400000000000000010000000577726974650000000000000005000000047a65746100000000000000140000000000000003010000000000000006000000020000000664656c6574650000000000000006000000046c697374000000000000000200000004000000297370696666653a2f2f7261746567756172642e6c6f63616c2f616461707465722f696e677265737331000000010000000200000000000000000000000100000001000000437370696666653a2f2f7261746567756172642e6c6f63616c2f617574686f726974792f31303131313231333134313531363137313831393161316231633164316531660000000300000000000000437370696666653a2f2f7261746567756172642e6c6f63616c2f7265706c6963612f322f3230323132323233323432353236323732383239326132623263326432653266000000020000000200000000000000437370696666653a2f2f7261746567756172642e6c6f63616c2f7265706c6963612f372f3330333133323333333433353336333733383339336133623363336433653366000000020000000700000000 diff --git a/tests/fixtures/policy_v1.json b/tests/fixtures/policy_v1.json new file mode 100644 index 0000000..602d981 --- /dev/null +++ b/tests/fixtures/policy_v1.json @@ -0,0 +1,60 @@ +{ + "schema_version": 1, + "mode": "credit", + "epoch_id": "000102030405060708090a0b0c0d0e0f", + "authority_incarnation": "101112131415161718191a1b1c1d1e1f", + "trust_root_sha256": "fee742f3d97b519e6b7a8ee84b88b019cea856aadcd44d0dc2ac113852a6432f", + "replica_slots": [ + {"slot_id": 7, "incarnation_id": "303132333435363738393a3b3c3d3e3f"}, + {"slot_id": 2, "incarnation_id": "202122232425262728292a2b2c2d2e2f"} + ], + "tenants": [ + { + "tenant_id": "zeta", + "capacity_units": "20", + "rate_units_per_second": "3", + "credit_batch_units": "6", + "operations": [ + {"operation_id": "list", "cost_units": "2"}, + {"operation_id": "delete", "cost_units": "6"} + ] + }, + { + "tenant_id": "alpha", + "capacity_units": "100", + "rate_units_per_second": "10", + "credit_batch_units": "8", + "operations": [ + {"operation_id": "write", "cost_units": "5"}, + {"operation_id": "read", "cost_units": "1"} + ] + } + ], + "principals": [ + { + "uri": "spiffe://rateguard.local/replica/7/303132333435363738393a3b3c3d3e3f", + "role": "replica", + "slot_id": 7, + "permissions": [] + }, + { + "uri": "spiffe://rateguard.local/adapter/ingress1", + "role": "adapter", + "permissions": [ + {"tenant_id": "zeta", "operation_id": "list"}, + {"tenant_id": "alpha", "operation_id": "read"} + ] + }, + { + "uri": "spiffe://rateguard.local/authority/101112131415161718191a1b1c1d1e1f", + "role": "authority", + "permissions": [] + }, + { + "uri": "spiffe://rateguard.local/replica/2/202122232425262728292a2b2c2d2e2f", + "role": "replica", + "slot_id": 2, + "permissions": [] + } + ] +} diff --git a/tests/history_export_test.cpp b/tests/history_export_test.cpp new file mode 100644 index 0000000..b3f77e5 --- /dev/null +++ b/tests/history_export_test.cpp @@ -0,0 +1,40 @@ +#include "src/events/history_exporter.h" + +#include +#include +#include + +using namespace rateguard::events; + +int main() { + RunPlan plan; + plan.producers.push_back({ProducerOwner::Authority, 0, 2}); + auto recorder = std::get(EventRecorder::Create(plan)); + auto producer = std::get( + recorder.AttachProducer(ProducerOwner::Authority, 0)); + auto reservation = std::get(producer.Reserve()); + EventV1 e; + e.stage = Stage::StrictDecision; + e.outcome = Outcome::Allow; + e.timestamp_ns = 123; + e.cost_units = 1; + (void)producer.Publish(std::move(reservation), e); + (void)producer.Seal(); + auto snapshot = std::get(recorder.ExportSnapshotV1()); + std::ostringstream output; + if (ExportStrictHistory(plan, snapshot, output) != ExportStatus::Complete) return 1; + // Independent fixed-width layout: header, producer, 2 slots, seal, trailer. + const std::string bytes = output.str(); + if (bytes.size() != 80 + 13 + 2 * 51 + 26 + 17 || + bytes.size() != snapshot.planned_bytes) return 2; + if (bytes.substr(0, 8) != "RGHIST01" || bytes.substr(8, 4) != std::string("\0\0\0\1", 4) || + static_cast(bytes[80]) != 2 || + static_cast(bytes[93]) != 2 || + static_cast(bytes[93 + 1 + 8 + 2 + 16 + 7]) != 123) return 3; + std::ostream failed(nullptr); + if (ExportStrictHistory(plan, snapshot, failed) != ExportStatus::WriteFailed) return 4; + snapshot.producers[0].slots[0].event.timestamp_ns++; + std::ostringstream rejected; + if (ExportStrictHistory(plan, snapshot, rejected) != ExportStatus::IncompleteHistory || + !rejected.str().empty()) return 5; +} diff --git a/tests/history_file_publisher_test.cpp b/tests/history_file_publisher_test.cpp new file mode 100644 index 0000000..0c15429 --- /dev/null +++ b/tests/history_file_publisher_test.cpp @@ -0,0 +1,156 @@ +#include "src/events/file_publisher.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::events; + +namespace { +int failures = 0; +#define CHECK(expr) do { if (!(expr)) { std::cerr << "FAIL line " << __LINE__ << ": " #expr " errno=" << errno << '\n'; ++failures; } } while (false) + +RunPlan MakePlan() { + RunPlan plan; + plan.epoch_id[0] = 0x12; + plan.policy_digest[0] = 0x34; + plan.producers.push_back({ProducerOwner::Authority, 0, 2}); + plan.budget_bytes = kMaxRunBudgetBytes; + return plan; +} +EventSnapshotV1 MakeCompleteSnapshot(RunPlan& plan) { + const std::uint64_t required = kRunHeaderEncodedBytes + kRunTerminalEncodedBytes + + kProducerEnvelopeEncodedBytes + 2*kEventSlotEncodedBytes + kProducerSealEncodedBytes; + plan.budget_bytes = required; + auto created = EventRecorder::Create(plan); + CHECK(std::holds_alternative(created)); + if (!std::holds_alternative(created)) return {}; + auto& recorder = std::get(created); + auto attached = recorder.AttachProducer(ProducerOwner::Authority, 0); + CHECK(std::holds_alternative(attached)); + if (!std::holds_alternative(attached)) return {}; + auto& producer = std::get(attached); + auto reserved = producer.Reserve(); + CHECK(std::holds_alternative(reserved)); + if (!std::holds_alternative(reserved)) return {}; + EventV1 event; + event.stage = Stage::StrictDecision; + event.outcome = Outcome::Allow; + event.attempt_id[0] = 0xab; + event.timestamp_ns = 0; // epoch-relative monotonic zero is valid + event.cost_units = 1; + CHECK(producer.Publish(std::move(std::get(reserved)), event) == + RecorderError::None); + CHECK(producer.Seal() == RecorderError::None); + auto exported = recorder.ExportSnapshotV1(); + CHECK(std::holds_alternative(exported)); + return std::get(std::move(exported)); +} +std::string ReadAllAt(int dirfd, std::string_view name) { + const std::string path(name); + const int fd = ::openat(dirfd, path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + if (fd < 0) return {}; + std::string result; + char data[128]; + for (;;) { + const auto n = ::read(fd, data, sizeof(data)); + if (n == 0) break; + if (n < 0) { if (errno == EINTR) continue; break; } + result.append(data, static_cast(n)); + } + ::close(fd); + return result; +} + +void TestPublishCollisionIncompleteAndDirectoryContract() { + char directory_template[] = "/tmp/rg005-publisher-test.XXXXXX"; + char* directory_name = ::mkdtemp(directory_template); + CHECK(directory_name != nullptr); + if (directory_name == nullptr) return; + CHECK(::chmod(directory_name, 0700) == 0); + const int dirfd = ::open(directory_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + CHECK(dirfd >= 0); + if (dirfd < 0) { ::rmdir(directory_name); return; } + + auto expected = MakePlan(); + const auto snapshot = MakeCompleteSnapshot(expected); + HistoryRunId run_id{}; + for (std::size_t i = 0; i < run_id.size(); ++i) run_id[i] = static_cast(i); + const auto published = PublishStrictHistoryFile(dirfd, 1'800'000'001, run_id, expected, snapshot); + const std::string final_name = "rg-history-v1-1800000001-000102030405060708090a0b0c0d0e0f.bin"; + CHECK(published.status == FilePublishStatus::Published); + CHECK(published.final_published && published.file_synced && published.temporary_removed && + published.directory_synced); + CHECK(published.filename() == final_name); + struct stat st{}; + CHECK(::fstatat(dirfd, final_name.c_str(), &st, AT_SYMLINK_NOFOLLOW) == 0); + CHECK(S_ISREG(st.st_mode) && (st.st_mode & 0777) == 0600); + const auto bytes = ReadAllAt(dirfd, final_name); + CHECK(bytes.size() == snapshot.planned_bytes); + CHECK(bytes.substr(0, 8) == "RGHIST01"); + + const auto collision = PublishStrictHistoryFile(dirfd, 1'800'000'001, run_id, expected, snapshot); + CHECK(collision.status == FilePublishStatus::FinalNameExists); + CHECK(!collision.final_published && collision.temporary_removed); + CHECK(ReadAllAt(dirfd, final_name) == bytes); // never overwrite existing final file + + auto incomplete_expected = MakePlan(); + auto incomplete_created = EventRecorder::Create(incomplete_expected); + CHECK(std::holds_alternative(incomplete_created)); + auto& incomplete_recorder = std::get(incomplete_created); + auto incomplete_attached = incomplete_recorder.AttachProducer(ProducerOwner::Authority, 0); + CHECK(std::holds_alternative(incomplete_attached)); + const auto incomplete = std::get(incomplete_recorder.ExportSnapshotV1()); + HistoryRunId another_id{}; another_id[0] = 0xee; + const auto rejected = PublishStrictHistoryFile(dirfd, 1'800'000'002, another_id, + incomplete_expected, incomplete); + CHECK(rejected.status == FilePublishStatus::IncompleteHistory); + CHECK(!rejected.final_published && rejected.temporary_removed); + const std::string partial = "rg-history-v1-1800000002-ee000000000000000000000000000000.bin.partial"; + CHECK(::fstatat(dirfd, partial.c_str(), &st, AT_SYMLINK_NOFOLLOW) != 0 && errno == ENOENT); + + const auto invalid_second = PublishStrictHistoryFile(dirfd, 1'000'000'000'000ULL, + run_id, expected, snapshot); + CHECK(invalid_second.status == FilePublishStatus::InvalidCreationSecond); + + const std::string existing_partial = "rg-history-v1-1800000003-000102030405060708090a0b0c0d0e0f.bin.partial"; + const int partfd = ::openat(dirfd, existing_partial.c_str(), O_CREAT | O_EXCL | O_WRONLY, + 0600); + CHECK(partfd >= 0); + if (partfd >= 0) { const char marker[] = "keep"; CHECK(::write(partfd, marker, 4) == 4); ::close(partfd); } + const auto stale_partial = PublishStrictHistoryFile(dirfd, 1'800'000'003, run_id, + expected, snapshot); + CHECK(stale_partial.status == FilePublishStatus::TemporaryNameExists); + CHECK(ReadAllAt(dirfd, existing_partial) == "keep"); + + const int regular_fd = ::openat(dirfd, "not-a-directory", O_CREAT | O_EXCL | O_WRONLY, 0600); + CHECK(regular_fd >= 0); + const auto invalid_dir = PublishStrictHistoryFile(regular_fd, 1'800'000'004, run_id, + expected, snapshot); + CHECK(invalid_dir.status == FilePublishStatus::InvalidDirectory); + if (regular_fd >= 0) { ::close(regular_fd); ::unlinkat(dirfd, "not-a-directory", 0); } + + ::unlinkat(dirfd, existing_partial.c_str(), 0); + ::unlinkat(dirfd, final_name.c_str(), 0); + ::close(dirfd); + CHECK(::rmdir(directory_name) == 0); +} +} // namespace + +int main() { + TestPublishCollisionIncompleteAndDirectoryContract(); + if (failures != 0) return 1; + std::cout << "PASS history_file_publisher\n"; + return 0; +} diff --git a/tests/history_reader_test.cpp b/tests/history_reader_test.cpp new file mode 100644 index 0000000..ecd6120 --- /dev/null +++ b/tests/history_reader_test.cpp @@ -0,0 +1,39 @@ +#include "src/events/history_exporter.h" +#include "tools/history/history_reader.h" + +#include + +using namespace rateguard::events; + +int main() { + RunPlan plan; + plan.producers = {{ProducerOwner::Adapter, 7, 1}}; + auto recorder = std::get(EventRecorder::Create(plan)); + auto adapter = std::get(recorder.AttachProducer(ProducerOwner::Adapter, 7)); + auto reservation = std::get(adapter.Reserve()); + EventV1 event; + event.stage = Stage::Received; + event.outcome = Outcome::Limited; + if (adapter.Publish(std::move(reservation), event) != RecorderError::None || + adapter.Seal() != RecorderError::None) return 1; + auto snapshot = std::get(recorder.ExportSnapshotV1()); + std::ostringstream output; + if (ExportStrictHistory(plan, snapshot, output) != ExportStatus::Complete) return 2; + const auto bytes = output.str(); + auto accepts = [&](const std::string& candidate) { + std::istringstream in(candidate); + auto result = history::ReadStrictHistory(in, plan); + const auto* decoded = std::get_if(&result); + return decoded && decoded->checksum64 == snapshot.checksum64; + }; + if (!accepts(bytes) || accepts(bytes + "x")) return 3; + for (size_t i = 0; i < bytes.size(); ++i) + if (accepts(bytes.substr(0, i))) return 4; + for (size_t i = 0; i < bytes.size(); ++i) { + auto damaged = bytes; + damaged[i] ^= 0x40; + if (accepts(damaged)) return 5; + } + plan.producers.front().event_capacity++; + if (accepts(bytes)) return 6; +} diff --git a/tests/history_validator_test.cpp b/tests/history_validator_test.cpp new file mode 100644 index 0000000..9128b55 --- /dev/null +++ b/tests/history_validator_test.cpp @@ -0,0 +1,201 @@ +#include "src/events/event_recorder.h" +#include "src/events/history_validator.h" + +#include +#include +#include +#include + +namespace { +using namespace rateguard::events; +using namespace rateguard::events::validation; + +void Check(bool condition, std::string_view name) { + if (!condition) { + std::cerr << "FAIL " << name << '\n'; + std::exit(1); + } +} + +RunPlan BasePlan(std::uint64_t budget = kMaxRunBudgetBytes) { + RunPlan plan; + plan.epoch_id[0] = 0xA1; + plan.policy_digest[0] = 0xB2; + plan.producers = { + {ProducerOwner::Backend, 0, 1}, + {ProducerOwner::Adapter, 0, 1}, + {ProducerOwner::Replica, 0, 1}, + {ProducerOwner::Authority, 0, 1}, + {ProducerOwner::WorkloadGenerator, 0, 1}, + }; + plan.budget_bytes = budget; + return plan; +} + +Stage StageFor(ProducerOwner owner) { + switch (owner) { + case ProducerOwner::WorkloadGenerator: return Stage::Offered; + case ProducerOwner::Authority: return Stage::StrictDecision; + case ProducerOwner::Replica: return Stage::Responded; + case ProducerOwner::Adapter: return Stage::Received; + case ProducerOwner::Backend: return Stage::Completed; + } + return Stage::Offered; +} + +EventSnapshotV1 CompleteSnapshot(const RunPlan& plan) { + auto created = EventRecorder::Create(plan); + Check(std::holds_alternative(created), "recorder_create"); + auto& recorder = std::get(created); + for (const auto& spec : plan.producers) { + auto attached = recorder.AttachProducer(spec.owner, spec.producer_index); + Check(std::holds_alternative(attached), "attach_producer"); + auto handle = std::move(std::get(attached)); + auto reserved = handle.Reserve(); + Check(std::holds_alternative(reserved), "reserve_event"); + EventV1 event; + event.stage = StageFor(spec.owner); + event.outcome = Outcome::Allow; + event.attempt_id[0] = 0xC3; + event.timestamp_ns = 17; + event.cost_units = 1; + const auto publish = handle.Publish( + std::move(std::get(reserved)), event); + Check(publish == RecorderError::None, "publish_event"); + Check(handle.Seal() == RecorderError::None, "seal_producer"); + } + auto exported = recorder.ExportSnapshotV1(); + Check(std::holds_alternative(exported), "export_snapshot"); + return std::get(std::move(exported)); +} + +bool Is(const EventSnapshotV1& snapshot, const RunPlan& plan, Verdict verdict, Reason reason) { + const auto report = ValidateHistorySnapshot(snapshot, plan); + return report.verdict == verdict && report.reason == reason; +} + +void TestValidAndPermutedExpectedPlan() { + auto plan = BasePlan(); + const auto snapshot = CompleteSnapshot(plan); + const auto report = ValidateHistorySnapshot(snapshot, plan); + Check(report.verdict == Verdict::Complete && report.reason == Reason::None, + "complete_snapshot_passes_structure"); + Check(report.published_events == 5 && report.snapshot_bytes == snapshot.planned_bytes, + "complete_snapshot_counts_and_extent"); + Check(!report.safety_pass_allowed(), "completeness_is_not_safety_pass"); + + std::reverse(plan.producers.begin(), plan.producers.end()); + Check(Is(snapshot, plan, Verdict::Complete, Reason::None), + "expected_roster_input_permutation_matches_canonical_snapshot"); +} + +void TestUnsealedAndGaps() { + auto plan = BasePlan(); + auto snapshot = CompleteSnapshot(plan); + snapshot.producers.front().sealed = false; + Check(Is(snapshot, plan, Verdict::Incomplete, Reason::ProducerNotSealed), + "unsealed_producer_is_incomplete"); + + snapshot = CompleteSnapshot(plan); + snapshot.producers.front().slots.front().producer_sequence = 2; + Check(Is(snapshot, plan, Verdict::Incomplete, Reason::ReservationGap), + "sequence_gap_is_incomplete"); + + snapshot = CompleteSnapshot(plan); + snapshot.producers.front().slots.front().status = SlotStatus::Reserved; + Check(Is(snapshot, plan, Verdict::Incomplete, Reason::ReservedSlotUnpublished), + "reserved_unpublished_slot_is_incomplete"); +} + +void TestCorruptionAndRoster() { + auto plan = BasePlan(); + auto snapshot = CompleteSnapshot(plan); + snapshot.producers.front().slots.front().checksum64 ^= 1; + Check(Is(snapshot, plan, Verdict::Incomplete, Reason::EventChecksumMismatch), + "event_checksum_corruption_is_incomplete"); + + snapshot = CompleteSnapshot(plan); + snapshot.producers.front().seal_checksum64 ^= 1; + Check(Is(snapshot, plan, Verdict::Incomplete, Reason::ProducerChecksumMismatch), + "producer_seal_checksum_corruption_is_incomplete"); + + snapshot = CompleteSnapshot(plan); + snapshot.checksum64 ^= 1; + Check(Is(snapshot, plan, Verdict::Incomplete, Reason::SnapshotChecksumMismatch), + "run_checksum_corruption_is_incomplete"); + + snapshot = CompleteSnapshot(plan); + snapshot.producers.front().slots.front().event.stage = Stage::Forwarded; + Check(Is(snapshot, plan, Verdict::Invalid, Reason::StageOwnerMismatch), + "wrong_stage_owner_is_invalid"); + + snapshot = CompleteSnapshot(plan); + snapshot.producers.pop_back(); + Check(Is(snapshot, plan, Verdict::Incomplete, Reason::ProducerMissing), + "missing_expected_producer_is_incomplete"); + + snapshot = CompleteSnapshot(plan); + snapshot.producers[1] = snapshot.producers[0]; + Check(Is(snapshot, plan, Verdict::Invalid, Reason::ProducerOrderOrCapacityMismatch), + "duplicate_or_noncanonical_producer_is_invalid"); + + snapshot = CompleteSnapshot(plan); + snapshot.producers.push_back(snapshot.producers.back()); + Check(Is(snapshot, plan, Verdict::Invalid, Reason::ProducerUnexpected), + "unexpected_producer_is_invalid"); +} + +void TestExpectedPlanAndCaps() { + auto plan = BasePlan(); + auto snapshot = CompleteSnapshot(plan); + + auto wrong_epoch = plan; + wrong_epoch.epoch_id[0] ^= 1; + Check(Is(snapshot, wrong_epoch, Verdict::Invalid, Reason::ExpectedPlanMismatch), + "epoch_mismatch_rejected"); + auto wrong_digest = plan; + wrong_digest.policy_digest[0] ^= 1; + Check(Is(snapshot, wrong_digest, Verdict::Invalid, Reason::ExpectedPlanMismatch), + "policy_digest_mismatch_rejected"); + auto wrong_capacity = plan; + wrong_capacity.producers.front().event_capacity = 2; + Check(Is(snapshot, wrong_capacity, Verdict::Invalid, Reason::ExpectedPlanMismatch), + "producer_capacity_mismatch_rejected"); + auto wrong_budget = plan; + --wrong_budget.budget_bytes; + Check(Is(snapshot, wrong_budget, Verdict::Invalid, Reason::ExpectedPlanMismatch), + "run_budget_mismatch_rejected"); + auto wrong_extent = snapshot; + ++wrong_extent.planned_bytes; + Check(Is(wrong_extent, plan, Verdict::Invalid, Reason::ExpectedPlanMismatch), + "serialized_extent_mismatch_rejected"); + auto bad_schema = snapshot; + bad_schema.schema_version = 2; + Check(Is(bad_schema, plan, Verdict::Invalid, Reason::SchemaMismatch), + "unknown_schema_rejected"); + + // Fixed-width exact-budget plans below the global cap are valid. + constexpr std::uint64_t exact_plan_bytes = 80 + 17 + 5 * (13 + 51 + 26); + auto exact_plan = BasePlan(exact_plan_bytes); + const auto exact_snapshot = CompleteSnapshot(exact_plan); + Check(exact_snapshot.planned_bytes == exact_plan_bytes && + Is(exact_snapshot, exact_plan, Verdict::Complete, Reason::None), + "exact_smaller_budget_plan_is_valid"); + + auto undersized_plan = BasePlan(exact_plan_bytes - 1); + Check(Is(exact_snapshot, undersized_plan, Verdict::Invalid, Reason::InvalidExpectedPlan), + "budget_below_required_extent_rejected"); + auto oversized_budget = BasePlan(kMaxRunBudgetBytes + 1); + Check(Is(exact_snapshot, oversized_budget, Verdict::Invalid, Reason::InvalidExpectedPlan), + "budget_above_global_cap_rejected"); +} + +} // namespace + +int main() { + TestValidAndPermutedExpectedPlan(); + TestUnsealedAndGaps(); + TestCorruptionAndRoster(); + TestExpectedPlanAndCaps(); + std::cout << "RG-005 validator cases passed\n"; +} diff --git a/tests/policy_driver.cpp b/tests/policy_driver.cpp new file mode 100644 index 0000000..2e87ea9 --- /dev/null +++ b/tests/policy_driver.cpp @@ -0,0 +1,82 @@ +#include "src/policy/canonical_codec.h" +#include "src/policy/policy_loader.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using nlohmann::json; + +std::string Hex(const std::uint8_t* bytes, std::size_t size) { + constexpr char digits[] = "0123456789abcdef"; + std::string result(size * 2, '0'); + for (std::size_t i = 0; i < size; ++i) { + result[2 * i] = digits[bytes[i] >> 4]; + result[2 * i + 1] = digits[bytes[i] & 0x0f]; + } + return result; +} + +const char* CodeName(rateguard::policy::PolicyErrorCode code) { + using rateguard::policy::PolicyErrorCode; + switch (code) { + case PolicyErrorCode::InvalidJson: return "invalid_json"; + case PolicyErrorCode::InvalidSchema: return "invalid_schema"; + case PolicyErrorCode::InvalidValue: return "invalid_value"; + case PolicyErrorCode::ResourceLimit: return "resource_limit"; + case PolicyErrorCode::CryptoFailure: return "crypto_failure"; + case PolicyErrorCode::EncodingFailure: return "encoding_failure"; + } + return "unknown"; +} + +int Error(rateguard::policy::PolicyError error) { + json output{{"status", "error"}, {"code", CodeName(error.code)}, + {"message", std::move(error.message)}}; + std::cout << output.dump() << '\n'; + return 2; +} +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::cerr << "usage: policy_driver \n"; + return 64; + } + try { + const std::filesystem::path path(argv[1]); + const auto size = std::filesystem::file_size(path); + if (size == 0 || size > rateguard::policy::PolicyLoader::kMaxJsonBytes) + return Error({rateguard::policy::PolicyErrorCode::ResourceLimit, + "policy JSON must be 1..64 MiB"}); + std::ifstream input(path, std::ios::binary); + if (!input) return Error({rateguard::policy::PolicyErrorCode::InvalidJson, + "unable to read policy JSON"}); + const std::string bytes{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + auto loaded = rateguard::policy::PolicyLoader::Load(bytes); + if (const auto* error = std::get_if(&loaded)) return Error(*error); + const auto& snapshot = *std::get>(loaded); + + auto encoded = rateguard::policy::CanonicalPolicyCodec::Encode(snapshot); + if (const auto* error = std::get_if(&encoded)) return Error(*error); + const auto& canonical = std::get>(encoded); + auto digest = rateguard::policy::CanonicalPolicyCodec::Digest(snapshot); + if (const auto* error = std::get_if(&digest)) return Error(*error); + const auto& sha = std::get(digest); + + json output{{"status", "ok"}, {"canonical_hex", Hex(canonical.data(), canonical.size())}, + {"sha256", Hex(sha.data(), sha.size())}}; + std::cout << output.dump() << '\n'; + return 0; + } catch (const std::exception&) { + return Error({rateguard::policy::PolicyErrorCode::InvalidJson, + "policy driver failed"}); + } +} diff --git a/tests/policy_test.cpp b/tests/policy_test.cpp new file mode 100644 index 0000000..4b0a4ca --- /dev/null +++ b/tests/policy_test.cpp @@ -0,0 +1,237 @@ +#include "../src/policy/canonical_codec.h" +#include "../src/policy/policy_loader.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using nlohmann::json; +using namespace rateguard::policy; +int failures = 0; + +void Check(bool condition, std::string_view name) { + if (!condition) { + std::cerr << "FAIL: " << name << '\n'; + ++failures; + } +} + +std::string ReadText(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) return {}; + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +std::string ReadHex(const std::string& path) { + const std::string text = ReadText(path); + std::string output; + auto digit = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + }; + std::string compact; + for (unsigned char c : text) + if (c != ' ' && c != '\n' && c != '\r' && c != '\t') compact.push_back(static_cast(c)); + if (compact.empty() || compact.size() % 2 != 0) return {}; + output.reserve(compact.size() / 2); + for (std::size_t i = 0; i < compact.size(); i += 2) { + const int high = digit(compact[i]); + const int low = digit(compact[i + 1]); + if (high < 0 || low < 0) return {}; + output.push_back(static_cast((high << 4) | low)); + } + return output; +} + +std::string Hex(const std::uint8_t* bytes, std::size_t size) { + constexpr char digits[] = "0123456789abcdef"; + std::string result(size * 2, '0'); + for (std::size_t i = 0; i < size; ++i) { + result[2 * i] = digits[bytes[i] >> 4]; + result[2 * i + 1] = digits[bytes[i] & 0x0f]; + } + return result; +} + +bool Rejected(std::string_view input) { + return std::holds_alternative(PolicyLoader::Load(input)); +} + +bool CryptoFailureIsTypedInIsolatedChild(const PolicySnapshot& snapshot) { + const pid_t child = fork(); + if (child < 0) return false; + if (child == 0) { + bool restored = false; + bool typed_failure = false; + { + struct RestoreDefaultProperties { + bool& restored; + ~RestoreDefaultProperties() { + restored = EVP_set_default_properties(nullptr, nullptr) == 1; + } + } restore{restored}; + + if (EVP_set_default_properties(nullptr, "provider=rateguard_no_such_provider") == 1) { + const auto result = CanonicalPolicyCodec::Digest(snapshot); + if (const auto* error = std::get_if(&result)) + typed_failure = error->code == PolicyErrorCode::CryptoFailure; + } + } + _exit(typed_failure && restored ? 0 : 1); + } + + int status = 0; + while (waitpid(child, &status, 0) < 0) { + if (errno != EINTR) return false; + } + return WIFEXITED(status) && WEXITSTATUS(status) == 0; +} +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::cerr << "usage: policy_test \n"; + return 2; + } + const std::string root = argv[1]; + const std::string json_path = root + "/tests/fixtures/policy_v1.json"; + const std::string expected_path = root + "/tests/fixtures/policy_v1.canonical.hex"; + const std::string input = ReadText(json_path); + Check(!input.empty(), "read canonical policy fixture"); + + auto loaded = PolicyLoader::Load(input); + if (const auto* error = std::get_if(&loaded)) { + std::cerr << "fixture load failed: " << error->message << '\n'; + return 1; + } + const auto snapshot = std::get>(loaded); + Check(snapshot->mode() == Mode::Credit, "mode loaded"); + Check(snapshot->tenants().size() == 2 && snapshot->tenants()[0].tenant_id == "alpha" && + snapshot->tenants()[1].tenant_id == "zeta", "tenant table sorted"); + Check(snapshot->replica_slots().size() == 2 && snapshot->replica_slots()[0].slot_id == 2 && + snapshot->replica_slots()[1].slot_id == 7, "arbitrary slot IDs sorted numerically"); + const TenantPolicy* alpha = snapshot->FindTenant("alpha"); + Check(alpha != nullptr && alpha->capacity_units == 100 && alpha->rate_units_per_second == 10 && + alpha->credit_batch_units == 8 && alpha->initial_balance_subunits() == 100'000'000'000ULL, + "validated tenant fields and full-B initial balance"); + Check(alpha != nullptr && alpha->FindOperation("read") != nullptr && + alpha->FindOperation("missing") == nullptr, "operation lookup is read-only"); + Check(snapshot->FindTenant("unconfigured") == nullptr, "unknown tenant lookup does not insert"); + const std::string adapter = "spiffe://rateguard.local/adapter/ingress1"; + Check(snapshot->IsAuthorized(adapter, PrincipalRole::Adapter, "alpha", "read"), + "registered adapter permission resolves"); + Check(!snapshot->IsAuthorized(adapter, PrincipalRole::Adapter, "alpha", "write"), + "unlisted operation is unauthorized"); + Check(!snapshot->IsAuthorized(adapter, PrincipalRole::Replica, "alpha", "read"), + "principal role is part of authorization"); + + auto encoded = CanonicalPolicyCodec::Encode(*snapshot); + Check(std::holds_alternative>(encoded), "encode succeeds"); + if (const auto* bytes = std::get_if>(&encoded)) { + const std::string expected_bytes = ReadHex(expected_path); + const std::string actual_bytes(reinterpret_cast(bytes->data()), bytes->size()); + Check(expected_bytes.size() == 580, "independent canonical fixture is 580 bytes"); + Check(actual_bytes == expected_bytes, "canonical bytes match independent Python oracle exactly"); + } + auto digest = CanonicalPolicyCodec::Digest(*snapshot); + Check(std::holds_alternative(digest), "SHA-256 digest succeeds"); + if (const auto* hash = std::get_if(&digest)) + Check(Hex(hash->data(), hash->size()) == + "0fa75c3373b71fc7c21ce0417258ea6545986d884c69c16f2ee8d6d9fefe00ff", + "SHA-256 matches independent Python oracle"); + Check(CryptoFailureIsTypedInIsolatedChild(*snapshot), + "unavailable OpenSSL provider returns typed crypto failure and restores properties"); + + json shuffled = json::parse(input); + std::reverse(shuffled["replica_slots"].begin(), shuffled["replica_slots"].end()); + std::reverse(shuffled["tenants"].begin(), shuffled["tenants"].end()); + std::reverse(shuffled["principals"].begin(), shuffled["principals"].end()); + for (auto& tenant : shuffled["tenants"]) + std::reverse(tenant["operations"].begin(), tenant["operations"].end()); + for (auto& principal : shuffled["principals"]) + std::reverse(principal["permissions"].begin(), principal["permissions"].end()); + auto shuffled_result = PolicyLoader::Load(shuffled.dump()); + Check(std::holds_alternative>(shuffled_result), + "input table order variation accepted"); + if (const auto* reordered = std::get_if>(&shuffled_result)) { + auto reordered_digest = CanonicalPolicyCodec::Digest(**reordered); + if (const auto* reordered_hash = std::get_if(&reordered_digest)) { + if (const auto* original_hash = std::get_if(&digest)) + Check(*reordered_hash == *original_hash, "input order normalizes to identical digest"); + else + Check(false, "original digest available for order comparison"); + } else { + Check(false, "reordered digest succeeds"); + } + } + + Check(Rejected("{\"schema_version\":1,\"schema_version\":1}"), "duplicate object keys rejected"); + json invalid = json::parse(input); + invalid["unexpected"] = true; + Check(Rejected(invalid.dump()), "unknown field rejected"); + invalid = json::parse(input); + invalid["schema_version"] = 1.0; + Check(Rejected(invalid.dump()), "floating-point schema version rejected"); + invalid = json::parse(input); + invalid["tenants"][0]["credit_batch_units"] = "4"; + Check(Rejected(invalid.dump()), "Q below maximum operation cost rejected"); + invalid = json::parse(input); + invalid["tenants"][0]["operations"].push_back(invalid["tenants"][0]["operations"][0]); + Check(Rejected(invalid.dump()), "duplicate operation ID rejected"); + invalid = json::parse(input); + invalid["principals"][0]["slot_id"] = 8; + Check(Rejected(invalid.dump()), "URI/slot membership mismatch rejected"); + invalid = json::parse(input); + invalid["principals"][1]["permissions"][0]["tenant_id"] = "unknown"; + Check(Rejected(invalid.dump()), "unknown authorization reference rejected"); + invalid = json::parse(input); + invalid["epoch_id"] = "000102030405060708090A0b0c0d0e0f"; + Check(Rejected(invalid.dump()), "non-lowercase epoch hex rejected"); + invalid = json::parse(input); + invalid["mode"] = "strict"; + for (auto& tenant : invalid["tenants"]) tenant.erase("credit_batch_units"); + auto strict = PolicyLoader::Load(invalid.dump()); + Check(std::holds_alternative>(strict), + "strict mode omits per-tenant credit Q"); + + // Exercise the loader's own byte cap directly; the command-line integration + // driver also checks file size before calling Load. + std::string exact_limit = input; + if (exact_limit.size() < PolicyLoader::kMaxJsonBytes) + exact_limit.append(PolicyLoader::kMaxJsonBytes - exact_limit.size(), ' '); + Check(exact_limit.size() == PolicyLoader::kMaxJsonBytes, + "construct exactly 64 MiB policy JSON"); + auto exact_limit_result = PolicyLoader::Load(exact_limit); + Check(std::holds_alternative>(exact_limit_result), + "exactly 64 MiB valid JSON is accepted"); + const std::string over_limit(PolicyLoader::kMaxJsonBytes + 1, ' '); + auto over_limit_result = PolicyLoader::Load(over_limit); + const auto* over_limit_error = std::get_if(&over_limit_result); + Check(over_limit_error != nullptr && + over_limit_error->code == PolicyErrorCode::ResourceLimit, + "PolicyLoader itself rejects input one byte over 64 MiB"); + + std::string deeply_nested; + for (int i = 0; i < 33; ++i) deeply_nested.push_back('['); + deeply_nested.append(33, ']'); + Check(Rejected(deeply_nested), "JSON nesting beyond 32 containers rejected"); + + if (failures != 0) return 1; + std::cout << "policy loader and canonical codec checks passed\n"; + return 0; +} diff --git a/tests/retry_behavior_test.cpp b/tests/retry_behavior_test.cpp new file mode 100644 index 0000000..0e9b647 --- /dev/null +++ b/tests/retry_behavior_test.cpp @@ -0,0 +1,83 @@ +#include "proto/rateguard/v1/admission.grpc.pb.h" +#include "rateguard/v1/channel_policy.h" +#include +#include +#include +#include +#include +#include + +namespace { +class UnavailableService final : public rateguard::v1::AdmissionService::Service { + public: + std::atomic calls{0}; + grpc::Status CheckAdmission(grpc::ServerContext*, + const rateguard::v1::CheckAdmissionRequest*, + rateguard::v1::AdmissionDecision*) override { + calls.fetch_add(1, std::memory_order_relaxed); + // No initial metadata or response is sent: configured retries may retry. + return {grpc::StatusCode::UNAVAILABLE, "synthetic retry fixture"}; + } +}; +const char* kRetryConfig = R"json({ + "methodConfig":[{ + "name":[{"service":"rateguard.v1.AdmissionService","method":"CheckAdmission"}], + "retryPolicy":{"maxAttempts":4,"initialBackoff":"0.01s", + "maxBackoff":"0.01s","backoffMultiplier":1, + "retryableStatusCodes":["UNAVAILABLE"]} + }] +})json"; +bool Invoke(const std::shared_ptr& channel) { + auto stub = rateguard::v1::AdmissionService::NewStub(channel); + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(5)); + rateguard::v1::CheckAdmissionRequest request; + rateguard::v1::AdmissionDecision response; + return stub->CheckAdmission(&context, request, &response).error_code() + == grpc::StatusCode::UNAVAILABLE; +} +} // namespace + +int main() { + UnavailableService service; + grpc::ServerBuilder builder; + int port = 0; + // Synthetic loopback fixture only. Runtime mTLS belongs to RG-004. + builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port); + builder.RegisterService(&service); + auto server = builder.BuildAndStart(); + if (!server || port == 0) return 1; + const auto target = "127.0.0.1:" + std::to_string(port); + int failures = 0; + + // Positive control: demonstrate that this fixture really causes four + // application invocations when configurable retries are enabled. + grpc::ChannelArguments retry_enabled; + retry_enabled.SetInt(GRPC_ARG_ENABLE_RETRIES, 1); + retry_enabled.SetServiceConfigJSON(kRetryConfig); + auto enabled = grpc::CreateCustomChannel( + target, grpc::InsecureChannelCredentials(), retry_enabled); + if (!Invoke(enabled) || service.calls.load() != 4) { + std::cerr << "retry-enabled control must invoke service four times\n"; + ++failures; + } + + service.calls.store(0); + // Even with a retry policy supplied, enforcement arguments prevent an + // invisible replay after the server application has observed the request. + auto enforcement = rateguard::v1::transport::EnforcementChannelArguments(); + enforcement.SetServiceConfigJSON(kRetryConfig); + auto disabled = grpc::CreateCustomChannel( + target, grpc::InsecureChannelCredentials(), enforcement); + if (!Invoke(disabled) || service.calls.load() != 1) { + std::cerr << "enforcement policy must invoke service exactly once\n"; + ++failures; + } + enabled.reset(); + disabled.reset(); + server->Shutdown(); + server->Wait(); + if (failures) return 1; + std::cout << "retry behavior: enabled=4, enforcement=1\n"; + return 0; +} diff --git a/tests/security/authorization_resolver_test.cpp b/tests/security/authorization_resolver_test.cpp new file mode 100644 index 0000000..dece5f9 --- /dev/null +++ b/tests/security/authorization_resolver_test.cpp @@ -0,0 +1,476 @@ +#include "rateguard/security/authorization_resolver.h" + +#include "ephemeral_pki.h" +#include "policy/canonical_codec.h" +#include "policy/policy_loader.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; +namespace contract = rateguard::v1::contract; +using rateguard::security::test::EphemeralPki; + +namespace { + +[[noreturn]] void Fail(std::string_view label) { + std::cerr << "FAIL " << label << '\n'; + std::exit(1); +} +void Check(bool condition, std::string_view label) { + if (!condition) Fail(label); +} + +class FixedClock final : public sec::ITrustedWallClock { + public: + explicit FixedClock(sec::WallTime value) : value_(value) {} + sec::TrustedWallClockResult Now() override { + ++calls; + if (!healthy_ && !return_value_when_unhealthy_) return sec::TrustedWallClockFailure{ + sec::TrustedWallClockFailureReason::PlatformUnavailable}; + return value_; + } + bool Healthy() const override { return healthy_; } + void Set(sec::WallTime value) { value_ = value; } + void SetUnhealthyButReturnValue() { healthy_ = false; return_value_when_unhealthy_ = true; } + unsigned calls{}; + private: + sec::WallTime value_; + bool healthy_{true}; + bool return_value_when_unhealthy_{false}; +}; + +class EmptyAuthIterator final : public grpc::AuthPropertyIterator { + public: + EmptyAuthIterator() : grpc::AuthPropertyIterator() {} +}; + +class FakeAuthContext final : public grpc::AuthContext { + public: + bool IsPeerAuthenticated() const override { return authenticated_; } + std::vector GetPeerIdentity() const override { + std::vector result; + const auto found = properties_.find(identity_name_); + if (found != properties_.end()) + for (const auto& value : found->second) result.emplace_back(value); + return result; + } + std::string GetPeerIdentityPropertyName() const override { return identity_name_; } + std::vector FindPropertyValues( + const std::string& name) const override { + std::vector result; + const auto found = properties_.find(name); + if (found != properties_.end()) + for (const auto& value : found->second) result.emplace_back(value); + return result; + } + grpc::AuthPropertyIterator begin() const override { return EmptyAuthIterator{}; } + grpc::AuthPropertyIterator end() const override { return EmptyAuthIterator{}; } + void AddProperty(const std::string& key, const grpc::string_ref& value) override { + properties_[key].emplace_back(value.data(), value.size()); + } + bool SetPeerIdentityPropertyName(const std::string& name) override { + identity_name_ = name; + return true; + } + void Add(std::string key, std::string value) { + properties_[std::move(key)].push_back(std::move(value)); + } + void SetAuthenticated(bool value) { authenticated_ = value; } + private: + bool authenticated_{true}; + std::string identity_name_{GRPC_PEER_URI_PROPERTY_NAME}; + std::map, std::less<>> properties_; +}; + +std::string ReadFile(const std::string& path) { + std::ifstream in(path, std::ios::binary); + if (!in) return {}; + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +std::string Hex(std::span bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string out; + out.reserve(bytes.size() * 2); + for (const auto b : bytes) { + out.push_back(digits[b >> 4]); + out.push_back(digits[b & 15]); + } + return out; +} + +pol::Digest32 RootDigest(std::string_view pem) { + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (!raw_bio) Fail("fixture_root_parse"); + std::unique_ptr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (!raw_cert) Fail("fixture_root_parse"); + std::unique_ptr cert(raw_cert, X509_free); + const int size = i2d_X509(cert.get(), nullptr); + if (size <= 0 || size > 64 * 1024) Fail("fixture_root_der"); + std::vector der(static_cast(size)); + auto* cursor = der.data(); + if (i2d_X509(cert.get(), &cursor) != size) Fail("fixture_root_der"); + pol::Digest32 digest{}; + unsigned int written = 0; + if (EVP_Digest(der.data(), der.size(), digest.data(), &written, + EVP_sha256(), nullptr) != 1 || written != digest.size()) + Fail("fixture_root_digest"); + return digest; +} + +struct Fixture { + EphemeralPki pki; + std::shared_ptr policy; + std::shared_ptr registry; + std::vector> identity_pems; + pol::Digest32 digest{}; + sec::WallTime now{}; + + explicit Fixture(const std::string& policy_path) { + auto root = RootDigest(pki.root_certificate_pem()); + auto json = nlohmann::json::parse(ReadFile(policy_path)); + json["trust_root_sha256"] = Hex(root); + for (auto& principal : json["principals"]) { + if (principal["role"] == "replica" && principal.value("slot_id", 0U) == 7U) { + principal["permissions"].push_back({{"tenant_id", "zeta"}, + {"operation_id", "list"}}); + } + } + auto loaded = pol::PolicyLoader::Load(json.dump()); + const auto* snapshot = std::get_if>(&loaded); + if (snapshot == nullptr) Fail("fixture_policy"); + policy = *snapshot; + auto digest_result = pol::CanonicalPolicyCodec::Digest(*policy); + const auto* digest_ptr = std::get_if(&digest_result); + if (digest_ptr == nullptr) Fail("fixture_policy_digest"); + digest = *digest_ptr; + + std::vector leaf_views; + std::vector owned_pems; + for (const auto& principal : policy->principals()) { + sec::PeerRole role = sec::PeerRole::kAdapter; + if (principal.role == pol::PrincipalRole::Replica) role = sec::PeerRole::kReplica; + if (principal.role == pol::PrincipalRole::Authority) role = sec::PeerRole::kAuthority; + const auto& identity = pki.Issue(role, principal.uri); + identity_pems.emplace_back(principal.uri, identity.certificate_pem); + owned_pems.push_back(identity.certificate_pem); + } + for (const auto& pem : owned_pems) leaf_views.emplace_back(pem); + const auto system_seconds = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + now = {system_seconds, 0}; + FixedClock clock(now); + auto registry_result = sec::CertificateRegistryLoader::Load( + policy, pki.root_certificate_pem(), leaf_views, clock); + const auto* value = std::get_if>( + ®istry_result); + if (value == nullptr) Fail("fixture_registry"); + registry = *value; + } + + FakeAuthContext Context(std::string_view uri) const { + FakeAuthContext context; + const auto found = std::find_if(identity_pems.begin(), identity_pems.end(), + [&](const auto& entry) { return entry.first == uri; }); + if (found == identity_pems.end()) Fail("fixture_identity"); + context.Add(GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, + GRPC_TLS_TRANSPORT_SECURITY_TYPE); + context.Add(GRPC_PEER_URI_PROPERTY_NAME, found->first); + context.Add(GRPC_X509_PEM_CERT_PROPERTY_NAME, found->second); + return context; + } +}; + +std::string Bytes(const auto& array) { + return {reinterpret_cast(array.data()), array.size()}; +} + +void CheckFailure(const auto& result, sec::AuthorizationDisposition expected, + sec::AuthorizationFailureReason reason, std::string_view label) { + const auto* failure = std::get_if(&result); + Check(failure != nullptr, label); + Check(failure->disposition == expected && failure->reason == reason, label); +} + +void Run(const std::string& policy_path) { + Fixture fixture(policy_path); + FixedClock clock(fixture.now); + auto resolver_result = sec::AuthorizationResolver::Create(fixture.registry, clock); + auto* resolver = std::get_if(&resolver_result); + Check(resolver != nullptr, "resolver_create_valid_binding"); + if (resolver == nullptr) return; + + sec::PeerAuthenticator authenticator(fixture.registry, clock); + const auto adapter_it = std::find_if(fixture.policy->principals().begin(), + fixture.policy->principals().end(), [](const auto& p) { + return p.role == pol::PrincipalRole::Adapter; + }); + const auto replica_it = std::find_if(fixture.policy->principals().begin(), + fixture.policy->principals().end(), [](const auto& p) { + return p.role == pol::PrincipalRole::Replica && p.slot_id == 7U; + }); + Check(adapter_it != fixture.policy->principals().end() && + replica_it != fixture.policy->principals().end(), "fixture_has_adapter_replica"); + if (adapter_it == fixture.policy->principals().end() || + replica_it == fixture.policy->principals().end()) return; + + const auto adapter_result = authenticator.Authenticate(fixture.Context(adapter_it->uri)); + auto* adapter = std::get_if(&adapter_result); + Check(adapter != nullptr, "adapter_authenticated"); + const auto replica_result = authenticator.Authenticate(fixture.Context(replica_it->uri)); + auto* replica = std::get_if(&replica_result); + Check(replica != nullptr, "replica_authenticated"); + if (adapter == nullptr || replica == nullptr) return; + + rateguard::v1::CheckAdmissionRequest check; + check.set_tenant_id("zeta"); + check.set_operation_id("list"); + check.set_attempt_id(std::string(16, 'a')); + check.set_epoch_id(Bytes(fixture.policy->epoch_id())); + check.set_policy_digest(Bytes(fixture.digest)); + + auto allowed = resolver->Resolve(*adapter, sec::RpcMethod::AdapterCheckAdmission, check); + const auto* authorized = std::get_if(&allowed); + Check(authorized && authorized->cost_units() == 2 && + authorized->mode() == pol::Mode::Credit && + authorized->tenant_id() == "zeta" && authorized->operation_id() == "list" && + authorized->attempt_id() == std::string(16, 'a') && + authorized->peer().uri() == adapter_it->uri && + authorized->method() == sec::RpcMethod::AdapterCheckAdmission, + "adapter_allowed_policy_cost_and_identity"); + if (authorized) { + const sec::AuthorizedOperation copied = *authorized; + Check(copied.peer().uri() == adapter_it->uri && + authorized->registry().get() == fixture.registry.get(), + "authorization_proof_copy_retains_registry"); + } + + auto forbidden = check; + forbidden.set_operation_id("delete"); + auto denied = resolver->Resolve(*adapter, sec::RpcMethod::AdapterCheckAdmission, forbidden); + CheckFailure(denied, sec::AuthorizationDisposition::PermissionDenied, + sec::AuthorizationFailureReason::UnauthorizedPair, + "configured_but_forbidden_pair_denied"); + + auto unknown = check; + unknown.set_tenant_id("unknown"); + auto unknown_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, unknown); + CheckFailure(unknown_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::UnknownTenant, + "unknown_tenant_invalid_argument"); + auto unknown_operation = check; + unknown_operation.set_operation_id("missing"); + auto unknown_operation_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, unknown_operation); + CheckFailure(unknown_operation_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::UnknownOperation, + "unknown_operation_invalid_argument"); + + auto short_attempt = check; + short_attempt.set_attempt_id(std::string(15, 'a')); + auto short_id_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, short_attempt); + CheckFailure(short_id_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::InvalidRequest, + "attempt_id_width_rejected"); + auto stale_digest = check; + stale_digest.set_policy_digest(std::string(32, 'x')); + auto stale_digest_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, stale_digest); + CheckFailure(stale_digest_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::PolicyBindingMismatch, + "stale_policy_digest_rejected"); + + // Unknown wire field 6 is not a trusted cost input; configured policy cost + // remains the only cost returned by the resolver. + auto cost_extension = check; + cost_extension.GetReflection()->MutableUnknownFields(&cost_extension)->AddVarint(6, 999); + auto extension_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, cost_extension); + const auto* extension_auth = std::get_if(&extension_result); + Check(extension_auth && extension_auth->cost_units() == 2, + "unknown_cost_wire_field_cannot_change_policy_cost"); + auto oversized = check; + oversized.GetReflection()->MutableUnknownFields(&oversized)->AddLengthDelimited( + 100, std::string(16 * 1024, 'x')); + auto oversized_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, oversized); + CheckFailure(oversized_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::InvalidRequest, + "decoded_payload_size_rejected"); + + auto malformed = check; + malformed.set_attempt_id("short"); + auto wrong_role_malformed = resolver->Resolve(*adapter, + sec::RpcMethod::ReplicaStrictCheck, malformed); + CheckFailure(wrong_role_malformed, sec::AuthorizationDisposition::PermissionDenied, + sec::AuthorizationFailureReason::MethodRoleMismatch, + "wrong_role_precedes_malformed_fields"); + auto bad_overload = resolver->Resolve(*adapter, + sec::RpcMethod::ReplicaAcquireCredit, check); + CheckFailure(bad_overload, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::InvalidRequest, + "wrong_method_overload_invalid_argument"); + auto unknown_method = resolver->Resolve(*adapter, + static_cast(255), check); + CheckFailure(unknown_method, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::InvalidRequest, + "unknown_method_invalid_argument"); + + auto strict_mismatch = resolver->Resolve(*replica, + sec::RpcMethod::ReplicaStrictCheck, check); + CheckFailure(strict_mismatch, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::ModeMismatch, + "strict_method_rejected_under_credit_policy"); + + rateguard::v1::AcquireCreditRequest grant; + grant.set_tenant_id("zeta"); + grant.set_slot(7); + const auto slot = std::find_if(fixture.policy->replica_slots().begin(), + fixture.policy->replica_slots().end(), [](const auto& entry) { + return entry.slot_id == 7; + }); + Check(slot != fixture.policy->replica_slots().end(), "fixture_slot_7"); + if (slot == fixture.policy->replica_slots().end()) return; + grant.set_incarnation_id(Bytes(slot->incarnation_id)); + grant.set_epoch_id(Bytes(fixture.policy->epoch_id())); + grant.set_policy_digest(Bytes(fixture.digest)); + grant.set_sequence(1); + grant.set_trigger_cost_units(2); + grant.set_trigger_operation_id("list"); + auto grant_result = resolver->Resolve(*replica, + sec::RpcMethod::ReplicaAcquireCredit, grant); + const auto* grant_auth = std::get_if(&grant_result); + Check(grant_auth && grant_auth->cost_units() == 2 && grant_auth->slot() == 7 && + grant_auth->sequence() == 1 && grant_auth->peer().uri() == replica_it->uri && + grant_auth->method() == sec::RpcMethod::ReplicaAcquireCredit && + grant_auth->incarnation_id() == slot->incarnation_id, + "replica_credit_authorized_without_claiming_grant"); + + auto bad_cost = grant; + bad_cost.set_trigger_cost_units(3); + auto cost_result = resolver->Resolve(*replica, + sec::RpcMethod::ReplicaAcquireCredit, bad_cost); + CheckFailure(cost_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::TriggerCostMismatch, + "trigger_cost_mismatch_rejected"); + auto zero_sequence = grant; + zero_sequence.set_sequence(0); + auto sequence_result = resolver->Resolve(*replica, + sec::RpcMethod::ReplicaAcquireCredit, zero_sequence); + CheckFailure(sequence_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::InvalidRequest, + "zero_sequence_rejected"); + auto wrong_slot = grant; + wrong_slot.set_slot(2); + auto slot_result = resolver->Resolve(*replica, + sec::RpcMethod::ReplicaAcquireCredit, wrong_slot); + CheckFailure(slot_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::ReplicaSlotMismatch, + "wrong_registered_slot_rejected"); + auto wrong_incarnation = grant; + wrong_incarnation.set_incarnation_id(std::string(16, 'x')); + auto incarnation_result = resolver->Resolve(*replica, + sec::RpcMethod::ReplicaAcquireCredit, wrong_incarnation); + CheckFailure(incarnation_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::ReplicaIncarnationMismatch, + "wrong_incarnation_rejected"); + auto forbidden_cost = grant; + forbidden_cost.set_trigger_operation_id("delete"); + forbidden_cost.set_trigger_cost_units(999); + auto forbidden_cost_result = resolver->Resolve(*replica, + sec::RpcMethod::ReplicaAcquireCredit, forbidden_cost); + CheckFailure(forbidden_cost_result, sec::AuthorizationDisposition::PermissionDenied, + sec::AuthorizationFailureReason::UnauthorizedPair, + "unauthorized_pair_precedes_cost_binding"); + + auto stale = check; + stale.set_epoch_id(std::string(16, 'x')); + auto stale_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, stale); + CheckFailure(stale_result, sec::AuthorizationDisposition::InvalidArgument, + sec::AuthorizationFailureReason::PolicyBindingMismatch, + "stale_epoch_rejected"); + + // Same URI and certificate under a separately loaded snapshot is still a + // mixed proof; the resolver requires exact registry object identity. + std::vector leaf_views; + for (const auto& identity : fixture.identity_pems) leaf_views.emplace_back(identity.second); + auto duplicate_registry_result = sec::CertificateRegistryLoader::Load( + fixture.policy, fixture.pki.root_certificate_pem(), leaf_views, clock); + const auto* duplicate_registry = std::get_if< + std::shared_ptr>(&duplicate_registry_result); + Check(duplicate_registry != nullptr, "duplicate_snapshot_loads"); + if (duplicate_registry != nullptr) { + sec::PeerAuthenticator duplicate_auth(*duplicate_registry, clock); + const auto duplicate_peer_result = duplicate_auth.Authenticate( + fixture.Context(adapter_it->uri)); + const auto* duplicate_peer = std::get_if( + &duplicate_peer_result); + Check(duplicate_peer != nullptr, "duplicate_snapshot_peer_authenticates"); + if (duplicate_peer != nullptr) { + auto mixed = resolver->Resolve(*duplicate_peer, + sec::RpcMethod::AdapterCheckAdmission, check); + CheckFailure(mixed, sec::AuthorizationDisposition::Unauthenticated, + sec::AuthorizationFailureReason::MixedRegistry, + "mixed_registry_token_rejected"); + } + } + + // The same authenticated token is revalidated against current UTC at every + // Resolve call; expiration cannot be bypassed by holding the token. + const auto* adapter_cert = fixture.registry->Find(adapter_it->uri); + Check(adapter_cert != nullptr, "adapter_registry_record"); + if (adapter_cert != nullptr) { + clock.Set(adapter_cert->validity.not_after); + auto expired_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, check); + CheckFailure(expired_result, sec::AuthorizationDisposition::Unauthenticated, + sec::AuthorizationFailureReason::CertificateExpired, + "fresh_expiry_checked_per_resolve"); + } + clock.Set(fixture.now); + clock.SetUnhealthyButReturnValue(); + const unsigned clock_calls = clock.calls; + auto clock_result = resolver->Resolve(*adapter, + sec::RpcMethod::AdapterCheckAdmission, check); + CheckFailure(clock_result, sec::AuthorizationDisposition::ApplicationUnavailable, + sec::AuthorizationFailureReason::ClockUntrusted, + "untrusted_clock_fails_closed"); + Check(clock.calls == clock_calls, + "unhealthy_clock_rejected_before_sampling_value"); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) Fail("usage: authorization_resolver_test policy_fixture.json"); + Run(argv[1]); + std::cout << "PASS authorization_resolver_policy_identity_clock" << '\n'; + return 0; +} diff --git a/tests/security/certificate_registry_profile_test.cpp b/tests/security/certificate_registry_profile_test.cpp new file mode 100644 index 0000000..c7a0a77 --- /dev/null +++ b/tests/security/certificate_registry_profile_test.cpp @@ -0,0 +1,241 @@ +#include "rateguard/security/certificate_registry.h" +#include "policy/policy_loader.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; +namespace { +using Key = std::unique_ptr; +using Cert = std::unique_ptr; +unsigned case_count = 0; +[[noreturn]] void Fail(std::string_view label) { + std::cerr << "FAIL registry_profile " << label << '\n'; + std::exit(1); +} +void Require(bool value, std::string_view label) { if (!value) Fail(label); } +struct Profile { + int curve = NID_X9_62_prime256v1; + bool sha384 = false; + const char* constraints = nullptr; + const char* usage = nullptr; + const char* eku = nullptr; + const char* before = nullptr; + const char* after = nullptr; + bool noncanonical_before = false; + bool corrupt_signature = false; + bool omit_san = false; + bool duplicate_san = false; +}; +Key NewKey(int curve) { + std::unique_ptr context( + EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr), EVP_PKEY_CTX_free); + Require(context && EVP_PKEY_keygen_init(context.get()) == 1 && + EVP_PKEY_CTX_set_ec_paramgen_curve_nid(context.get(), curve) == 1, + "fixture_key_setup"); + EVP_PKEY* key = nullptr; + Require(EVP_PKEY_keygen(context.get(), &key) == 1, "fixture_keygen"); + return Key(key, EVP_PKEY_free); +} +void Extension(X509* cert, X509* issuer, int nid, const std::string& value) { + X509V3_CTX context{}; + X509V3_set_ctx(&context, issuer, cert, nullptr, nullptr, 0); + std::unique_ptr extension( + X509V3_EXT_conf_nid(nullptr, &context, nid, const_cast(value.c_str())), + X509_EXTENSION_free); + Require(extension && X509_add_ext(cert, extension.get(), -1) == 1, + "fixture_extension"); +} +Cert NewCertificate(EVP_PKEY* key, X509* root, EVP_PKEY* root_key, + pol::PrincipalRole role, std::string_view uri, + const Profile& profile) { + static long serial = 1; + Cert cert(X509_new(), X509_free); + Require(cert && X509_set_version(cert.get(), 2) == 1 && + ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), serial++) == 1 && + X509_set_pubkey(cert.get(), key) == 1, "fixture_certificate"); + Require(X509_gmtime_adj(X509_getm_notBefore(cert.get()), -3600) && + X509_gmtime_adj(X509_getm_notAfter(cert.get()), 3600), "fixture_time"); + if (profile.before) + Require(ASN1_TIME_set_string_X509(X509_getm_notBefore(cert.get()), profile.before) == 1, + "fixture_before"); + if (profile.after) + Require(ASN1_TIME_set_string_X509(X509_getm_notAfter(cert.get()), profile.after) == 1, + "fixture_after"); + if (profile.noncanonical_before) { + std::unique_ptr time( + ASN1_STRING_type_new(V_ASN1_GENERALIZEDTIME), ASN1_TIME_free); + Require(time && ASN1_STRING_set(time.get(), "20200101000000Z", 15) == 1 && + X509_set1_notBefore(cert.get(), time.get()) == 1, "fixture_noncanonical"); + } + X509_NAME* subject = X509_get_subject_name(cert.get()); + const char* name = root ? "Registry profile leaf" : "Registry profile root"; + Require(X509_NAME_add_entry_by_txt(subject, "CN", MBSTRING_ASC, + reinterpret_cast(name), -1, -1, 0) == 1 && + X509_set_issuer_name(cert.get(), root ? X509_get_subject_name(root) : subject) == 1, + "fixture_names"); + X509* issuer = root ? root : cert.get(); + Extension(cert.get(), issuer, NID_basic_constraints, + profile.constraints ? profile.constraints : root ? "critical,CA:FALSE" : "critical,CA:TRUE,pathlen:0"); + Extension(cert.get(), issuer, NID_key_usage, + profile.usage ? profile.usage : root ? "critical,digitalSignature" : "critical,keyCertSign,cRLSign"); + Extension(cert.get(), issuer, NID_subject_key_identifier, "hash"); + Extension(cert.get(), issuer, NID_authority_key_identifier, "keyid:always"); + if (root) { + const char* eku = profile.eku ? profile.eku : role == pol::PrincipalRole::Adapter ? + "clientAuth" : role == pol::PrincipalRole::Authority ? "serverAuth" : "clientAuth,serverAuth"; + Extension(cert.get(), issuer, NID_ext_key_usage, eku); + if (!profile.omit_san) + Extension(cert.get(), issuer, NID_subject_alt_name, "URI:" + std::string(uri)); + if (profile.duplicate_san) + Extension(cert.get(), issuer, NID_subject_alt_name, "URI:" + std::string(uri)); + } + Require(X509_sign(cert.get(), root ? root_key : key, + profile.sha384 ? EVP_sha384() : EVP_sha256()) > 0, + "fixture_sign"); + if (profile.corrupt_signature) { + const int count = i2d_X509(cert.get(), nullptr); + Require(count > 0, "fixture_corrupt_size"); + std::vector bytes(static_cast(count)); + auto* destination = bytes.data(); + Require(i2d_X509(cert.get(), &destination) == count, "fixture_corrupt_der"); + bytes.back() ^= 1; + const auto* source = bytes.data(); + cert.reset(d2i_X509(nullptr, &source, count)); + Require(static_cast(cert), "fixture_corrupt_parse"); + } + return cert; +} +std::string Pem(X509* cert) { + std::unique_ptr bio(BIO_new(BIO_s_mem()), BIO_free); + Require(bio && PEM_write_bio_X509(bio.get(), cert) == 1, "fixture_pem"); + char* bytes = nullptr; + const long size = BIO_get_mem_data(bio.get(), &bytes); + Require(size > 0 && bytes, "fixture_pem_bytes"); + return {bytes, static_cast(size)}; +} +std::string RootHash(X509* cert) { + unsigned char digest[EVP_MAX_MD_SIZE]{}; + unsigned int size = 0; + Require(X509_digest(cert, EVP_sha256(), digest, &size) == 1 && size == 32, + "fixture_root_hash"); + constexpr char hex[] = "0123456789abcdef"; + std::string result; + for (unsigned int i = 0; i < size; ++i) { + result.push_back(hex[digest[i] >> 4]); result.push_back(hex[digest[i] & 15]); + } + return result; +} +class Clock final : public sec::ITrustedWallClock { + public: + Clock() : now_{std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(), 0} {} + sec::TrustedWallClockResult Now() override { return now_; } + bool Healthy() const override { return true; } + private: + sec::WallTime now_; +}; +void Run(const nlohmann::json& fixture, std::string_view label, const Profile& root_profile, + const Profile& leaf_profile, std::optional expected) { + ++case_count; + Key root_key = NewKey(root_profile.curve); + Cert root = NewCertificate(root_key.get(), nullptr, nullptr, + pol::PrincipalRole::Authority, "", root_profile); + auto json = fixture; + json["trust_root_sha256"] = RootHash(root.get()); + auto loaded = pol::PolicyLoader::Load(json.dump()); + Require(std::holds_alternative>(loaded), + "fixture_policy"); + auto policy = std::get>(loaded); + std::vector leafs; + for (const auto& principal : policy->principals()) { + const Profile profile = principal.role == pol::PrincipalRole::Adapter ? leaf_profile : Profile{}; + Key key = NewKey(profile.curve); + Cert leaf = NewCertificate(key.get(), root.get(), root_key.get(), principal.role, + principal.uri, profile); + leafs.push_back(Pem(leaf.get())); + } + std::vector views; + for (const auto& pem : leafs) views.emplace_back(pem); + Clock clock; + const auto result = sec::CertificateRegistryLoader::Load(policy, Pem(root.get()), views, clock); + if (expected) { + const auto* error = std::get_if(&result); + Require(error && error->code == *expected, label); + } else { + const auto* registry = std::get_if>(&result); + Require(registry && *registry, label); + Require((*registry)->AllValidAt(std::get(clock.Now())), label); + } +} +} // namespace + +int main(int argc, char** argv) { + Require(argc == 2, "usage"); + std::ifstream input(argv[1]); + Require(static_cast(input), "fixture_open"); + const auto fixture = nlohmann::json::parse(input); + using Error = sec::CertificateRegistryErrorCode; + Run(fixture, "positive", {}, {}, std::nullopt); + Profile root; + root.curve = NID_secp384r1; + Run(fixture, "root_p384", root, {}, Error::InvalidRootProfile); + root = {}; root.sha384 = true; + Run(fixture, "root_sha384", root, {}, Error::InvalidRootProfile); + root = {}; root.constraints = "critical,CA:FALSE"; + Run(fixture, "root_non_ca", root, {}, Error::InvalidRootProfile); + root = {}; root.constraints = "critical,CA:TRUE,pathlen:1"; + Run(fixture, "root_path_length", root, {}, Error::InvalidRootProfile); + root = {}; root.usage = "critical,digitalSignature"; + Run(fixture, "root_no_certificate_sign", root, {}, Error::InvalidRootProfile); + root = {}; root.corrupt_signature = true; + Run(fixture, "root_invalid_self_signature", root, {}, Error::InvalidRootProfile); + root = {}; root.noncanonical_before = true; + Run(fixture, "root_generalized_before_2050", root, {}, Error::InvalidRootProfile); + root = {}; root.before = "690101000000Z"; root.after = "99991231235959Z"; + Run(fixture, "root_signed_pre_epoch_maximum_year", root, {}, std::nullopt); + root = {}; root.before = "200101000000Z"; root.after = "210101000000Z"; + Run(fixture, "root_expired", root, {}, Error::CertificateExpired); + root = {}; root.before = "20500101000000Z"; root.after = "99991231235959Z"; + Run(fixture, "root_future", root, {}, Error::CertificateNotYetValid); + Profile leaf; + leaf.curve = NID_secp384r1; + Run(fixture, "leaf_p384", {}, leaf, Error::InvalidLeafProfile); + leaf = {}; leaf.sha384 = true; + Run(fixture, "leaf_sha384", {}, leaf, Error::InvalidLeafProfile); + leaf = {}; leaf.constraints = "critical,CA:TRUE,pathlen:0"; + Run(fixture, "leaf_ca", {}, leaf, Error::InvalidLeafProfile); + leaf = {}; leaf.usage = "critical,keyEncipherment"; + Run(fixture, "leaf_no_digital_signature", {}, leaf, Error::InvalidLeafProfile); + leaf = {}; leaf.eku = "clientAuth,serverAuth"; + Run(fixture, "adapter_extra_server_eku", {}, leaf, Error::InvalidLeafProfile); + leaf = {}; leaf.eku = "anyExtendedKeyUsage"; + Run(fixture, "leaf_any_eku", {}, leaf, Error::InvalidLeafProfile); + leaf = {}; leaf.noncanonical_before = true; + Run(fixture, "leaf_generalized_before_2050", {}, leaf, Error::InvalidLeafProfile); + leaf = {}; leaf.before = "690101000000Z"; + Run(fixture, "leaf_signed_pre_epoch", {}, leaf, std::nullopt); + leaf = {}; leaf.omit_san = true; + Run(fixture, "leaf_missing_san", {}, leaf, Error::IdentityMismatch); + leaf = {}; leaf.duplicate_san = true; + Run(fixture, "leaf_duplicate_san_extension", {}, leaf, Error::IdentityMismatch); + std::cout << "PASS registry_profile_cases=" << case_count << '\n'; +} diff --git a/tests/security/certificate_registry_test.cpp b/tests/security/certificate_registry_test.cpp new file mode 100644 index 0000000..591165c --- /dev/null +++ b/tests/security/certificate_registry_test.cpp @@ -0,0 +1,311 @@ +#include "ephemeral_pki.h" + +#include "policy/canonical_codec.h" +#include "policy/policy_loader.h" +#include "rateguard/security/certificate_registry.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; +namespace { + +int failures = 0; +void Check(bool condition, std::string_view label) { + if (!condition) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} + +class TestClock final : public sec::ITrustedWallClock { + public: + explicit TestClock(sec::WallTime time, bool healthy = true) + : time_(time), healthy_(healthy) {} + sec::TrustedWallClockResult Now() override { + ++calls; + if (!healthy_) return sec::TrustedWallClockFailure{ + sec::TrustedWallClockFailureReason::PlatformUnavailable}; + return time_; + } + bool Healthy() const override { return healthy_; } + void Set(sec::WallTime time) { time_ = time; } + unsigned calls{}; + private: + sec::WallTime time_; + bool healthy_; +}; + +std::string ReadFile(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) return {}; + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +std::string Hex(const std::uint8_t* data, std::size_t size) { + constexpr char digits[] = "0123456789abcdef"; + std::string result(size * 2, '0'); + for (std::size_t i = 0; i < size; ++i) { + result[i * 2] = digits[data[i] >> 4]; + result[i * 2 + 1] = digits[data[i] & 0x0f]; + } + return result; +} + +bool RootDigest(std::string_view pem, pol::Digest32* digest) { + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (!raw_bio) return false; + std::unique_ptr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (!raw_cert) return false; + std::unique_ptr cert(raw_cert, X509_free); + const int length = i2d_X509(cert.get(), nullptr); + if (length <= 0 || length > 64 * 1024) return false; + std::vector der(static_cast(length)); + unsigned char* cursor = der.data(); + if (i2d_X509(cert.get(), &cursor) != length) return false; + unsigned int written = 0; + return EVP_Digest(der.data(), der.size(), digest->data(), &written, + EVP_sha256(), nullptr) == 1 && written == digest->size(); +} + +struct Fixture { + sec::test::EphemeralPki pki; + std::shared_ptr snapshot; + std::vector identities; + std::vector leaf_pems; + std::string policy_error; + + explicit Fixture(const std::string& policy_fixture_path) { + const std::string base = ReadFile(policy_fixture_path); + if (base.empty()) { policy_error = "fixture unavailable"; return; } + pol::Digest32 root_hash{}; + if (!RootDigest(pki.root_certificate_pem(), &root_hash)) { + policy_error = "root digest failed"; + return; + } + try { + auto json = nlohmann::json::parse(base); + json["trust_root_sha256"] = Hex(root_hash.data(), root_hash.size()); + const std::string bound_policy = json.dump(); + auto loaded = pol::PolicyLoader::Load(bound_policy); + if (const auto* error = std::get_if(&loaded)) { + policy_error = error->message; + return; + } + snapshot = std::get>(std::move(loaded)); + identities.reserve(snapshot->principals().size()); + leaf_pems.reserve(snapshot->principals().size()); + for (const auto& principal : snapshot->principals()) { + sec::PeerRole role = sec::PeerRole::kAdapter; + switch (principal.role) { + case pol::PrincipalRole::Adapter: role = sec::PeerRole::kAdapter; break; + case pol::PrincipalRole::Replica: role = sec::PeerRole::kReplica; break; + case pol::PrincipalRole::Authority: role = sec::PeerRole::kAuthority; break; + } + const auto& identity = pki.IssueWithValidity(role, principal.uri, -60, 3600); + identities.push_back(&identity); + leaf_pems.push_back(identity.certificate_pem); + } + } catch (const std::exception&) { + policy_error = "fixture setup failed"; + } + } +}; + +using LoadResult = sec::CertificateRegistryResult< + std::shared_ptr>; + +const sec::CertificateRegistry* Loaded(const LoadResult& result) { + const auto* value = std::get_if>(&result); + return value ? value->get() : nullptr; +} + +std::optional ErrorOf(const LoadResult& result) { + const auto* error = std::get_if(&result); + return error ? std::optional(error->code) : std::nullopt; +} + +void TestValidSnapshotAndOrder(const std::string& policy_path) { + Fixture fixture(policy_path); + Check(fixture.snapshot != nullptr, "policy fixture loads with ephemeral root fingerprint"); + if (!fixture.snapshot) return; + TestClock clock({1'800'000'000, 0}); + // The certificate fixture is generated relative to system time. Select that + // time for successful construction; boundary tests use copied bounds below. + const auto system_seconds = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + clock.Set({system_seconds, 0}); + const auto result = sec::CertificateRegistryLoader::Load( + fixture.snapshot, fixture.pki.root_certificate_pem(), fixture.leaf_pems, clock); + const auto* registry = Loaded(result); + Check(registry != nullptr, "valid direct root and every leaf create snapshot"); + Check(clock.calls == 1, "load samples trusted wall clock exactly once"); + if (!registry) return; + Check(registry->validated_at() == sec::WallTime{system_seconds, 0}, + "snapshot records validation sample without retaining input PEM"); + Check(registry->epoch_id() == fixture.snapshot->epoch_id() && + registry->authority_incarnation() == fixture.snapshot->authority_incarnation(), + "registry is bound to immutable policy epoch and authority"); + const auto digest = pol::CanonicalPolicyCodec::Digest(*fixture.snapshot); + Check(std::get_if(&digest) != nullptr && + registry->policy_digest() == std::get(digest), + "registry carries canonical policy digest"); + Check(registry->peers().size() == fixture.snapshot->principals().size(), + "registry includes exactly the policy principal set"); + Check(registry->peer_pins() && registry->peer_pins()->valid() && + registry->AllValidAt({system_seconds, 0}), "registry exposes immutable verifier pins and validity"); + + auto reversed = fixture.leaf_pems; + std::reverse(reversed.begin(), reversed.end()); + TestClock second_clock({system_seconds, 0}); + const auto reordered = sec::CertificateRegistryLoader::Load( + fixture.snapshot, fixture.pki.root_certificate_pem(), reversed, second_clock); + const auto* reordered_registry = Loaded(reordered); + Check(reordered_registry && reordered_registry->peers().size() == registry->peers().size(), + "leaf input order does not affect sorted immutable registry"); + if (reordered_registry) { + for (std::size_t i = 0; i < registry->peers().size(); ++i) { + Check(registry->peers()[i].peer.uri == reordered_registry->peers()[i].peer.uri && + registry->peers()[i].peer.leaf_der_sha256 == reordered_registry->peers()[i].peer.leaf_der_sha256, + "canonical registry order and pins are stable"); + } + } +} + +void TestHalfOpenTimeBoundaries(const std::string& policy_path) { + Fixture fixture(policy_path); + if (!fixture.snapshot) { Check(false, "time fixture policy loads"); return; } + const auto system_seconds = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + TestClock initial_clock({system_seconds, 0}); + const auto initial = sec::CertificateRegistryLoader::Load( + fixture.snapshot, fixture.pki.root_certificate_pem(), fixture.leaf_pems, initial_clock); + const auto* registry = Loaded(initial); + Check(registry != nullptr, "time boundary fixture validates initially"); + if (!registry) return; + + sec::WallTime latest_start = registry->root_validity().not_before; + sec::WallTime earliest_end = registry->root_validity().not_after; + for (const auto& peer : registry->peers()) { + if (latest_start < peer.validity.not_before) latest_start = peer.validity.not_before; + if (peer.validity.not_after < earliest_end) earliest_end = peer.validity.not_after; + } + Check(latest_start < earliest_end, "all fixture certificates have a common valid interval"); + if (!(latest_start < earliest_end)) return; + + auto LoadAt = [&](sec::WallTime time) { + TestClock clock(time); + return sec::CertificateRegistryLoader::Load( + fixture.snapshot, fixture.pki.root_certificate_pem(), fixture.leaf_pems, clock); + }; + Check(ErrorOf(LoadAt({latest_start.unix_seconds - 1, 999'999'999U})) == + sec::CertificateRegistryErrorCode::CertificateNotYetValid, + "notBefore minus one nanosecond is rejected"); + Check(Loaded(LoadAt(latest_start)) != nullptr, "notBefore is inclusive"); + Check(Loaded(LoadAt({latest_start.unix_seconds, 1U})) != nullptr, + "notBefore plus one nanosecond is valid"); + Check(Loaded(LoadAt({earliest_end.unix_seconds - 1, 999'999'999U})) != nullptr, + "notAfter minus one nanosecond is valid"); + Check(ErrorOf(LoadAt(earliest_end)) == sec::CertificateRegistryErrorCode::CertificateExpired, + "notAfter is exclusive"); + Check(ErrorOf(LoadAt({earliest_end.unix_seconds, 1U})) == + sec::CertificateRegistryErrorCode::CertificateExpired, + "notAfter plus one nanosecond is expired"); +} + +void TestInputAndBindingFailures(const std::string& policy_path) { + Fixture fixture(policy_path); + if (!fixture.snapshot) { Check(false, "negative fixture policy loads"); return; } + const auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + auto load = [&](std::string_view root, std::span leaves, + TestClock& clock) { + return sec::CertificateRegistryLoader::Load(fixture.snapshot, root, leaves, clock); + }; + TestClock clock({now, 0}); + std::string prefix = "untrusted-prefix\n" + fixture.pki.root_certificate_pem(); + Check(ErrorOf(load(prefix, fixture.leaf_pems, clock)) == + sec::CertificateRegistryErrorCode::InvalidPem, + "non-whitespace prefix is rejected"); + std::string trailing = fixture.pki.root_certificate_pem() + "extra"; + Check(ErrorOf(load(trailing, fixture.leaf_pems, clock)) == + sec::CertificateRegistryErrorCode::InvalidPem, + "non-whitespace trailing data is rejected"); + Check(ErrorOf(load(fixture.pki.root_certificate_pem(), + std::span(fixture.leaf_pems).first(fixture.leaf_pems.size() - 1), + clock)) == sec::CertificateRegistryErrorCode::LeafCountMismatch, + "missing leaf is rejected"); + auto duplicate = fixture.leaf_pems; + duplicate.back() = duplicate.front(); + Check(ErrorOf(load(fixture.pki.root_certificate_pem(), duplicate, clock)) == + sec::CertificateRegistryErrorCode::DuplicateLeaf, + "duplicate principal leaf is rejected"); + auto extra = fixture.leaf_pems; + extra.push_back(extra.front()); + Check(ErrorOf(load(fixture.pki.root_certificate_pem(), extra, clock)) == + sec::CertificateRegistryErrorCode::LeafCountMismatch, + "extra leaf is rejected"); + + sec::test::EphemeralPki foreign; + const auto& foreign_root_peer = foreign.Issue(sec::PeerRole::kAdapter, + fixture.snapshot->principals().front().uri); + (void)foreign_root_peer; + Check(ErrorOf(load(foreign.root_certificate_pem(), fixture.leaf_pems, clock)) == + sec::CertificateRegistryErrorCode::RootFingerprintMismatch, + "different root fingerprint cannot bind to policy snapshot"); + + std::string oversized(sec::CertificateRegistry::kMaxCertificatePemBytes + 1, ' '); + Check(ErrorOf(load(oversized, fixture.leaf_pems, clock)) == + sec::CertificateRegistryErrorCode::ResourceLimit, + "per-certificate PEM bound is enforced before parsing"); + std::string cap_filler(sec::CertificateRegistry::kMaxCertificatePemBytes, ' '); + std::vector over_aggregate(1024, cap_filler); + Check(ErrorOf(load(fixture.pki.root_certificate_pem(), over_aggregate, clock)) == + sec::CertificateRegistryErrorCode::ResourceLimit, + "aggregate public PEM cap includes all supplied leaf entries"); + std::vector too_many(sec::CertificateRegistry::kMaxPrincipalCount + 1, + std::string_view{}); + Check(ErrorOf(load(fixture.pki.root_certificate_pem(), too_many, clock)) == + sec::CertificateRegistryErrorCode::ResourceLimit, + "principal count cap is enforced"); + + TestClock untrusted({now, 0}, false); + Check(ErrorOf(load(fixture.pki.root_certificate_pem(), fixture.leaf_pems, untrusted)) == + sec::CertificateRegistryErrorCode::ClockUntrusted, + "untrusted current time fails closed"); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::cerr << "usage: certificate_registry_test \n"; + return 2; + } + TestValidSnapshotAndOrder(argv[1]); + TestHalfOpenTimeBoundaries(argv[1]); + TestInputAndBindingFailures(argv[1]); + if (failures != 0) return 1; + std::cout << "certificate registry checks passed\n"; + return 0; +} diff --git a/tests/security/client_call_guard_test.cpp b/tests/security/client_call_guard_test.cpp new file mode 100644 index 0000000..60ec422 --- /dev/null +++ b/tests/security/client_call_guard_test.cpp @@ -0,0 +1,449 @@ +#include "rateguard/security/client_call_guard.h" + +#include "ephemeral_pki.h" +#include "policy/canonical_codec.h" +#include "policy/policy_loader.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; +using rateguard::security::test::EphemeralPki; + +namespace { + +[[noreturn]] void Fail(std::string_view label) { + std::cerr << "FAIL " << label << '\n'; + std::exit(1); +} +void Check(bool condition, std::string_view label) { + if (!condition) Fail(label); +} + +sec::WallTime JustBefore(sec::WallTime value) { + if (value.unix_seconds <= 0 || value.nanoseconds != 0) + Fail("fixture_whole_second_boundary"); + return {value.unix_seconds - 1, 999'999'999U}; +} + +class FixedClock final : public sec::ITrustedWallClock { + public: + explicit FixedClock(sec::WallTime value) : value_(value) {} + sec::TrustedWallClockResult Now() override { + ++calls; + if (fail_after_sample_) { + healthy_ = false; + return value_; + } + if (!healthy_ && !return_value_when_unhealthy_) + return sec::TrustedWallClockFailure{ + sec::TrustedWallClockFailureReason::PlatformUnavailable}; + return value_; + } + bool Healthy() const override { ++health_checks; return healthy_; } + void Set(sec::WallTime value) { value_ = value; } + void SetUnhealthyValue() { healthy_ = false; return_value_when_unhealthy_ = true; } + void FailAfterSample() { fail_after_sample_ = true; } + mutable unsigned health_checks{}; + unsigned calls{}; + private: + sec::WallTime value_; + bool healthy_{true}; + bool return_value_when_unhealthy_{false}; + bool fail_after_sample_{false}; +}; + +std::string ReadFile(const std::string& path) { + std::ifstream in(path, std::ios::binary); + if (!in) return {}; + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +std::string Hex(std::span bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string out; + out.reserve(bytes.size() * 2); + for (const auto b : bytes) { + out.push_back(digits[b >> 4]); + out.push_back(digits[b & 15]); + } + return out; +} + +pol::Digest32 RootDigest(std::string_view pem) { + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (!raw_bio) Fail("fixture_root_parse"); + std::unique_ptr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (!raw_cert) Fail("fixture_root_parse"); + std::unique_ptr cert(raw_cert, X509_free); + const int size = i2d_X509(cert.get(), nullptr); + if (size <= 0 || size > 64 * 1024) Fail("fixture_root_der"); + std::vector der(static_cast(size)); + auto* cursor = der.data(); + if (i2d_X509(cert.get(), &cursor) != size) Fail("fixture_root_der"); + pol::Digest32 digest{}; + unsigned int written = 0; + if (EVP_Digest(der.data(), der.size(), digest.data(), &written, + EVP_sha256(), nullptr) != 1 || written != digest.size()) + Fail("fixture_root_digest"); + return digest; +} + +sec::PeerRole ToPeerRole(pol::PrincipalRole role) { + switch (role) { + case pol::PrincipalRole::Adapter: return sec::PeerRole::kAdapter; + case pol::PrincipalRole::Replica: return sec::PeerRole::kReplica; + case pol::PrincipalRole::Authority: return sec::PeerRole::kAuthority; + } + Fail("fixture_role"); +} + +struct Fixture final { + EphemeralPki pki; + std::shared_ptr policy; + std::shared_ptr registry; + std::string root_pem; + std::vector leaf_pems; + std::map uri_by_role; + std::map not_before_by_role; + std::map not_after_by_role; + sec::WallTime now{}; + + Fixture(const std::string& policy_path, + const std::map>& validity = {}) { + root_pem = pki.root_certificate_pem(); + auto json = nlohmann::json::parse(ReadFile(policy_path)); + json["trust_root_sha256"] = Hex(RootDigest(root_pem)); + auto loaded = pol::PolicyLoader::Load(json.dump()); + const auto* snapshot = std::get_if>(&loaded); + if (snapshot == nullptr) Fail("fixture_policy"); + policy = *snapshot; + + const auto seconds = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + now = {seconds, 0}; + leaf_pems.reserve(policy->principals().size()); + for (const auto& principal : policy->principals()) { + const auto role = ToPeerRole(principal.role); + uri_by_role.try_emplace(role, principal.uri); + const auto interval = validity.find(role); + const auto& identity = interval == validity.end() + ? pki.Issue(role, principal.uri) + : pki.IssueWithValidity(role, principal.uri, + interval->second.first, interval->second.second); + leaf_pems.push_back(identity.certificate_pem); + } + std::vector leaf_views; + leaf_views.reserve(leaf_pems.size()); + for (const auto& pem : leaf_pems) leaf_views.emplace_back(pem); + FixedClock clock(now); + auto registry_result = sec::CertificateRegistryLoader::Load( + policy, root_pem, leaf_views, clock); + const auto* value = std::get_if>( + ®istry_result); + if (value == nullptr) Fail("fixture_registry"); + registry = *value; + for (const auto& [role, uri] : uri_by_role) { + const auto* cert = registry->Find(uri); + if (cert == nullptr) Fail("fixture_registry_lookup"); + not_before_by_role[role] = cert->validity.not_before; + not_after_by_role[role] = cert->validity.not_after; + } + } +}; + +template +void CheckFailure(const T& result, sec::ClientGuardDisposition disposition, + sec::ClientGuardFailureReason reason, + std::string_view label) { + const auto* failure = std::get_if(&result); + Check(failure != nullptr, label); + Check(failure->disposition == disposition && failure->reason == reason, label); +} + +auto CreateGuard(const std::shared_ptr& registry, + sec::ITrustedWallClock& clock, sec::ClientCallPurpose purpose, + const std::map& uris) { + sec::PeerRole local_role = purpose == sec::ClientCallPurpose::AdapterToReplicaAdmission + ? sec::PeerRole::kAdapter : sec::PeerRole::kReplica; + sec::PeerRole server_role = purpose == sec::ClientCallPurpose::AdapterToReplicaAdmission + ? sec::PeerRole::kReplica : sec::PeerRole::kAuthority; + return sec::ClientCallGuard::Create(registry, clock, purpose, + uris.at(local_role), uris.at(server_role)); +} + +void TestHappyPathAndBindings(const std::string& policy_path) { + Fixture fixture(policy_path); + FixedClock clock(fixture.now); + auto guard_result = CreateGuard(fixture.registry, clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, fixture.uri_by_role); + auto* guard = std::get_if(&guard_result); + Check(guard != nullptr, "adapter_replica_guard_create"); + if (guard == nullptr) return; + auto prepared_result = guard->ValidateBeforeCall(); + auto* prepared = std::get_if(&prepared_result); + Check(prepared != nullptr, "pre_call_valid"); + if (prepared == nullptr) return; + auto passed = guard->ValidateBeforeForward(*prepared); + Check(std::holds_alternative(passed), + "pre_forward_fresh_validation"); + + auto replica_authority = CreateGuard(fixture.registry, clock, + sec::ClientCallPurpose::ReplicaToAuthority, fixture.uri_by_role); + auto* internal_guard = std::get_if(&replica_authority); + Check(internal_guard != nullptr, "replica_authority_guard_create"); + if (internal_guard != nullptr) { + auto internal_prepared = internal_guard->ValidateBeforeCall(); + auto* token = std::get_if(&internal_prepared); + Check(token != nullptr, "replica_authority_prepared"); + if (token != nullptr) { + CheckFailure(guard->ValidateBeforeForward(*token), + sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::ForeignPreparedCall, + "cross_guard_prepared_proof_rejected"); + } + } + + // Equal IDs, purpose, and endpoints do not make independently loaded + // registry objects interchangeable; proof binding uses object identity. + std::vector leaf_views; + for (const auto& pem : fixture.leaf_pems) leaf_views.emplace_back(pem); + auto second_registry_result = sec::CertificateRegistryLoader::Load( + fixture.policy, fixture.root_pem, leaf_views, clock); + const auto* second_registry = std::get_if< + std::shared_ptr>(&second_registry_result); + Check(second_registry != nullptr, "same_policy_second_registry_loads"); + if (second_registry != nullptr) { + auto second_guard_result = CreateGuard(*second_registry, clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, fixture.uri_by_role); + auto* second_guard = std::get_if(&second_guard_result); + Check(second_guard != nullptr, "same_config_second_guard"); + if (second_guard != nullptr) { + auto second_prepared_result = second_guard->ValidateBeforeCall(); + const auto* second_prepared = std::get_if( + &second_prepared_result); + Check(second_prepared != nullptr, "same_config_second_proof"); + if (second_prepared != nullptr) { + CheckFailure(guard->ValidateBeforeForward(*second_prepared), + sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::ForeignPreparedCall, + "different_registry_same_config_proof_rejected"); + } + } + } + + auto wrong_server = sec::ClientCallGuard::Create(fixture.registry, clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, + fixture.uri_by_role.at(sec::PeerRole::kAdapter), + fixture.uri_by_role.at(sec::PeerRole::kAuthority)); + CheckFailure(wrong_server, sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::ServerRoleMismatch, + "wrong_endpoint_role_rejected"); + auto unknown_local = sec::ClientCallGuard::Create(fixture.registry, clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, + "spiffe://rateguard.invalid/adapter/missing", + fixture.uri_by_role.at(sec::PeerRole::kReplica)); + CheckFailure(unknown_local, sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::MissingClientCertificate, + "unknown_local_identity_rejected"); + +} + +void TestProofOwnsRegistry(const std::string& policy_path) { + Fixture fixture(policy_path); + FixedClock clock(fixture.now); + auto owned_registry = fixture.registry; + std::weak_ptr weak_registry = owned_registry; + std::optional retained; + { + auto lifetime_guard = CreateGuard(owned_registry, clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, fixture.uri_by_role); + auto* lifetime_guard_ptr = std::get_if(&lifetime_guard); + Check(lifetime_guard_ptr != nullptr, "lifetime_guard_create"); + if (lifetime_guard_ptr != nullptr) { + auto result = lifetime_guard_ptr->ValidateBeforeCall(); + const auto* value = std::get_if(&result); + Check(value != nullptr, "lifetime_token_create"); + if (value != nullptr) retained.emplace(*value); + } + } + owned_registry.reset(); + fixture.registry.reset(); + Check(retained.has_value() && !weak_registry.expired(), + "prepared_token_owns_immutable_registry"); + retained.reset(); + Check(weak_registry.expired(), "registry_released_after_proof_release"); +} + +void TestClockFailuresAndFreshness(const std::string& policy_path) { + Fixture fixture(policy_path); + FixedClock clock(fixture.now); + auto guard_result = CreateGuard(fixture.registry, clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, fixture.uri_by_role); + auto* guard = std::get_if(&guard_result); + Check(guard != nullptr, "clock_guard_create"); + if (guard == nullptr) return; + auto prepared_result = guard->ValidateBeforeCall(); + const auto* prepared = std::get_if(&prepared_result); + Check(prepared != nullptr, "clock_prepared"); + if (prepared == nullptr) return; + + clock.Set({fixture.now.unix_seconds - 1, 999'999'999U}); + CheckFailure(guard->ValidateBeforeForward(*prepared), + sec::ClientGuardDisposition::ApplicationUnavailable, + sec::ClientGuardFailureReason::ClockUntrusted, + "pre_forward_rejects_time_before_pre_call_sample"); + clock.Set(fixture.now); + + clock.SetUnhealthyValue(); + const auto calls_before = clock.calls; + CheckFailure(guard->ValidateBeforeForward(*prepared), + sec::ClientGuardDisposition::ApplicationUnavailable, + sec::ClientGuardFailureReason::ClockUntrusted, + "pre_unhealthy_clock_rejected"); + Check(clock.calls == calls_before, "unhealthy_clock_checked_before_now"); + + FixedClock post_failure_clock(fixture.now); + auto post_guard_result = CreateGuard(fixture.registry, post_failure_clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, fixture.uri_by_role); + auto* post_guard = std::get_if(&post_guard_result); + if (post_guard == nullptr) Fail("post_failure_guard_create"); + const auto initial_post_result = post_guard->ValidateBeforeCall(); + Check(std::holds_alternative(initial_post_result), + "pre_failure_sample_valid"); + post_failure_clock.FailAfterSample(); + CheckFailure(post_guard->ValidateBeforeCall(), + sec::ClientGuardDisposition::ApplicationUnavailable, + sec::ClientGuardFailureReason::ClockUntrusted, + "post_sample_unhealthy_clock_rejected"); +} + +void TestExpiryBoundaries(const std::string& policy_path) { + // The local leaf has a later notBefore than the server leaf and an earlier + // notAfter, allowing both sides of its half-open interval to be isolated. + Fixture local_fixture(policy_path, { + {sec::PeerRole::kAdapter, {-30, 3600}}, + {sec::PeerRole::kReplica, {-60, 7200}}}); + FixedClock local_clock(local_fixture.now); + auto local_guard_result = CreateGuard(local_fixture.registry, local_clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, local_fixture.uri_by_role); + auto* local_guard = std::get_if(&local_guard_result); + Check(local_guard != nullptr, "local_boundary_guard"); + if (local_guard != nullptr) { + auto local_prepared_result = local_guard->ValidateBeforeCall(); + const auto* local_prepared_value = std::get_if( + &local_prepared_result); + Check(local_prepared_value != nullptr, "local_prepared_before_expiry"); + std::optional local_prepared; + if (local_prepared_value != nullptr) local_prepared.emplace(*local_prepared_value); + const auto local_before = local_fixture.not_before_by_role.at(sec::PeerRole::kAdapter); + local_clock.Set(JustBefore(local_before)); + CheckFailure(local_guard->ValidateBeforeCall(), + sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::ClientNotYetValid, + "local_before_not_before_rejected"); + local_clock.Set(local_before); + Check(std::holds_alternative( + local_guard->ValidateBeforeCall()), "local_exact_not_before_allowed"); + + const auto local_after = local_fixture.not_after_by_role.at(sec::PeerRole::kAdapter); + local_clock.Set(JustBefore(local_after)); + Check(std::holds_alternative( + local_guard->ValidateBeforeCall()), "local_before_not_after_allowed"); + local_clock.Set(local_after); + CheckFailure(local_guard->ValidateBeforeCall(), + sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::ClientExpired, + "local_exact_not_after_rejected"); + if (local_prepared) { + CheckFailure(local_guard->ValidateBeforeForward(*local_prepared), + sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::ClientExpired, + "pre_forward_rechecks_local_expiry"); + } + } + + // Reverse notBefore ordering to isolate the expected server certificate. + Fixture server_fixture(policy_path, { + {sec::PeerRole::kAdapter, {-60, 7200}}, + {sec::PeerRole::kReplica, {-30, 3600}}}); + FixedClock server_clock(server_fixture.now); + auto server_guard_result = CreateGuard(server_fixture.registry, server_clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, server_fixture.uri_by_role); + auto* server_guard = std::get_if(&server_guard_result); + Check(server_guard != nullptr, "server_boundary_guard"); + if (server_guard != nullptr) { + const auto server_before = server_fixture.not_before_by_role.at(sec::PeerRole::kReplica); + server_clock.Set(JustBefore(server_before)); + CheckFailure(server_guard->ValidateBeforeCall(), + sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::ServerNotYetValid, + "server_before_not_before_rejected"); + server_clock.Set(server_before); + Check(std::holds_alternative( + server_guard->ValidateBeforeCall()), "server_exact_not_before_allowed"); + + const auto server_after = server_fixture.not_after_by_role.at(sec::PeerRole::kReplica); + server_clock.Set(JustBefore(server_after)); + Check(std::holds_alternative( + server_guard->ValidateBeforeCall()), "server_before_not_after_allowed"); + server_clock.Set(server_after); + CheckFailure(server_guard->ValidateBeforeCall(), + sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::ServerExpired, + "server_exact_not_after_rejected"); + } + + Fixture root_fixture(policy_path); + FixedClock root_clock(root_fixture.now); + auto root_guard_result = CreateGuard(root_fixture.registry, root_clock, + sec::ClientCallPurpose::AdapterToReplicaAdmission, root_fixture.uri_by_role); + auto* root_guard = std::get_if(&root_guard_result); + Check(root_guard != nullptr, "root_boundary_guard"); + if (root_guard != nullptr) { + const auto root_after = root_fixture.registry->root_validity().not_after; + root_clock.Set(JustBefore(root_after)); + Check(std::holds_alternative( + root_guard->ValidateBeforeCall()), "root_before_not_after_allowed"); + root_clock.Set(root_after); + CheckFailure(root_guard->ValidateBeforeCall(), + sec::ClientGuardDisposition::CredentialInvalid, + sec::ClientGuardFailureReason::RootExpired, + "root_exact_not_after_rejected"); + } +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) Fail("usage: client_call_guard_test policy_fixture.json"); + TestHappyPathAndBindings(argv[1]); + TestClockFailuresAndFreshness(argv[1]); + TestProofOwnsRegistry(argv[1]); + TestExpiryBoundaries(argv[1]); + std::cout << "PASS client_call_guard_registry_time" << '\n'; + return 0; +} diff --git a/tests/security/ephemeral_pki.cpp b/tests/security/ephemeral_pki.cpp new file mode 100644 index 0000000..6d9731f --- /dev/null +++ b/tests/security/ephemeral_pki.cpp @@ -0,0 +1,208 @@ +#include "ephemeral_pki.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::security::test { +namespace { +template +using OsslPtr = std::unique_ptr; +using Pkey = OsslPtr; +using X509Ptr = OsslPtr; +using Bio = std::unique_ptr; + +Pkey GenerateKey() { + EVP_PKEY_CTX* raw = EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr); + if (!raw) throw std::runtime_error("EC key context unavailable"); + std::unique_ptr ctx(raw, EVP_PKEY_CTX_free); + char group[] = "prime256v1"; + OSSL_PARAM params[] = {OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, group, 0), OSSL_PARAM_construct_end()}; + if (EVP_PKEY_keygen_init(ctx.get()) <= 0 || EVP_PKEY_CTX_set_params(ctx.get(), params) <= 0) + throw std::runtime_error("EC P-256 setup failed"); + EVP_PKEY* key = nullptr; + if (EVP_PKEY_generate(ctx.get(), &key) <= 0 || key == nullptr) + throw std::runtime_error("EC P-256 generation failed"); + return Pkey(key, EVP_PKEY_free); +} + +void AddExtension(X509* cert, X509* issuer, int nid, const char* value) { + X509V3_CTX context{}; + X509V3_set_ctx(&context, issuer, cert, nullptr, nullptr, 0); + X509_EXTENSION* raw = X509V3_EXT_conf_nid(nullptr, &context, nid, const_cast(value)); + if (!raw) throw std::runtime_error("certificate extension construction failed"); + std::unique_ptr ext(raw, X509_EXTENSION_free); + if (X509_add_ext(cert, ext.get(), -1) != 1) throw std::runtime_error("certificate extension append failed"); +} + +X509Ptr MakeCert(EVP_PKEY* key, const std::string& uri, PeerRole role, + X509* issuer, EVP_PKEY* issuer_key, long serial, bool is_ca, + long not_before_delta = -60, long not_after_delta = 24 * 60 * 60, + const std::string* explicit_san = nullptr) { + X509* raw = X509_new(); + if (!raw) throw std::runtime_error("X509_new failed"); + X509Ptr cert(raw, X509_free); + X509_set_version(cert.get(), 2); + ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), serial); + X509_gmtime_adj(X509_getm_notBefore(cert.get()), not_before_delta); + X509_gmtime_adj(X509_getm_notAfter(cert.get()), not_after_delta); + X509_set_pubkey(cert.get(), key); + X509_NAME* name = X509_get_subject_name(cert.get()); + const char* common_name = is_ca ? "RateGuard test root CA" : "RateGuard test leaf"; + X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, + reinterpret_cast(common_name), -1, -1, 0); + X509_set_issuer_name(cert.get(), issuer ? X509_get_subject_name(issuer) : name); + if (is_ca) { + AddExtension(cert.get(), cert.get(), NID_basic_constraints, "critical,CA:TRUE,pathlen:0"); + AddExtension(cert.get(), cert.get(), NID_key_usage, "critical,keyCertSign,cRLSign"); + AddExtension(cert.get(), cert.get(), NID_subject_key_identifier, "hash"); + AddExtension(cert.get(), cert.get(), NID_authority_key_identifier, "keyid:always"); + } else { + AddExtension(cert.get(), issuer, NID_basic_constraints, "critical,CA:FALSE"); + AddExtension(cert.get(), issuer, NID_key_usage, "critical,digitalSignature"); + AddExtension(cert.get(), issuer, NID_subject_key_identifier, "hash"); + AddExtension(cert.get(), issuer, NID_authority_key_identifier, "keyid:always"); + const char* eku = role == PeerRole::kReplica ? "clientAuth,serverAuth" : + role == PeerRole::kAdapter ? "clientAuth" : "serverAuth"; + AddExtension(cert.get(), issuer, NID_ext_key_usage, eku); + const std::string san = explicit_san ? *explicit_san : "URI:" + uri; + AddExtension(cert.get(), issuer, NID_subject_alt_name, san.c_str()); + } + if (X509_sign(cert.get(), issuer_key ? issuer_key : key, EVP_sha256()) <= 0) + throw std::runtime_error("X509_sign failed"); + return cert; +} + +std::string CertPem(X509* cert) { + Bio bio(BIO_new(BIO_s_mem()), BIO_free); + if (!bio || PEM_write_bio_X509(bio.get(), cert) != 1) throw std::runtime_error("certificate PEM encoding failed"); + char* data = nullptr; + const long size = BIO_get_mem_data(bio.get(), &data); + if (size <= 0 || data == nullptr) throw std::runtime_error("certificate PEM extraction failed"); + return std::string(data, static_cast(size)); +} + +std::string KeyPem(EVP_PKEY* key) { + Bio bio(BIO_new(BIO_s_mem()), BIO_free); + if (!bio || PEM_write_bio_PrivateKey(bio.get(), key, nullptr, nullptr, 0, nullptr, nullptr) != 1) + throw std::runtime_error("private key in-memory encoding failed"); + char* data = nullptr; + const long size = BIO_get_mem_data(bio.get(), &data); + if (size <= 0 || data == nullptr) throw std::runtime_error("private key PEM extraction failed"); + return std::string(data, static_cast(size)); +} + +Sha256Digest DigestDer(X509* cert) { + const int n = i2d_X509(cert, nullptr); + if (n <= 0 || n > 64 * 1024) throw std::runtime_error("DER encoding failed"); + std::string der(static_cast(n), '\0'); + unsigned char* p = reinterpret_cast(der.data()); + if (i2d_X509(cert, &p) != n) throw std::runtime_error("DER encoding failed"); + Sha256Digest digest{}; + unsigned int size = 0; + if (EVP_Digest(der.data(), der.size(), digest.data(), &size, EVP_sha256(), nullptr) != 1 || size != digest.size()) + throw std::runtime_error("SHA-256 unavailable"); + return digest; +} +} // namespace + +struct EphemeralPki::Impl { + Pkey root_key{nullptr, EVP_PKEY_free}; + X509Ptr root_cert{nullptr, X509_free}; + std::string root_pem; + long serial = 1; + std::vector> identities; +}; + +EphemeralPki::EphemeralPki() : impl_(new Impl) { + impl_->root_key = GenerateKey(); + impl_->root_cert = MakeCert(impl_->root_key.get(), "", PeerRole::kAuthority, + nullptr, nullptr, impl_->serial++, true); + impl_->root_pem = CertPem(impl_->root_cert.get()); +} +EphemeralPki::~EphemeralPki() { delete impl_; } +const std::string& EphemeralPki::root_certificate_pem() const { return impl_->root_pem; } + +bool EphemeralPki::VerifyChain(const EphemeralIdentity& identity, + bool server_purpose, int* error_code) const { + if (error_code) *error_code = X509_V_ERR_UNSPECIFIED; + Bio root_bio(BIO_new_mem_buf(impl_->root_pem.data(), + static_cast(impl_->root_pem.size())), BIO_free); + Bio leaf_bio(BIO_new_mem_buf(identity.certificate_pem.data(), + static_cast(identity.certificate_pem.size())), BIO_free); + if (!root_bio || !leaf_bio) return false; + X509* root_raw = PEM_read_bio_X509(root_bio.get(), nullptr, nullptr, nullptr); + X509* leaf_raw = PEM_read_bio_X509(leaf_bio.get(), nullptr, nullptr, nullptr); + X509Ptr root(root_raw, X509_free); + X509Ptr leaf(leaf_raw, X509_free); + if (!root || !leaf) return false; + X509_STORE* store_raw = X509_STORE_new(); + if (!store_raw) return false; + std::unique_ptr store(store_raw, X509_STORE_free); + if (X509_STORE_add_cert(store.get(), root.get()) != 1) return false; + X509_STORE_CTX* context_raw = X509_STORE_CTX_new(); + if (!context_raw) return false; + std::unique_ptr context( + context_raw, X509_STORE_CTX_free); + if (X509_STORE_CTX_init(context.get(), store.get(), leaf.get(), nullptr) != 1) + return false; + const int purpose = server_purpose ? X509_PURPOSE_SSL_SERVER : X509_PURPOSE_SSL_CLIENT; + if (X509_STORE_CTX_set_purpose(context.get(), purpose) != 1) return false; + const int verified = X509_verify_cert(context.get()); + if (error_code) *error_code = X509_STORE_CTX_get_error(context.get()); + return verified == 1; +} + +const EphemeralIdentity& EphemeralPki::Issue(PeerRole role, std::string uri) { + return IssueWithValidity(role, std::move(uri), -60, 24 * 60 * 60); +} + +const EphemeralIdentity& EphemeralPki::IssueWithValidity( + PeerRole role, std::string uri, long not_before_seconds_from_now, + long not_after_seconds_from_now) { + Pkey key = GenerateKey(); + X509Ptr cert = MakeCert(key.get(), uri, role, impl_->root_cert.get(), impl_->root_key.get(), + impl_->serial++, false, not_before_seconds_from_now, + not_after_seconds_from_now); + auto identity = std::make_unique(); + identity->registered.uri = std::move(uri); + identity->registered.role = role; + identity->registered.leaf_der_sha256 = DigestDer(cert.get()); + identity->certificate_pem = CertPem(cert.get()); + identity->private_key_pem = KeyPem(key.get()); + impl_->identities.push_back(std::move(identity)); + return *impl_->identities.back(); +} + +const EphemeralIdentity& EphemeralPki::IssueWithUriSans( + PeerRole role, std::vector uri_sans) { + if (uri_sans.empty()) throw std::runtime_error("URI SAN fixture must not be empty"); + std::string san; + for (const auto& uri : uri_sans) { + if (!san.empty()) san += ","; + san += "URI:" + uri; + } + Pkey key = GenerateKey(); + X509Ptr cert = MakeCert(key.get(), uri_sans.front(), role, impl_->root_cert.get(), + impl_->root_key.get(), impl_->serial++, false, -60, + 24 * 60 * 60, &san); + auto identity = std::make_unique(); + identity->registered.uri = uri_sans.front(); + identity->registered.role = role; + identity->registered.leaf_der_sha256 = DigestDer(cert.get()); + identity->certificate_pem = CertPem(cert.get()); + identity->private_key_pem = KeyPem(key.get()); + impl_->identities.push_back(std::move(identity)); + return *impl_->identities.back(); +} + +} // namespace rateguard::security::test diff --git a/tests/security/ephemeral_pki.h b/tests/security/ephemeral_pki.h new file mode 100644 index 0000000..676500b --- /dev/null +++ b/tests/security/ephemeral_pki.h @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +#include "rateguard/security/peer_identity.h" + +namespace rateguard::security::test { + +struct EphemeralIdentity final { + RegisteredPeer registered; + std::string certificate_pem; + std::string private_key_pem; +}; + +// Test-only authority and identities. All keys are generated in memory; callers +// must never print or serialize private_key_pem/certificate_pem. +class EphemeralPki final { + public: + EphemeralPki(); + ~EphemeralPki(); + EphemeralPki(const EphemeralPki&) = delete; + EphemeralPki& operator=(const EphemeralPki&) = delete; + + const std::string& root_certificate_pem() const; + const EphemeralIdentity& Issue(PeerRole role, std::string uri); + bool VerifyChain(const EphemeralIdentity& identity, bool server_purpose, + int* error_code) const; + const EphemeralIdentity& IssueWithValidity(PeerRole role, std::string uri, + long not_before_seconds_from_now, + long not_after_seconds_from_now); + const EphemeralIdentity& IssueWithUriSans(PeerRole role, + std::vector uri_sans); + + private: + struct Impl; + Impl* impl_; +}; + +} // namespace rateguard::security::test diff --git a/tests/security/mtls_probe_test.cpp b/tests/security/mtls_probe_test.cpp new file mode 100644 index 0000000..1789553 --- /dev/null +++ b/tests/security/mtls_probe_test.cpp @@ -0,0 +1,205 @@ +#include "ephemeral_pki.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "proto/rateguard/v1/admission.grpc.pb.h" +#include "rateguard/security/tls_certificate_verifier.h" + +namespace sec = rateguard::security; +namespace rg = rateguard::v1; +using grpc::experimental::IdentityKeyCertPair; +using grpc::experimental::StaticDataCertificateProvider; + +namespace { +class ProbeService final : public rg::AdmissionService::Service { + public: + grpc::Status CheckAdmission(grpc::ServerContext*, const rg::CheckAdmissionRequest*, + rg::AdmissionDecision* response) override { + ++calls; + response->set_outcome(rg::DECISION_OUTCOME_ALLOW); + return grpc::Status::OK; + } + std::atomic calls{0}; +}; + +struct RunResult { grpc::Status status; unsigned calls; }; + +std::shared_ptr Provider( + const std::string& root, const sec::test::EphemeralIdentity* identity) { + std::vector pairs; + if (identity) pairs.push_back({identity->private_key_pem, identity->certificate_pem}); + return std::make_shared(root, pairs); +} + +std::shared_ptr ClientCredentials( + const std::string& trusted_root, + const sec::test::EphemeralIdentity* client_identity, + std::shared_ptr registry, + sec::ExpectedPeer expected) { + grpc::experimental::TlsChannelCredentialsOptions options; + options.set_certificate_provider(Provider(trusted_root, client_identity)); + options.watch_root_certs(); + if (client_identity) { + options.watch_identity_key_cert_pairs(); + } + options.set_verify_server_certs(true); + options.set_check_call_host(false); + options.set_certificate_verifier( + grpc::experimental::ExternalCertificateVerifier::Create( + std::move(registry), std::move(expected))); + return grpc::experimental::TlsCredentials(options); +} + +RunResult Invoke(const std::string& server_root, + const sec::test::EphemeralIdentity& server_identity, + const std::vector& server_registry_records, + std::shared_ptr client_credentials, + unsigned rpc_count = 1) { + ProbeService service; + grpc::experimental::TlsServerCredentialsOptions server_options( + Provider(server_root, &server_identity)); + server_options.watch_root_certs(); + server_options.watch_identity_key_cert_pairs(); + server_options.set_cert_request_type(GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); + server_options.set_certificate_verifier( + grpc::experimental::ExternalCertificateVerifier::Create( + std::make_shared(server_registry_records))); + auto server_credentials = grpc::experimental::TlsServerCredentials(server_options); + int port = 0; + grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", server_credentials, &port); + builder.RegisterService(&service); + auto server = builder.BuildAndStart(); + if (!server || port <= 0) return {grpc::Status(grpc::StatusCode::UNAVAILABLE, "probe server failed"), service.calls.load()}; + + auto channel = grpc::CreateChannel("127.0.0.1:" + std::to_string(port), client_credentials); + auto stub = rg::AdmissionService::NewStub(channel); + rg::CheckAdmissionRequest request; + request.set_tenant_id("probe"); + request.set_operation_id("read"); + request.set_attempt_id(std::string(16, '\x01')); + request.set_epoch_id(std::string(16, '\x02')); + request.set_policy_digest(std::string(32, '\x03')); + grpc::Status status; + for (unsigned i = 0; i < rpc_count; ++i) { + rg::AdmissionDecision response; + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3)); + status = stub->CheckAdmission(&context, request, &response); + if (!status.ok()) break; + } + const unsigned calls = service.calls.load(); + channel.reset(); + server->Shutdown(); + return {status, calls}; +} + +bool Scenario(const char* name, bool expected_ok, const RunResult& result, + unsigned expected_calls = 1) { + const bool ok = result.status.ok() == expected_ok && + result.calls == (expected_ok ? expected_calls : 0); + std::cout << name << ": " << (ok ? "PASS" : "FAIL") << " rpc=" + << (result.status.ok() ? "OK" : "REJECTED") << " handler_calls=" << result.calls << '\n'; + return ok; +} +} // namespace + +int main() { + try { + sec::test::EphemeralPki pki; + const auto& server = pki.Issue(sec::PeerRole::kReplica, + "spiffe://rateguard.local/replica/1/0102030405060708090a0b0c0d0e0f10"); + const auto& client = pki.Issue(sec::PeerRole::kAdapter, "spiffe://rateguard.local/adapter/probe"); + const auto& bad_uri = pki.Issue(sec::PeerRole::kAdapter, "spiffe://rateguard.local/adapter/unregistered"); + const auto& second_client = pki.Issue(sec::PeerRole::kAdapter, client.registered.uri); + const auto& wrong_eku = pki.Issue(sec::PeerRole::kAuthority, + "spiffe://rateguard.local/authority/030405060708090a0b0c0d0e0f101112"); + const auto& expired_client = pki.IssueWithValidity(sec::PeerRole::kAdapter, + "spiffe://rateguard.local/adapter/expired", -7200, -3600); + const auto& future_client = pki.IssueWithValidity(sec::PeerRole::kAdapter, + "spiffe://rateguard.local/adapter/future", 3600, 7200); + const auto& multi_uri_client = pki.IssueWithUriSans(sec::PeerRole::kAdapter, + {"spiffe://rateguard.local/adapter/probe", "spiffe://rateguard.local/adapter/other"}); + const auto& wrong_server_uri = pki.Issue(sec::PeerRole::kReplica, + "spiffe://rateguard.local/replica/9/0909090a0b0c0d0e0f10111213141516"); + const auto& second_server = pki.Issue(sec::PeerRole::kReplica, server.registered.uri); + sec::test::EphemeralPki foreign_pki; + const auto& unknown_ca_client = foreign_pki.Issue(sec::PeerRole::kAdapter, "spiffe://rateguard.local/adapter/probe"); + const auto& unknown_ca_server = foreign_pki.Issue(sec::PeerRole::kReplica, + "spiffe://rateguard.local/replica/1/0102030405060708090a0b0c0d0e0f10"); + + int server_purpose_error = 0; + int client_purpose_error = 0; + const bool valid_server_chain = pki.VerifyChain(server, true, &server_purpose_error); + const bool valid_client_chain = pki.VerifyChain(client, false, &client_purpose_error); + if (!valid_server_chain || !valid_client_chain) { + // Numeric OpenSSL verification codes only; never print certificates, + // private keys, or raw OpenSSL error strings. + std::cerr << "PKI_PREFLIGHT_FAIL server_error=" << server_purpose_error + << " client_error=" << client_purpose_error << '\n'; + return 3; + } + + auto client_registry = std::make_shared( + std::vector{server.registered}); + const sec::ExpectedPeer expected_server{server.registered.uri, server.registered.leaf_der_sha256, + server.registered.role}; + auto server_registry_for = [](const sec::test::EphemeralIdentity& peer) { + return std::vector{peer.registered}; + }; + int fails = 0; + auto run = [&](const char* name, const sec::test::EphemeralIdentity* presented, + std::vector allowlist, bool expect_ok, + const std::string& trusted_root = std::string{}) { + const auto& root = trusted_root.empty() ? pki.root_certificate_pem() : trusted_root; + auto creds = ClientCredentials(root, presented, client_registry, expected_server); + if (!Scenario(name, expect_ok, Invoke(pki.root_certificate_pem(), server, + allowlist, std::move(creds)))) ++fails; + }; + run("valid", &client, server_registry_for(client), true); + run("wrong_uri", &bad_uri, server_registry_for(client), false); + // The server allowlist has the expected URI and expected digest, while the + // presented leaf has the same URI but a different DER digest. + run("same_uri_wrong_leaf_pin", &second_client, server_registry_for(client), false); + run("wrong_eku", &wrong_eku, server_registry_for(wrong_eku), false); + run("unknown_ca", &unknown_ca_client, server_registry_for(client), false); + run("missing_client_certificate", nullptr, server_registry_for(client), false); + run("expired_client_leaf", &expired_client, server_registry_for(expired_client), false); + run("not_yet_valid_client_leaf", &future_client, server_registry_for(future_client), false); + run("multiple_uri_sans", &multi_uri_client, server_registry_for(multi_uri_client), false); + + auto expected_client_creds = [&](sec::ExpectedPeer expected) { + return ClientCredentials(pki.root_certificate_pem(), &client, client_registry, + std::move(expected)); + }; + auto server_pin_case = [&](const char* name, const sec::test::EphemeralIdentity& presented_server, + bool expect_ok) { + const auto result = Invoke(pki.root_certificate_pem(), presented_server, + server_registry_for(client), expected_client_creds(expected_server)); + if (!Scenario(name, expect_ok, result)) ++fails; + }; + server_pin_case("wrong_server_uri", wrong_server_uri, false); + server_pin_case("same_uri_wrong_server_leaf_pin", second_server, false); + server_pin_case("unknown_server_ca", unknown_ca_server, false); + const auto reused = Invoke(pki.root_certificate_pem(), server, + server_registry_for(client), expected_client_creds(expected_server), 2); + if (!Scenario("reused_channel_two_rpcs", true, reused, 2)) ++fails; + return fails == 0 ? 0 : 1; + } catch (const std::exception&) { + // Do not print OpenSSL errors or credential material; they can contain + // peer-controlled strings in future implementations. + std::cerr << "mTLS probe setup failed\n"; + return 2; + } +} diff --git a/tests/security/peer_authenticator_test.cpp b/tests/security/peer_authenticator_test.cpp new file mode 100644 index 0000000..2d47fac --- /dev/null +++ b/tests/security/peer_authenticator_test.cpp @@ -0,0 +1,394 @@ +#include "ephemeral_pki.h" +#include "rateguard/security/peer_authenticator.h" + +#include "policy/canonical_codec.h" +#include "policy/policy_loader.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; + +namespace { + +static_assert(std::is_copy_constructible_v); +static_assert(std::is_nothrow_copy_assignable_v); +// Rvalue construction remains possible through the copy constructor; no +// implicit move operation may transfer the registry owner away. +static_assert(std::is_move_constructible_v); + +int failures = 0; + +void Check(bool condition, std::string_view label) { + if (!condition) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} + +class EmptyAuthPropertyIterator final : public grpc::AuthPropertyIterator { + public: + EmptyAuthPropertyIterator() : grpc::AuthPropertyIterator() {} +}; + +class TestAuthContext final : public grpc::AuthContext { + public: + explicit TestAuthContext(bool authenticated = true) : authenticated_(authenticated) {} + + void Add(std::string name, std::string value) { + properties_.emplace_back(std::move(name), std::move(value)); + } + bool IsPeerAuthenticated() const override { return authenticated_; } + std::vector GetPeerIdentity() const override { + return FindPropertyValues(GRPC_PEER_URI_PROPERTY_NAME); + } + std::string GetPeerIdentityPropertyName() const override { + return GRPC_PEER_URI_PROPERTY_NAME; + } + std::vector FindPropertyValues( + const std::string& name) const override { + std::vector values; + for (const auto& property : properties_) { + if (property.first == name) values.emplace_back(property.second.data(), property.second.size()); + } + return values; + } + grpc::AuthPropertyIterator begin() const override { + return EmptyAuthPropertyIterator{}; + } + grpc::AuthPropertyIterator end() const override { + return EmptyAuthPropertyIterator{}; + } + void AddProperty(const std::string&, const grpc::string_ref&) override {} + bool SetPeerIdentityPropertyName(const std::string&) override { return false; } + + private: + bool authenticated_; + std::vector> properties_; +}; + +class TestClock final : public sec::ITrustedWallClock { + public: + explicit TestClock(sec::WallTime time, bool healthy = true) + : time_(time), healthy_(healthy) {} + sec::TrustedWallClockResult Now() override { + ++calls; + if (!healthy_) { + return sec::TrustedWallClockFailure{ + sec::TrustedWallClockFailureReason::PlatformUnavailable}; + } + return time_; + } + bool Healthy() const override { return healthy_; } + void Set(sec::WallTime time) { time_ = time; } + void SetHealthy(bool healthy) { healthy_ = healthy; } + unsigned calls{}; + + private: + sec::WallTime time_; + bool healthy_; +}; + +std::string ReadFile(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) return {}; + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +std::string Hex(const std::uint8_t* data, std::size_t size) { + constexpr char digits[] = "0123456789abcdef"; + std::string result(size * 2, '0'); + for (std::size_t i = 0; i < size; ++i) { + result[i * 2] = digits[data[i] >> 4]; + result[i * 2 + 1] = digits[data[i] & 0x0f]; + } + return result; +} + +bool RootDigest(std::string_view pem, pol::Digest32* digest) { + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (raw_bio == nullptr) return false; + std::unique_ptr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (raw_cert == nullptr) return false; + std::unique_ptr cert(raw_cert, X509_free); + const int length = i2d_X509(cert.get(), nullptr); + if (length <= 0 || length > 64 * 1024) return false; + std::vector der(static_cast(length)); + unsigned char* cursor = der.data(); + if (i2d_X509(cert.get(), &cursor) != length) return false; + unsigned int written = 0; + return EVP_Digest(der.data(), der.size(), digest->data(), &written, + EVP_sha256(), nullptr) == 1 && written == digest->size(); +} + +struct Fixture final { + sec::test::EphemeralPki pki; + std::shared_ptr policy; + std::shared_ptr registry; + const sec::test::EphemeralIdentity* adapter{}; + std::string error; + + explicit Fixture(const std::string& path) { + const std::string source = ReadFile(path); + if (source.empty()) { + error = "policy fixture unavailable"; + return; + } + pol::Digest32 root_hash{}; + if (!RootDigest(pki.root_certificate_pem(), &root_hash)) { + error = "root digest unavailable"; + return; + } + try { + auto json = nlohmann::json::parse(source); + json["trust_root_sha256"] = Hex(root_hash.data(), root_hash.size()); + auto loaded = pol::PolicyLoader::Load(json.dump()); + if (const auto* issue = std::get_if(&loaded)) { + error = issue->message; + return; + } + policy = std::get>(std::move(loaded)); + + std::vector identities; + std::vector leaves; + identities.reserve(policy->principals().size()); + leaves.reserve(policy->principals().size()); + for (const auto& principal : policy->principals()) { + sec::PeerRole role = sec::PeerRole::kAdapter; + switch (principal.role) { + case pol::PrincipalRole::Adapter: role = sec::PeerRole::kAdapter; break; + case pol::PrincipalRole::Replica: role = sec::PeerRole::kReplica; break; + case pol::PrincipalRole::Authority: role = sec::PeerRole::kAuthority; break; + } + const auto& identity = pki.IssueWithValidity(role, principal.uri, -60, 3600); + identities.push_back(&identity); + leaves.push_back(identity.certificate_pem); + if (principal.role == pol::PrincipalRole::Adapter && adapter == nullptr) { + adapter = &identity; + } + } + const auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + TestClock initial_clock({now, 0}); + auto built = sec::CertificateRegistryLoader::Load( + policy, pki.root_certificate_pem(), leaves, initial_clock); + if (const auto* issue = std::get_if(&built)) { + error = "certificate registry fixture rejected"; + (void)issue; + return; + } + registry = std::get>(std::move(built)); + } catch (const std::exception&) { + error = "fixture setup failed"; + } + } +}; + +TestAuthContext Context(std::string_view uri, std::string_view cert, + std::string_view transport = GRPC_TLS_TRANSPORT_SECURITY_TYPE) { + TestAuthContext context; + context.Add(GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, std::string(transport)); + context.Add(GRPC_PEER_URI_PROPERTY_NAME, std::string(uri)); + context.Add(GRPC_X509_PEM_CERT_PROPERTY_NAME, std::string(cert)); + return context; +} + +void TestAuthenticatedPrincipalAndLifetime(const std::string& path) { + Fixture fixture(path); + Check(fixture.registry != nullptr && fixture.adapter != nullptr, + "validated policy and adapter certificate fixture available"); + if (!fixture.registry || fixture.adapter == nullptr) return; + const auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + TestClock clock({now, 0}); + auto context = Context(fixture.adapter->registered.uri, + fixture.adapter->certificate_pem); + std::optional rvalue_constructed; + { + sec::PeerAuthenticator authenticator(fixture.registry, clock); + auto result = authenticator.Authenticate(context); + auto* proof = std::get_if(&result); + Check(proof != nullptr, "registered TLS URI and exact DER leaf pin authenticate"); + Check(clock.calls == 1, "each authentication obtains a fresh trusted clock sample"); + if (proof == nullptr) return; + Check(proof->uri() == fixture.adapter->registered.uri && + proof->role() == sec::PeerRole::kAdapter && + proof->registry().get() == fixture.registry.get(), + "opaque proof owns exact registry and resolved principal identity"); + rvalue_constructed.emplace(std::move(*proof)); + } + fixture.registry.reset(); + Check(rvalue_constructed && rvalue_constructed->registry() != nullptr && + rvalue_constructed->certificate() != nullptr && + rvalue_constructed->certificate()->peer.uri == rvalue_constructed->uri(), + "rvalue construction retains the proof after original variant and registry owners die"); +} + +void TestRejectedTransportIdentityAndPem(const std::string& path) { + Fixture fixture(path); + Check(fixture.registry != nullptr && fixture.adapter != nullptr, + "negative identity fixture available"); + if (!fixture.registry || fixture.adapter == nullptr) return; + const auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + TestClock clock({now, 0}); + sec::PeerAuthenticator authenticator(fixture.registry, clock); + const auto& id = *fixture.adapter; + + auto expect = [&](const TestAuthContext& context, sec::PeerAuthFailureReason reason, + sec::PeerAuthDisposition disposition, std::string_view label) { + auto result = authenticator.Authenticate(context); + const auto* failure = std::get_if(&result); + Check(failure && failure->reason == reason && failure->disposition == disposition, label); + }; + + TestAuthContext no_identity(false); + no_identity.Add(GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, GRPC_TLS_TRANSPORT_SECURITY_TYPE); + no_identity.Add(GRPC_PEER_URI_PROPERTY_NAME, id.registered.uri); + no_identity.Add(GRPC_X509_PEM_CERT_PROPERTY_NAME, id.certificate_pem); + expect(no_identity, sec::PeerAuthFailureReason::UnauthenticatedContext, + sec::PeerAuthDisposition::Unauthenticated, "unauthenticated auth context fails closed"); + + auto bad_transport = Context(id.registered.uri, id.certificate_pem, "ssl"); + expect(bad_transport, sec::PeerAuthFailureReason::UnsupportedTransport, + sec::PeerAuthDisposition::Unauthenticated, "wrong transport security type fails closed"); + + auto ambiguous_transport = Context(id.registered.uri, id.certificate_pem); + ambiguous_transport.Add(GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, + GRPC_TLS_TRANSPORT_SECURITY_TYPE); + expect(ambiguous_transport, sec::PeerAuthFailureReason::MissingOrAmbiguousTransport, + sec::PeerAuthDisposition::Unauthenticated, "multiple transport properties fail closed"); + + auto ambiguous_uri = Context(id.registered.uri, id.certificate_pem); + ambiguous_uri.Add(GRPC_PEER_URI_PROPERTY_NAME, id.registered.uri); + expect(ambiguous_uri, sec::PeerAuthFailureReason::MissingOrAmbiguousUri, + sec::PeerAuthDisposition::Unauthenticated, "multiple URI properties fail closed"); + + auto missing_cert = TestAuthContext{}; + missing_cert.Add(GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, GRPC_TLS_TRANSPORT_SECURITY_TYPE); + missing_cert.Add(GRPC_PEER_URI_PROPERTY_NAME, id.registered.uri); + expect(missing_cert, sec::PeerAuthFailureReason::MissingOrAmbiguousLeaf, + sec::PeerAuthDisposition::Unauthenticated, "missing leaf property fails closed"); + + auto ambiguous_leaf = Context(id.registered.uri, id.certificate_pem); + ambiguous_leaf.Add(GRPC_X509_PEM_CERT_PROPERTY_NAME, id.certificate_pem); + expect(ambiguous_leaf, sec::PeerAuthFailureReason::MissingOrAmbiguousLeaf, + sec::PeerAuthDisposition::Unauthenticated, "multiple leaf properties fail closed"); + + const auto& changed_pin = fixture.pki.Issue(sec::PeerRole::kAdapter, + id.registered.uri); + auto pin_mismatch = Context(id.registered.uri, changed_pin.certificate_pem); + expect(pin_mismatch, sec::PeerAuthFailureReason::LeafPinMismatch, + sec::PeerAuthDisposition::Unauthenticated, "same URI with different leaf DER fails pin check"); + + auto unknown_uri = Context("spiffe://rateguard.local/adapter/unknown", id.certificate_pem); + expect(unknown_uri, sec::PeerAuthFailureReason::UnregisteredUri, + sec::PeerAuthDisposition::Unauthenticated, "unregistered URI fails closed"); + + std::string prefixed = "prefix" + id.certificate_pem; + auto prefix_ctx = Context(id.registered.uri, prefixed); + expect(prefix_ctx, sec::PeerAuthFailureReason::InvalidLeafPem, + sec::PeerAuthDisposition::Unauthenticated, "nonwhitespace PEM prefix rejected"); + + std::string multiple_certs = id.certificate_pem + id.certificate_pem; + auto multi_ctx = Context(id.registered.uri, multiple_certs); + expect(multi_ctx, sec::PeerAuthFailureReason::InvalidLeafPem, + sec::PeerAuthDisposition::Unauthenticated, "additional PEM certificate rejected"); + + std::string nul_uri = id.registered.uri; + nul_uri.push_back('\0'); + auto nul_ctx = Context(nul_uri, id.certificate_pem); + expect(nul_ctx, sec::PeerAuthFailureReason::InvalidUri, + sec::PeerAuthDisposition::Unauthenticated, "embedded NUL in URI rejected"); + + std::string non_ascii_uri = id.registered.uri; + non_ascii_uri.append("\xc3\xa9", 2); + auto non_ascii_ctx = Context(non_ascii_uri, id.certificate_pem); + expect(non_ascii_ctx, sec::PeerAuthFailureReason::InvalidUri, + sec::PeerAuthDisposition::Unauthenticated, "non-ASCII URI bytes rejected"); + + std::string nul_pem = id.certificate_pem; + nul_pem.push_back('\0'); + auto nul_pem_ctx = Context(id.registered.uri, nul_pem); + expect(nul_pem_ctx, sec::PeerAuthFailureReason::InvalidLeafPem, + sec::PeerAuthDisposition::Unauthenticated, "embedded NUL in PEM rejected"); + + auto oversized_ctx = Context(id.registered.uri, + std::string(sec::CertificateRegistry::kMaxCertificatePemBytes + 1, 'x')); + expect(oversized_ctx, sec::PeerAuthFailureReason::OversizedLeaf, + sec::PeerAuthDisposition::Unauthenticated, "oversized leaf metadata fails closed"); +} + +void TestFreshValidityAndClockFailures(const std::string& path) { + Fixture fixture(path); + Check(fixture.registry != nullptr && fixture.adapter != nullptr, + "validity fixture available"); + if (!fixture.registry || fixture.adapter == nullptr) return; + auto context = Context(fixture.adapter->registered.uri, + fixture.adapter->certificate_pem); + const auto* record = fixture.registry->Find(fixture.adapter->registered.uri); + Check(record != nullptr, "adapter record in immutable registry"); + if (record == nullptr) return; + + TestClock expired_clock(record->validity.not_after); + sec::PeerAuthenticator expired_auth(fixture.registry, expired_clock); + auto expired = expired_auth.Authenticate(context); + const auto* expired_error = std::get_if(&expired); + Check(expired_error && expired_error->reason == sec::PeerAuthFailureReason::CertificateExpired && + expired_error->disposition == sec::PeerAuthDisposition::Unauthenticated, + "leaf notAfter is exclusive on a fresh authentication"); + + TestClock unhealthy(record->validity.not_before, false); + sec::PeerAuthenticator unhealthy_auth(fixture.registry, unhealthy); + auto unavailable = unhealthy_auth.Authenticate(context); + const auto* unavailable_error = std::get_if(&unavailable); + Check(unavailable_error && unavailable_error->reason == sec::PeerAuthFailureReason::ClockUntrusted && + unavailable_error->disposition == sec::PeerAuthDisposition::ApplicationUnavailable, + "untrusted wall clock yields application-unavailable disposition"); + + TestClock malformed({record->validity.not_before.unix_seconds, 1'000'000'000U}); + sec::PeerAuthenticator malformed_auth(fixture.registry, malformed); + auto malformed_result = malformed_auth.Authenticate(context); + const auto* malformed_error = std::get_if(&malformed_result); + Check(malformed_error && malformed_error->reason == sec::PeerAuthFailureReason::ClockUntrusted && + malformed_error->disposition == sec::PeerAuthDisposition::ApplicationUnavailable, + "invalid trusted-wall-clock tuple fails closed"); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::cerr << "usage: peer_authenticator_test \n"; + return 2; + } + TestAuthenticatedPrincipalAndLifetime(argv[1]); + TestRejectedTransportIdentityAndPem(argv[1]); + TestFreshValidityAndClockFailures(argv[1]); + if (failures != 0) { + std::cerr << failures << " peer-authenticator checks failed\n"; + return 1; + } + std::cout << "peer authenticator checks passed\n"; + return 0; +} diff --git a/tests/security/pinned_peer_rpc_client_contract_test.cpp b/tests/security/pinned_peer_rpc_client_contract_test.cpp new file mode 100644 index 0000000..defbf54 --- /dev/null +++ b/tests/security/pinned_peer_rpc_client_contract_test.cpp @@ -0,0 +1,249 @@ +#include "ephemeral_pki.h" +#include "rateguard/security/pinned_peer_rpc_client.h" + +#include "policy/policy_loader.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; +namespace rg = rateguard::v1; + +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_move_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_same_v< + sec::PinnedClientCallResult, + std::variant>>); + +namespace { + +int failures = 0; +void Check(bool ok, std::string_view label) { + if (!ok) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} + +std::string ReadFile(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) return {}; + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +std::string Hex(std::span bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string result; + result.reserve(bytes.size() * 2); + for (const auto byte : bytes) { + result.push_back(digits[byte >> 4]); + result.push_back(digits[byte & 15]); + } + return result; +} + +pol::Digest32 RootDigest(std::string_view pem) { + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (raw_bio == nullptr) return {}; + std::unique_ptr bio(raw_bio, &BIO_free); + X509* raw_certificate = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (raw_certificate == nullptr) return {}; + std::unique_ptr certificate(raw_certificate, &X509_free); + const int size = i2d_X509(certificate.get(), nullptr); + if (size <= 0 || size > 64 * 1024) return {}; + std::vector der(static_cast(size)); + unsigned char* cursor = der.data(); + if (i2d_X509(certificate.get(), &cursor) != size) return {}; + pol::Digest32 digest{}; + unsigned int digest_size = 0; + if (EVP_Digest(der.data(), der.size(), digest.data(), &digest_size, + EVP_sha256(), nullptr) != 1 || digest_size != digest.size()) return {}; + return digest; +} + +class MutableClock final : public sec::ITrustedWallClock { + public: + explicit MutableClock(sec::WallTime now) : now_(now) {} + sec::TrustedWallClockResult Now() override { return now_; } + bool Healthy() const override { return healthy_; } + void Set(sec::WallTime now) { now_ = now; } + void SetHealthy(bool healthy) { healthy_ = healthy; } + private: + sec::WallTime now_; + bool healthy_{true}; +}; + +struct Fixture final { + sec::test::EphemeralPki pki; + std::shared_ptr policy; + std::shared_ptr registry; + const sec::test::EphemeralIdentity* adapter{}; + const sec::test::EphemeralIdentity* replica{}; + const sec::test::EphemeralIdentity* authority{}; + sec::WallTime now{}; + + explicit Fixture(const std::string& policy_path) { + auto document = nlohmann::json::parse(ReadFile(policy_path)); + document["trust_root_sha256"] = Hex(RootDigest(pki.root_certificate_pem())); + auto loaded = pol::PolicyLoader::Load(document.dump()); + auto* policy_value = std::get_if>(&loaded); + Check(policy_value != nullptr, "policy_fixture_loads"); + if (policy_value == nullptr) return; + policy = *policy_value; + + const auto unix_seconds = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + now = {unix_seconds, 0}; + MutableClock initial_clock(now); + std::vector leaf_pems; + leaf_pems.reserve(policy->principals().size()); + for (const auto& principal : policy->principals()) { + sec::PeerRole role = sec::PeerRole::kAdapter; + if (principal.role == pol::PrincipalRole::Replica) role = sec::PeerRole::kReplica; + if (principal.role == pol::PrincipalRole::Authority) role = sec::PeerRole::kAuthority; + const auto& identity = pki.IssueWithValidity(role, principal.uri, -60, 3600); + leaf_pems.push_back(identity.certificate_pem); + if (principal.role == pol::PrincipalRole::Adapter && adapter == nullptr) + adapter = &identity; + if (principal.role == pol::PrincipalRole::Replica && replica == nullptr) + replica = &identity; + if (principal.role == pol::PrincipalRole::Authority && authority == nullptr) + authority = &identity; + } + auto loaded_registry = sec::CertificateRegistryLoader::Load( + policy, pki.root_certificate_pem(), leaf_pems, initial_clock); + auto* registry_value = std::get_if>( + &loaded_registry); + Check(registry_value != nullptr, "certificate_registry_loads"); + if (registry_value != nullptr) registry = *registry_value; + } + + sec::PinnedPeerClientConfig Config() const { + sec::PinnedPeerClientConfig config; + config.purpose = sec::ClientCallPurpose::AdapterToReplicaAdmission; + config.target = "127.0.0.1:1"; // Deliberately no service is listening. + config.local_uri = adapter->registered.uri; + config.expected_server_uri = replica->registered.uri; + config.root_certificate_pem = pki.root_certificate_pem(); + config.local_certificate_pem = adapter->certificate_pem; + config.local_private_key_pem = adapter->private_key_pem; + return config; + } +}; + +bool IsFactoryFailure(const std::variant& result, + sec::PinnedClientFactoryFailureReason reason) { + const auto* failure = std::get_if(&result); + return failure != nullptr && failure->reason == reason; +} + +void Run(const std::string& policy_path) { + Fixture fixture(policy_path); + Check(fixture.registry != nullptr && fixture.adapter != nullptr && + fixture.replica != nullptr && fixture.authority != nullptr, + "fixture_has_registered_roles"); + if (!fixture.registry || fixture.adapter == nullptr || fixture.replica == nullptr) return; + + MutableClock clock(fixture.now); + auto valid = sec::PinnedPeerRpcClient::Create(fixture.Config(), fixture.registry, clock); + Check(std::holds_alternative(valid), + "valid_pinned_client_factory_succeeds"); + if (auto* client = std::get_if(&valid)) { + rg::CheckAdmissionRequest request; + request.set_tenant_id("alpha"); + request.set_operation_id("read"); + request.set_attempt_id(std::string(16, '\x01')); + request.set_epoch_id(std::string(16, '\x02')); + request.set_policy_digest(std::string(32, '\x03')); + + clock.Set({fixture.now.unix_seconds + 3700, 0}); + auto expired = client->CheckAdmission( + request, std::chrono::system_clock::now() + std::chrono::seconds(2)); + Check(std::holds_alternative(expired), + "expired_guard_is_not_sent"); + + clock.Set(fixture.now); + auto invoked = client->CheckAdmission( + request, std::chrono::system_clock::now() + std::chrono::milliseconds(100)); + auto* result = std::get_if>(&invoked); + Check(result != nullptr, "stub_invocation_is_reported_as_invoked"); + if (result != nullptr) { + Check(result->has_transport_status(), "invoked_result_preserves_transport_status"); + clock.Set({fixture.now.unix_seconds + 3700, 0}); + auto forward_check = client->ValidateBeforeForward(*result); + Check(std::holds_alternative(forward_check), + "post_response_expiry_blocks_forward_check"); + Check(result->raw_response().outcome() == rg::DECISION_OUTCOME_UNSPECIFIED, + "post_response_guard_does_not_rewrite_raw_response"); + } + } + + auto prefixed_key = fixture.Config(); + prefixed_key.local_private_key_pem = + fixture.pki.root_certificate_pem() + prefixed_key.local_private_key_pem; + Check(IsFactoryFailure(sec::PinnedPeerRpcClient::Create( + std::move(prefixed_key), fixture.registry, clock), + sec::PinnedClientFactoryFailureReason::InvalidPrivateKeyPem), + "key_prefix_is_rejected"); + + auto multiple_keys = fixture.Config(); + multiple_keys.local_private_key_pem += "\n" + multiple_keys.local_private_key_pem; + Check(IsFactoryFailure(sec::PinnedPeerRpcClient::Create( + std::move(multiple_keys), fixture.registry, clock), + sec::PinnedClientFactoryFailureReason::InvalidPrivateKeyPem), + "multiple_key_blocks_are_rejected"); + + auto wrong_key = fixture.Config(); + wrong_key.local_private_key_pem = fixture.authority->private_key_pem; + Check(IsFactoryFailure(sec::PinnedPeerRpcClient::Create( + std::move(wrong_key), fixture.registry, clock), + sec::PinnedClientFactoryFailureReason::PrivateKeyMismatch), + "private_key_must_match_pinned_leaf"); + + auto oversized_key = fixture.Config(); + oversized_key.local_private_key_pem.assign(64U * 1024U + 1U, 'x'); + Check(IsFactoryFailure(sec::PinnedPeerRpcClient::Create( + std::move(oversized_key), fixture.registry, clock), + sec::PinnedClientFactoryFailureReason::OversizedCredential), + "private_key_input_cap_is_enforced"); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::cerr << "usage: pinned_peer_rpc_client_contract_test \n"; + return 2; + } + try { + Run(argv[1]); + } catch (...) { + std::cerr << "FAIL: unexpected bounded test exception\n"; + ++failures; + } + std::cout << (failures == 0 ? "PASS" : "FAIL") + << ": pinned outbound client contract checks\n"; + return failures == 0 ? 0 : 1; +} diff --git a/tests/security/trusted_wall_clock_test.cpp b/tests/security/trusted_wall_clock_test.cpp new file mode 100644 index 0000000..09d518c --- /dev/null +++ b/tests/security/trusted_wall_clock_test.cpp @@ -0,0 +1,234 @@ +#include "security/trusted_wall_clock.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::security; +namespace contract = rateguard::v1::contract; + +namespace { +int failures = 0; +void Check(bool condition, const char* label) { + if (!condition) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} +TrustedWallClockFailure Fail(TrustedWallClockFailureReason reason) { + return {reason}; +} + +class FakePlatform final : public ITrustedWallClockPlatform { + public: + std::deque> syncs; + std::deque> times; + std::atomic sync_calls{0}; + std::atomic realtime_calls{0}; + + TrustedWallClockResult ReadSynchronization() override { + ++sync_calls; + if (syncs.empty()) return SynchronizationStatus{0, 0}; + auto result = std::move(syncs.front()); + syncs.pop_front(); + return result; + } + TrustedWallClockResult ReadRealtime() override { + ++realtime_calls; + if (times.empty()) return RawWallTime{100, 0}; + auto result = std::move(times.front()); + times.pop_front(); + return result; + } +}; + +TrustedWallClockResult> Create( + std::unique_ptr platform) { + std::unique_ptr erased(std::move(platform)); + return TrustedWallClock::Create(std::move(erased)); +} + +bool HasFailure(const auto& result, TrustedWallClockFailureReason reason) { + const auto* failure = std::get_if(&result); + if (!failure || failure->reason != reason) return false; + const auto service = failure->ToServiceError(contract::Commitment::NotCommitted); + return service.category == contract::ErrorCategory::Dependency && + service.code == contract::ErrorCode::Unavailable && + service.retry == contract::RetryDisposition::Never && + service.commitment == contract::Commitment::NotCommitted; +} + +void TestCommitmentMapping() { + const TrustedWallClockFailure failure{ + TrustedWallClockFailureReason::BackwardsRead}; + for (const auto commitment : {contract::Commitment::NotCommitted, + contract::Commitment::Possible, + contract::Commitment::Committed}) { + const auto service = failure.ToServiceError(commitment); + Check(service.category == contract::ErrorCategory::Dependency && + service.code == contract::ErrorCode::Unavailable && + service.retry == contract::RetryDisposition::Never && + service.commitment == commitment, + "clock error preserves caller-supplied operation commitment"); + } +} + +void TestAllowedAndRejectedStates() { + for (std::int32_t state = 0; state <= 4; ++state) { + auto fake = std::make_unique(); + fake->syncs = {SynchronizationStatus{state, 0}, SynchronizationStatus{state, 0}}; + fake->times = {RawWallTime{10, 50}, RawWallTime{10, 51}}; + auto created = Create(std::move(fake)); + Check(std::holds_alternative>(created), + "TIME_OK/INS/DEL/OOP/WAIT states accepted"); + if (auto* clock = std::get_if>(&created)) { + Check((*clock)->Healthy(), "healthy after initial trusted sample"); + auto now = (*clock)->Now(); + Check(std::get_if(&now) && std::get(now) == WallTime{10, 51}, + "trusted wall time sample returned exactly"); + } + } + auto time_error = std::make_unique(); + time_error->syncs = {SynchronizationStatus{5, 0}}; + Check(HasFailure(Create(std::move(time_error)), + TrustedWallClockFailureReason::TimeErrorState), + "TIME_ERROR rejects factory"); + auto unknown = std::make_unique(); + unknown->syncs = {SynchronizationStatus{99, 0}}; + Check(HasFailure(Create(std::move(unknown)), + TrustedWallClockFailureReason::UnknownState), + "unknown synchronization state rejects factory"); +} + +void TestStatusFlagsAndTypedErrors() { + const std::array, 3> flags{{ + {0x0040, TrustedWallClockFailureReason::UnsynchronizedFlag}, + {0x1000, TrustedWallClockFailureReason::ClockErrorFlag}, + {0x1040, TrustedWallClockFailureReason::UnsynchronizedFlag}, + }}; + for (const auto& [bits, reason] : flags) { + auto fake = std::make_unique(); + fake->syncs = {SynchronizationStatus{0, bits}}; + Check(HasFailure(Create(std::move(fake)), reason), + "STA_UNSYNC/STA_CLOCKERR bits reject before realtime read"); + } + + auto sync_failure = std::make_unique(); + sync_failure->syncs = {Fail(TrustedWallClockFailureReason::SynchronizationSyscall)}; + auto sync_fail = Create(std::move(sync_failure)); + Check(HasFailure(sync_fail, TrustedWallClockFailureReason::SynchronizationSyscall), + "synchronization syscall error is typed unavailable"); + + auto realtime_failure = std::make_unique(); + realtime_failure->times = {Fail(TrustedWallClockFailureReason::RealtimeSyscall)}; + Check(HasFailure(Create(std::move(realtime_failure)), + TrustedWallClockFailureReason::RealtimeSyscall), + "realtime syscall error rejects initial factory sample"); + Check(HasFailure(TrustedWallClock::Create(nullptr), + TrustedWallClockFailureReason::PlatformUnavailable), + "missing platform is typed unavailable"); +} + +void TestRangeOrderingAndStickyFailure() { + auto invalid_seconds = std::make_unique(); + invalid_seconds->times = {RawWallTime{-1, 0}}; + Check(HasFailure(Create(std::move(invalid_seconds)), + TrustedWallClockFailureReason::InvalidSeconds), + "negative Unix seconds rejected"); + + const std::array invalid_nanos{-1, 1'000'000'000}; + for (std::int64_t nanos : invalid_nanos) { + auto invalid = std::make_unique(); + invalid->times = {RawWallTime{100, nanos}}; + Check(HasFailure(Create(std::move(invalid)), + TrustedWallClockFailureReason::InvalidNanoseconds), + "negative or out-of-range nanoseconds rejected"); + } + + auto extreme = std::make_unique(); + extreme->times = {RawWallTime{std::numeric_limits::max(), + 999'999'999}}; + auto extreme_result = Create(std::move(extreme)); + Check(std::holds_alternative>(extreme_result), + "maximum int64 seconds do not overflow through nanosecond multiplication"); + + auto equal = std::make_unique(); + equal->times = {RawWallTime{100, 200}, RawWallTime{100, 200}}; + auto equal_result = Create(std::move(equal)); + if (auto* clock = std::get_if>(&equal_result)) + Check(std::holds_alternative((*clock)->Now()), "equal wall-time samples accepted"); + else + Check(false, "equal sample clock created"); + + auto backwards = std::make_unique(); + backwards->times = {RawWallTime{101, 0}, RawWallTime{100, 999'999'999}, + RawWallTime{102, 0}}; + auto backwards_result = Create(std::move(backwards)); + auto& clock = *std::get>(backwards_result); + Check(HasFailure(clock.Now(), TrustedWallClockFailureReason::BackwardsRead), + "lexicographically backward sample latches trust loss"); + Check(!clock.Healthy(), "backwards sample makes health false"); + Check(HasFailure(clock.Now(), TrustedWallClockFailureReason::BackwardsRead), + "first failure remains sticky"); + Check(HasFailure(clock.Now(), TrustedWallClockFailureReason::BackwardsRead), + "later recovery-looking data cannot restore trust"); +} + +void TestInitialFailureAndConcurrency() { + auto bad_initial = std::make_unique(); + bad_initial->syncs = {SynchronizationStatus{1, 0}}; + bad_initial->times = {Fail(TrustedWallClockFailureReason::RealtimeSyscall)}; + Check(HasFailure(Create(std::move(bad_initial)), + TrustedWallClockFailureReason::RealtimeSyscall), + "factory returns no usable object if initial realtime read fails"); + + constexpr std::size_t count = 24; + auto concurrent = std::make_unique(); + for (std::size_t i = 0; i <= count; ++i) { + concurrent->syncs.emplace_back(SynchronizationStatus{0, 0}); + concurrent->times.emplace_back(RawWallTime{1000 + static_cast(i), 0}); + } + auto result = Create(std::move(concurrent)); + auto& clock = *std::get>(result); + std::array successful{}; + std::array values{}; + std::array threads; + for (std::size_t i = 0; i < count; ++i) { + threads[i] = std::thread([&, i] { + auto value = clock.Now(); + if (const auto* time = std::get_if(&value)) { + values[i] = *time; + successful[i] = true; + } + }); + } + for (auto& thread : threads) thread.join(); + for (bool ok : successful) Check(ok, "concurrent trusted wall-time sample succeeds"); + std::sort(values.begin(), values.end(), [](WallTime lhs, WallTime rhs) { return lhs < rhs; }); + for (std::size_t i = 0; i < count; ++i) + Check(values[i] == WallTime{1001 + static_cast(i), 0}, + "mutex serializes synchronization/read/compare sequence"); + Check(clock.Healthy(), "concurrent sequence stays trusted"); +} +} // namespace + +int main() { + TestCommitmentMapping(); + TestAllowedAndRejectedStates(); + TestStatusFlagsAndTypedErrors(); + TestRangeOrderingAndStickyFailure(); + TestInitialFailureAndConcurrency(); + if (failures != 0) return EXIT_FAILURE; + std::cout << "trusted wall clock checks passed\n"; + return EXIT_SUCCESS; +} diff --git a/tests/strict_reconciliation_test.cpp b/tests/strict_reconciliation_test.cpp new file mode 100644 index 0000000..e35b057 --- /dev/null +++ b/tests/strict_reconciliation_test.cpp @@ -0,0 +1,161 @@ +#include "tools/history/strict_reconciliation.h" +#include +#include +#include +#include +#include +#include + +using namespace rateguard::events; +using namespace rateguard::events::reconciliation; +namespace { +int failures=0; +#define CHECK(x) do { if (!(x)) { std::cerr << "FAIL line " << __LINE__ << ": " #x "\n"; ++failures; } } while(0) +struct Input { ProducerOwner owner; Stage stage; Outcome outcome; std::uint8_t id; std::uint64_t time; }; +AttemptId Id(std::uint8_t x) { AttemptId id{}; id[0]=0xF0; id[15]=x; return id; } +EventSnapshotV1 Build(std::vector inputs, RunPlan& plan) { + std::map counts; + for (const auto& x:inputs) ++counts[x.owner]; + plan={}; plan.epoch_id[0]=0x21; plan.policy_digest[0]=0x42; + for (const auto& [owner,count]:counts) plan.producers.push_back({owner,0,count}); + auto made=EventRecorder::Create(plan); CHECK(std::holds_alternative(made)); + auto recorder=std::get(std::move(made)); + std::map handles; + for(const auto& [owner,count]:counts) { + (void)count; auto attached=recorder.AttachProducer(owner,0); + CHECK(std::holds_alternative(attached)); + handles.emplace(owner,std::get(std::move(attached))); + } + std::map sequence; + for(const auto& x:inputs) { + auto reservation_result=handles.at(x.owner).Reserve(); + CHECK(std::holds_alternative(reservation_result)); + auto reservation=std::get(std::move(reservation_result)); + EventV1 event; event.stage=x.stage; event.outcome=x.outcome; event.attempt_id=Id(x.id); + event.timestamp_ns=x.time; event.cost_units=1; + CHECK(handles.at(x.owner).Publish(std::move(reservation),event)==RecorderError::None); + ++sequence[x.owner]; + } + for(auto& [owner,handle]:handles) { (void)owner; CHECK(handle.Seal()==RecorderError::None); } + auto snapshot=recorder.ExportSnapshotV1(); CHECK(std::holds_alternative(snapshot)); + return std::get(std::move(snapshot)); +} +AttemptDeadline Deadline(std::uint8_t id,std::uint64_t ns) { return {Id(id),ns}; } +const AttemptResult* Find(const ReconciliationReport& r,std::uint8_t id) { + for (const auto& attempt : r.attempts) { + if (attempt.attempt_id == Id(id)) return &attempt; + } + return nullptr; +} +void TestTimelyAndEqualityLate() { + RunPlan p; auto s=Build({ + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,1,10}, + {ProducerOwner::Authority,Stage::StrictDecision,Outcome::Allow,1,20}, + {ProducerOwner::Replica,Stage::Responded,Outcome::Allow,1,30}, + {ProducerOwner::Adapter,Stage::Received,Outcome::Allow,1,40}, + {ProducerOwner::Adapter,Stage::Forwarded,Outcome::Allow,1,41}, + {ProducerOwner::Backend,Stage::Completed,Outcome::Error,1,50}, + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,2,10}, + {ProducerOwner::Authority,Stage::StrictDecision,Outcome::Allow,2,20}, + {ProducerOwner::Replica,Stage::Responded,Outcome::Allow,2,30}, + {ProducerOwner::Adapter,Stage::Received,Outcome::Allow,2,41}, + {ProducerOwner::Adapter,Stage::Forwarded,Outcome::Allow,2,42}, + },p); + const AttemptDeadline ds[]={Deadline(1,41),Deadline(2,41)}; + auto r=ReconcileStrictHistory(s,p,ds); + CHECK(r.evidence==EvidenceState::Complete && !r.safety_pass_allowed); + CHECK(r.offered_records==2 && r.offered_attempts==2); + CHECK(r.strict_allow_commits==2 && r.response_sends==2 && r.adapter_receipts==2); + CHECK(r.timely_allow==1 && r.late_allow==1); + CHECK(Find(r,1)->state==AttemptState::TimelyAllow); + CHECK(Find(r,2)->state==AttemptState::LateAllow); // equality is late: timely is strictly < deadline + CHECK(Find(r,1)->timestamp_order_valid && Find(r,2)->timestamp_order_valid); + bool denied_late_forward = false; + for (const auto violation : r.violations) { + if (violation == Violation::ForwardWithoutAllow) denied_late_forward = true; + } + CHECK(denied_late_forward); // equal-to-deadline receipt cannot authorize forwarding +} +void TestLostResponseAndNoResponseLimited() { + RunPlan p; auto s=Build({ + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,3,10}, + {ProducerOwner::Authority,Stage::StrictDecision,Outcome::Allow,3,20}, + {ProducerOwner::Replica,Stage::Responded,Outcome::Allow,3,30}, + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,4,11}, + {ProducerOwner::Authority,Stage::StrictDecision,Outcome::Limited,4,21}, + {ProducerOwner::Replica,Stage::Responded,Outcome::Limited,4,31}, + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,9,12}, + {ProducerOwner::Authority,Stage::StrictDecision,Outcome::Allow,9,22}, + {ProducerOwner::Adapter,Stage::Received,Outcome::Unavailable,9,32}, + },p); + const AttemptDeadline ds[]={Deadline(3,100),Deadline(4,100),Deadline(9,100)}; + auto r=ReconcileStrictHistory(s,p,ds); + CHECK(r.evidence==EvidenceState::Complete); + CHECK(r.committed_unanswered==1); // only committed ALLOW debit + CHECK(r.decision_unanswered==2); // known LIMITED is a decision but not debit + CHECK(r.limited_decision_unanswered==1); + CHECK(r.response_sent_unreceived==2 && r.adapter_receipts==1); + CHECK(r.timely_limited==0); // no-response LIMITED is never counted delivered + CHECK(r.terminal_errors==1 && r.decision_response_mismatches==0); // committed ALLOW may receive an application error + CHECK(Find(r,3)->state==AttemptState::CommittedUnanswered); + CHECK(Find(r,4)->state==AttemptState::CommittedUnanswered); + CHECK(Find(r,3)->committed && !Find(r,4)->committed); + CHECK(Find(r,9)->state==AttemptState::TerminalError); +} +void TestDuplicateStageAndUncommittedAllow() { + RunPlan p; auto s=Build({ + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,5,10}, + {ProducerOwner::Authority,Stage::StrictDecision,Outcome::Allow,5,20}, + {ProducerOwner::Adapter,Stage::Received,Outcome::Allow,5,30}, + {ProducerOwner::Adapter,Stage::Received,Outcome::Allow,5,31}, + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,6,10}, + {ProducerOwner::Adapter,Stage::Received,Outcome::Allow,6,20}, + },p); + const AttemptDeadline ds[]={Deadline(5,100),Deadline(6,100)}; + auto r=ReconcileStrictHistory(s,p,ds); + CHECK(r.evidence==EvidenceState::Complete); + CHECK(r.duplicate_stage_violations==1); + CHECK(Find(r,5)->state==AttemptState::DuplicateStage); + CHECK(r.uncommitted_allow_responses==1); + CHECK(r.unresolved_attempts>=2); + CHECK(r.timely_allow==0); // duplicates / no matching committed decision cannot inflate numerator +} +void TestExternalDeadlineRequiredAndDuplicateDeadlineRejected() { + RunPlan p; auto s=Build({ + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,0x7e,10}, + {ProducerOwner::Authority,Stage::StrictDecision,Outcome::Allow,0x7e,20}, + },p); + auto absent=ReconcileStrictHistory(s,p,{}); + CHECK(absent.evidence==EvidenceState::Complete); + CHECK(absent.unmatched_deadlines==1 && absent.unresolved_attempts==1); + CHECK(Find(absent,0x7e)->state==AttemptState::CommittedUnanswered); + const AttemptDeadline duplicate[]={Deadline(0x7e,100),Deadline(0x7e,100)}; + auto bad=ReconcileStrictHistory(s,p,duplicate); + CHECK(bad.evidence==EvidenceState::Invalid); + CHECK(!bad.safety_pass_allowed); +} +void TestTimestampOrderAndOrphan() { + RunPlan p; auto s=Build({ + {ProducerOwner::WorkloadGenerator,Stage::Offered,Outcome::None,7,30}, + {ProducerOwner::Authority,Stage::StrictDecision,Outcome::Allow,7,20}, + {ProducerOwner::Adapter,Stage::Received,Outcome::Allow,7,40}, + {ProducerOwner::Backend,Stage::Completed,Outcome::Error,8,50}, + },p); + const AttemptDeadline ds[]={Deadline(7,100),Deadline(8,100)}; + auto r=ReconcileStrictHistory(s,p,ds); + CHECK(r.evidence==EvidenceState::Complete); + CHECK(!Find(r,7)->timestamp_order_valid); + CHECK(r.orphan_stage_attempts==1 && r.unmatched_deadlines==1); + CHECK(Find(r,8)->state==AttemptState::OrphanStage); + CHECK(!r.safety_pass_allowed); +} +} +int main(){ + TestTimelyAndEqualityLate(); + TestLostResponseAndNoResponseLimited(); + TestDuplicateStageAndUncommittedAllow(); + TestExternalDeadlineRequiredAndDuplicateDeadlineRejected(); + TestTimestampOrderAndOrphan(); + if(failures){std::cerr<<"RG005 reconciliation tests failed: "< +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::supervisor; + +#define CHECK(expr) do { if (!(expr)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #expr); \ + std::abort(); \ +} } while (false) + +namespace { + +BootstrapPlan Plan() { + BootstrapPlan plan; + plan.domain_id[0] = 0x51; + plan.epoch_id[0] = 1; + plan.authority_incarnation[0] = 2; + plan.policy_digest[0] = 3; + plan.expected_clock_identity.boot_uuid[0] = 4; + plan.expected_clock_identity.namespace_device = 11; + plan.expected_clock_identity.namespace_inode = 12; + plan.expected_clock_identity.clock_id = 1; + const auto add = [&](ParticipantRole role, std::uint32_t slot, const char* id, + std::uint8_t incarnation, char container) { + PlannedParticipant p; + p.role = role; + p.slot_id = slot; + p.participant_id = id; + p.incarnation[0] = role == ParticipantRole::Authority + ? plan.authority_incarnation[0] : incarnation; + p.container_id = std::string(64, container); + plan.participants.push_back(p); + }; + add(ParticipantRole::Authority, 0, "authority", 2, 'a'); + add(ParticipantRole::Witness, 0, "witness", 5, 'b'); + add(ParticipantRole::Replica, 0, "replica-zero", 6, 'c'); + add(ParticipantRole::Replica, UINT32_MAX, "replica-max", 7, 'd'); + add(ParticipantRole::Adapter, 0, "adapter-a", 8, 'e'); + add(ParticipantRole::Adapter, 0, "adapter-b", 9, 'f'); + return plan; +} + +ObservedBootstrapIdentity Observation(const BootstrapPlan& plan, std::size_t index, + std::uint64_t pid) { + ObservedBootstrapIdentity value; + value.participant = plan.participants.at(index); + value.pid = pid; + value.pid_start_ticks = pid + 1000; + value.clock_identity = plan.expected_clock_identity; + return value; +} + +BootstrapInventory MustCreate(const BootstrapPlan& plan) { + auto result = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(result)); + return std::get(std::move(result)); +} + +BootstrapInventory MustRecord(const BootstrapInventory& prior, + const ObservedBootstrapIdentity& observed) { + auto result = prior.RecordIdentity(observed); + CHECK(result.status == BootstrapError::None); + return std::move(result.next); +} + +BootstrapInventory RoundTrip(const BootstrapInventory& value) { + auto encoded = EncodeBootstrapInventoryV1(value); + CHECK(std::holds_alternative(encoded)); + auto decoded = DecodeBootstrapInventoryV1(std::get(encoded)); + CHECK(std::holds_alternative(decoded)); + return std::get(std::move(decoded)); +} + +void TestNoReadyCandidateUntilExactFullRoster() { + const auto plan = Plan(); + auto inventory = MustCreate(plan); + CHECK(inventory.recorded_count() == 0); + CHECK(inventory.revision() == 1); + CHECK(std::holds_alternative(inventory.ReadyCandidate())); + CHECK(std::get(inventory.ReadyCandidate()) == BootstrapError::IncompleteRoster); + + for (std::size_t i = 0; i < plan.participants.size(); ++i) { + inventory = MustRecord(inventory, Observation(plan, i, 100 + i)); + CHECK(inventory.recorded_count() == i + 1); + CHECK(inventory.revision() == i + 2); + // The caller-visible state is modeled through encode/decode between every + // launch step; this test does not claim those bytes were durably persisted. + inventory = RoundTrip(inventory); + if (i + 1 < plan.participants.size()) + CHECK(std::holds_alternative(inventory.ReadyCandidate())); + } + const auto ready = inventory.ReadyCandidate(); + CHECK(std::holds_alternative(ready)); + const auto& candidate = std::get(ready); + CHECK(candidate.epoch_id == plan.epoch_id); + CHECK(candidate.authority_incarnation == plan.authority_incarnation); + CHECK(candidate.policy_digest == plan.policy_digest); + CHECK(candidate.clock_identity == plan.expected_clock_identity); + CHECK(candidate.participants.size() == plan.participants.size()); + for (std::size_t i = 0; i < plan.participants.size(); ++i) { + const auto& planned = plan.participants[i]; + const auto found = std::find_if(candidate.participants.begin(), candidate.participants.end(), + [&](const Participant& p) { + return p.role == planned.role && p.participant_id == planned.participant_id; + }); + CHECK(found != candidate.participants.end()); + const auto& actual = *found; + CHECK(actual.role == planned.role); + CHECK(actual.slot_id == planned.slot_id); + CHECK(actual.participant_id == planned.participant_id); + CHECK(actual.incarnation == planned.incarnation); + CHECK(actual.process.container_id == planned.container_id); + CHECK(actual.process.pid == 100 + i); + CHECK(actual.process.pid_start_ticks == 1100 + i); + CHECK(actual.clock_identity == plan.expected_clock_identity); + } +} + +void TestIdempotentRepeatAndImmutableIdentity() { + const auto plan = Plan(); + auto inventory = MustCreate(plan); + const auto first = Observation(plan, 0, 200); + inventory = MustRecord(inventory, first); + CHECK(inventory.revision() == 2); + const auto duplicate = inventory.RecordIdentity(first); + CHECK(duplicate.status == BootstrapError::None); + CHECK(duplicate.next.recorded_count() == 1); + CHECK(duplicate.next.revision() == inventory.revision()); + CHECK(!duplicate.next.recovery_required()); + + auto replacement = first; + replacement.pid_start_ticks += 1; + const auto rejected = duplicate.next.RecordIdentity(replacement); + CHECK(rejected.status == BootstrapError::IdentityMismatch); + CHECK(rejected.next.recovery_required()); + CHECK(rejected.next.revision() == inventory.revision() + 1); + CHECK(rejected.next.recovery_reason() == BootstrapError::IdentityMismatch); + CHECK(std::holds_alternative(rejected.next.ReadyCandidate())); + + const auto retry = rejected.next.RecordIdentity(first); + CHECK(retry.status == BootstrapError::RecoveryRequired); + CHECK(retry.next.recovery_required()); + CHECK(retry.next.revision() == rejected.next.revision()); + CHECK(std::holds_alternative(retry.next.ReadyCandidate())); +} + +void TestUnknownAndMismatchedObservationsLatchRecovery() { + const auto plan = Plan(); + auto inventory = MustCreate(plan); + for (const auto& bad_kind : {0, 1, 2, 3}) { + auto bad = Observation(plan, 0, 300); + if (bad_kind == 0) bad.participant.participant_id = "unplanned"; + if (bad_kind == 1) bad.participant.container_id = std::string(64, 'z'); + if (bad_kind == 2) bad.participant.incarnation[0] ^= 1; + if (bad_kind == 3) bad.clock_identity.namespace_inode += 1; + auto transition = inventory.RecordIdentity(bad); + CHECK(transition.status != BootstrapError::None); + CHECK(transition.next.recovery_required()); + CHECK(std::holds_alternative(transition.next.ReadyCandidate())); + } + + auto unknown_role = Observation(plan, 0, 300); + unknown_role.participant.role = ParticipantRole::Adapter; + auto unknown = inventory.RecordIdentity(unknown_role); + CHECK(unknown.status == BootstrapError::IdentityNotInPlan); + CHECK(unknown.next.recovery_reason() == BootstrapError::IdentityNotInPlan); +} + +void TestInvalidProcessIdentityAndPIDReuse() { + const auto plan = Plan(); + for (const bool pid_zero : {false, true}) { + auto inventory = MustCreate(plan); + auto bad = Observation(plan, 0, 400); + if (pid_zero) bad.pid = 0; + else bad.pid_start_ticks = 0; + const auto result = inventory.RecordIdentity(bad); + CHECK(result.status != BootstrapError::None); + CHECK(result.next.recovery_required()); + } + + auto inventory = MustCreate(plan); + inventory = MustRecord(inventory, Observation(plan, 0, 500)); + auto reused_pid = Observation(plan, 1, 500); + reused_pid.pid_start_ticks = 9000; // Different start time cannot make two live PIDs unique. + const auto collision = inventory.RecordIdentity(reused_pid); + CHECK(collision.status == BootstrapError::DuplicateProcessIdentity); + CHECK(collision.next.recovery_reason() == BootstrapError::DuplicateProcessIdentity); + CHECK(collision.next.recovery_required()); + +} + +void TestPlanValidationAndExplicitRecovery() { + auto invalid = Plan(); + invalid.participants[2].container_id = invalid.participants[1].container_id; + CHECK(std::holds_alternative(BootstrapInventory::Create(invalid))); + + invalid = Plan(); + invalid.expected_clock_identity.clock_id = 99; + CHECK(std::holds_alternative(BootstrapInventory::Create(invalid))); + + auto inventory = MustCreate(Plan()); + const auto recovery = inventory.RequireRecovery(BootstrapError::InvalidEncoding); + CHECK(recovery.recovery_required()); + CHECK(recovery.revision() == inventory.revision() + 1); + CHECK(recovery.recovery_reason() == BootstrapError::InvalidEncoding); + CHECK(std::holds_alternative(recovery.ReadyCandidate())); + auto attempted_recover = recovery.RecordIdentity(Observation(Plan(), 0, 601)); + CHECK(attempted_recover.status == BootstrapError::RecoveryRequired); + CHECK(attempted_recover.next.recovery_required()); + CHECK(attempted_recover.next.revision() == recovery.revision()); +} + +void TestCanonicalCodecRejectsMalformedAndUntrustedEdits() { + const auto inventory = MustCreate(Plan()); + const auto encoded = EncodeBootstrapInventoryV1(inventory); + CHECK(std::holds_alternative(encoded)); + const auto canonical = std::get(encoded); + const auto round_trip = DecodeBootstrapInventoryV1(canonical); + CHECK(std::holds_alternative(round_trip)); + + auto whitespace = canonical; + whitespace.push_back(' '); + const auto noncanonical = DecodeBootstrapInventoryV1(whitespace); + CHECK(std::get_if(&noncanonical) != nullptr); + CHECK(std::get(noncanonical) == BootstrapError::NonCanonical); + + auto bad_digest = canonical; + const auto hash = bad_digest.find("\"sha256\":\""); + CHECK(hash != std::string::npos); + const auto hash_digit = hash + 10; + bad_digest[hash_digit] = bad_digest[hash_digit] == '0' ? '1' : '0'; + const auto digest_error = DecodeBootstrapInventoryV1(bad_digest); + CHECK(std::get_if(&digest_error) != nullptr); + CHECK(std::get(digest_error) == BootstrapError::DigestMismatch); + + // Duplicate keys are rejected even when their values would later fail schema validation. + auto duplicate = canonical; + const auto inventory_key = duplicate.find("\"inventory\":"); + CHECK(inventory_key != std::string::npos); + duplicate.insert(inventory_key, "\"invent\\u006fry\":{},"); + const auto duplicate_error = DecodeBootstrapInventoryV1(duplicate); + CHECK(std::get_if(&duplicate_error) != nullptr); + CHECK(std::get(duplicate_error) == BootstrapError::DuplicateKey); + + auto unknown = canonical; + const auto object = unknown.find('{'); + CHECK(object == 0); + unknown.insert(object + 1, "\"unexpected\":0,"); + const auto unknown_error = DecodeBootstrapInventoryV1(unknown); + CHECK(std::get_if(&unknown_error) != nullptr); + CHECK(std::get(unknown_error) == BootstrapError::UnknownKey); + + const auto oversized = DecodeBootstrapInventoryV1(std::string(kMaxBootstrapBytes + 1, ' ')); + CHECK(std::get_if(&oversized) != nullptr); + CHECK(std::get(oversized) == BootstrapError::TooLarge); +} + +} // namespace + +int main() { + static_assert(kMaxBootstrapBytes == 4U * 1024U * 1024U); + TestNoReadyCandidateUntilExactFullRoster(); + TestIdempotentRepeatAndImmutableIdentity(); + TestUnknownAndMismatchedObservationsLatchRecovery(); + TestInvalidProcessIdentityAndPIDReuse(); + TestPlanValidationAndExplicitRecovery(); + TestCanonicalCodecRejectsMalformedAndUntrustedEdits(); + std::puts("independent bootstrap inventory checks passed"); +} diff --git a/tests/supervisor/bootstrap_inventory_test.cpp b/tests/supervisor/bootstrap_inventory_test.cpp new file mode 100644 index 0000000..453ff3f --- /dev/null +++ b/tests/supervisor/bootstrap_inventory_test.cpp @@ -0,0 +1,209 @@ +#include "supervisor/bootstrap_inventory.h" + +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::supervisor; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #condition); \ + std::abort(); \ + } \ +} while (false) + +std::string Hex(const std::array& bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string out; + for (const auto byte : bytes) { + out.push_back(digits[byte >> 4]); + out.push_back(digits[byte & 15]); + } + return out; +} + +BootstrapPlan Plan() { + BootstrapPlan plan; + plan.domain_id.fill(0x10); + plan.epoch_id.fill(0x11); + plan.authority_incarnation.fill(0x22); + plan.policy_digest.fill(0x33); + plan.expected_clock_identity.boot_uuid.fill(0x44); + plan.expected_clock_identity.namespace_device = 7; + plan.expected_clock_identity.namespace_inode = 9; + plan.expected_clock_identity.monotonic_offset_seconds = -2; + plan.expected_clock_identity.monotonic_offset_nanoseconds = 123; + plan.expected_clock_identity.boottime_offset_seconds = 3; + plan.expected_clock_identity.boottime_offset_nanoseconds = 456; + plan.expected_clock_identity.clock_id = 1; + + const auto participant = [](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation_byte, char suffix) { + PlannedParticipant p; + p.role = role; + p.slot_id = slot; + p.participant_id = std::move(id); + p.incarnation.fill(incarnation_byte); + p.container_id = std::string(63, 'a') + suffix; + return p; + }; + // Deliberately unsorted to verify canonical inventory order. + plan.participants = { + participant(ParticipantRole::Witness, 0, "witness", 0x66, '4'), + participant(ParticipantRole::Adapter, 0, "adapter", 0x77, '3'), + participant(ParticipantRole::Replica, 19, "replica", 0x88, '2'), + participant(ParticipantRole::Authority, 0, "authority", 0x22, '1'), + }; + return plan; +} + +std::variant NewInventory() { + return BootstrapInventory::Create(Plan()); +} + +ObservedBootstrapIdentity Observation(const PlannedParticipant& participant, std::uint64_t pid) { + return ObservedBootstrapIdentity{participant, pid, pid + 1000, Plan().expected_clock_identity}; +} + +BootstrapInventory Apply(const BootstrapInventory& prior, const ObservedBootstrapIdentity& observed) { + auto transition = prior.RecordIdentity(observed); + CHECK(transition.status == BootstrapError::None); + return transition.next; +} + +void TestStageProgressAndCodec() { + auto created = NewInventory(); + CHECK(std::holds_alternative(created)); + auto inventory = std::get(created); + CHECK(inventory.recorded_count() == 0); + CHECK(std::get(inventory.ReadyCandidate()) == BootstrapError::IncompleteRoster); + CHECK(inventory.records().front().planned.role == ParticipantRole::Authority); + CHECK(inventory.records().back().planned.role == ParticipantRole::Witness); + + const auto encoded_initial = EncodeBootstrapInventoryV1(inventory); + CHECK(std::holds_alternative(encoded_initial)); + auto digest = BootstrapDigestV1(inventory); + CHECK((std::holds_alternative>(digest))); + CHECK(Hex(std::get>(digest)) == + "7d46c1694ecf5fb38622deb41273c40c7b4de26d2066c16ed1418bfcdd93e773"); + auto decoded = DecodeBootstrapInventoryV1(std::get(encoded_initial)); + CHECK(std::holds_alternative(decoded)); + CHECK(EncodeBootstrapInventoryV1(std::get(decoded)) == encoded_initial); + + const auto original_plan = Plan(); + for (std::size_t index = 0; index < original_plan.participants.size(); ++index) { + inventory = Apply(inventory, Observation(original_plan.participants[index], 100 + index)); + CHECK(inventory.recorded_count() == index + 1); + if (index + 1 != original_plan.participants.size()) + CHECK(std::get(inventory.ReadyCandidate()) == BootstrapError::IncompleteRoster); + } + CHECK(inventory.revision() == 5); + const auto complete = inventory.ReadyCandidate(); + CHECK(std::holds_alternative(complete)); + CHECK(std::get(complete).participants.size() == original_plan.participants.size()); + CHECK(std::get(complete).participants[1].slot_id == 19); + + const auto repeated = inventory.RecordIdentity(Observation(original_plan.participants[0], 100)); + CHECK(repeated.status == BootstrapError::None); + CHECK(repeated.next.revision() == inventory.revision()); + CHECK(EncodeBootstrapInventoryV1(repeated.next) == EncodeBootstrapInventoryV1(inventory)); + const auto final_encoded = EncodeBootstrapInventoryV1(inventory); + CHECK(std::holds_alternative(final_encoded)); + CHECK(std::holds_alternative(DecodeBootstrapInventoryV1(std::get(final_encoded)))); +} + +void TestMismatchLatchesRecovery() { + auto created = NewInventory(); + CHECK(std::holds_alternative(created)); + const auto inventory = std::get(created); + auto unknown = Observation(Plan().participants.front(), 101); + unknown.participant.participant_id = "not-registered"; + auto transition = inventory.RecordIdentity(unknown); + CHECK(transition.status == BootstrapError::IdentityNotInPlan); + CHECK(transition.next.recovery_required()); + CHECK(transition.next.recovery_reason() == BootstrapError::IdentityNotInPlan); + CHECK(transition.next.revision() == inventory.revision() + 1); + CHECK(std::get(transition.next.ReadyCandidate()) == BootstrapError::RecoveryRequired); + + auto correct = Observation(inventory.records().front().planned, 101); + auto blocked = transition.next.RecordIdentity(correct); + CHECK(blocked.status == BootstrapError::RecoveryRequired); + CHECK(blocked.next.recovery_required()); + + auto initial2 = NewInventory(); + CHECK(std::holds_alternative(initial2)); + auto wrong_clock = Observation(inventory.records().front().planned, 101); + wrong_clock.clock_identity.namespace_inode++; + auto clock_failure = std::get(initial2).RecordIdentity(wrong_clock); + CHECK(clock_failure.status == BootstrapError::IdentityMismatch); + CHECK(clock_failure.next.recovery_required()); +} + +void TestReplacementAndDuplicatePidLatch() { + const auto plan = Plan(); + auto created = NewInventory(); + CHECK(std::holds_alternative(created)); + auto inventory = std::get(created); + inventory = Apply(inventory, Observation(plan.participants[0], 200)); + auto replacement = inventory.RecordIdentity(Observation(plan.participants[0], 201)); + CHECK(replacement.status == BootstrapError::IdentityMismatch); + CHECK(replacement.next.recovery_required()); + + auto another = NewInventory(); + CHECK(std::holds_alternative(another)); + inventory = std::get(another); + inventory = Apply(inventory, Observation(plan.participants[0], 300)); + auto duplicate = inventory.RecordIdentity(Observation(plan.participants[1], 300)); + CHECK(duplicate.status == BootstrapError::DuplicateProcessIdentity); + CHECK(duplicate.next.recovery_required()); +} + +void TestCodecRejectsCorruptionDuplicatesAndCaps() { + auto created = NewInventory(); + CHECK(std::holds_alternative(created)); + const auto encoded = EncodeBootstrapInventoryV1(std::get(created)); + CHECK(std::holds_alternative(encoded)); + const auto good = std::get(encoded); + + auto corrupted = good; + const auto digest = corrupted.find("\"sha256\":\""); + CHECK(digest != std::string::npos); + corrupted[digest + 10] = corrupted[digest + 10] == '0' ? '1' : '0'; + CHECK(std::get(DecodeBootstrapInventoryV1(corrupted)) == BootstrapError::DigestMismatch); + + CHECK(std::get(DecodeBootstrapInventoryV1(good + " ")) == BootstrapError::NonCanonical); + const std::string duplicate = "{\"inventory\":{},\"inventory\":{},\"sha256\":\"" + + std::string(64, '0') + "\"}"; + CHECK(std::get(DecodeBootstrapInventoryV1(duplicate)) == BootstrapError::DuplicateKey); + CHECK(std::get(DecodeBootstrapInventoryV1(std::string(kMaxBootstrapBytes + 1, ' '))) == + BootstrapError::TooLarge); +} + +void TestInvalidPlansRejected() { + auto plan = Plan(); + plan.participants[0].container_id = plan.participants[1].container_id; + CHECK(std::get(BootstrapInventory::Create(plan)) == BootstrapError::InvalidPlan); + plan = Plan(); + plan.participants.pop_back(); + CHECK(std::get(BootstrapInventory::Create(plan)) == BootstrapError::InvalidPlan); + plan = Plan(); + plan.participants[2].slot_id = UINT32_MAX; // fixed policy IDs are not constrained to [0, N) + auto max_slot = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(max_slot)); +} + +} // namespace + +int main() { + TestStageProgressAndCodec(); + TestMismatchLatchesRecovery(); + TestReplacementAndDuplicatePidLatch(); + TestCodecRejectsCorruptionDuplicatesAndCaps(); + TestInvalidPlansRejected(); + return 0; +} diff --git a/tests/supervisor/bootstrap_recovery_reader_independent_test.cpp b/tests/supervisor/bootstrap_recovery_reader_independent_test.cpp new file mode 100644 index 0000000..cacad33 --- /dev/null +++ b/tests/supervisor/bootstrap_recovery_reader_independent_test.cpp @@ -0,0 +1,558 @@ +#include "supervisor/bootstrap_recovery_reader.h" +#include "supervisor/bootstrap_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::supervisor; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #condition); \ + std::abort(); \ + } \ +} while (false) + +struct TempRoot { + std::string parent; + std::string root; + TempRoot() { + std::array pattern{}; + const std::string seed = "/tmp/rateguard-recovery-qa-XXXXXX"; + std::copy(seed.begin(), seed.end(), pattern.begin()); + char* made = ::mkdtemp(pattern.data()); + CHECK(made != nullptr); + parent = made; + root = parent + "/runtime"; + } + ~TempRoot() { std::error_code ignored; std::filesystem::remove_all(parent, ignored); } +}; + +BootstrapPlan MakePlan(std::uint8_t epoch_byte = 0x11) { + BootstrapPlan plan; + plan.domain_id.fill(0x10); + plan.epoch_id.fill(epoch_byte); + plan.authority_incarnation.fill(0x22); + plan.policy_digest.fill(0x33); + plan.expected_clock_identity = {}; + plan.expected_clock_identity.boot_uuid.fill(0x44); + plan.expected_clock_identity.namespace_device = 7; + plan.expected_clock_identity.namespace_inode = 9; + plan.expected_clock_identity.monotonic_offset_seconds = 0; + plan.expected_clock_identity.monotonic_offset_nanoseconds = 0; + plan.expected_clock_identity.boottime_offset_seconds = 0; + plan.expected_clock_identity.boottime_offset_nanoseconds = 0; + plan.expected_clock_identity.clock_id = 1; + const auto make = [](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, char suffix) { + PlannedParticipant p; + p.role = role; p.slot_id = slot; p.participant_id = std::move(id); + p.incarnation.fill(incarnation); p.container_id = std::string(63, 'a') + suffix; + return p; + }; + plan.participants = { + make(ParticipantRole::Authority, 0, "authority", 0x22, '1'), + make(ParticipantRole::Replica, 77, "replica", 0x55, '2'), + make(ParticipantRole::Adapter, 0, "adapter", 0x66, '3'), + make(ParticipantRole::Witness, 0, "witness", 0x77, '4'), + }; + return plan; +} + +std::string EpochDirectory(const std::string& root, const EpochId& epoch) { + constexpr char digits[] = "0123456789abcdef"; + std::string hex; + for (auto b : epoch) { hex.push_back(digits[b >> 4]); hex.push_back(digits[b & 15]); } + return root + "/epoch-" + hex; +} + +ObservedBootstrapIdentity Observe(const BootstrapPlan& plan, std::size_t index, std::uint64_t pid) { + return ObservedBootstrapIdentity{plan.participants[index], pid, pid + 1000, + plan.expected_clock_identity}; +} + +std::array Digest(const BootstrapInventory& inventory) { + const auto result = BootstrapDigestV1(inventory); + CHECK((std::holds_alternative>(result))); + return std::get>(result); +} + +// Populate one durable bootstrap inventory, then close all fresh-owner handles +// so the reader receives only an OpenExisting recovery-mode RuntimeOwner. +void CreateArtifacts(const std::string& root, const BootstrapPlan& plan, bool complete = false) { + auto owner_result = RuntimeOwner::CreateNew(root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto store_result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan); + CHECK(store_result.ok()); + CHECK(store_result.visibility == BootstrapVisibility::Durable); + auto store = std::move(store_result.store); + if (complete) { + auto snapshot = store->Snapshot(); + for (std::size_t i = 0; i < plan.participants.size(); ++i) { + auto updated = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, i, 100 + i)); + CHECK(updated.store_error == BootstrapStoreError::None); + CHECK(updated.visibility == BootstrapVisibility::Durable); + snapshot = std::move(updated.snapshot); + } + } + store.reset(); + owner.reset(); +} + +std::unique_ptr OpenRecoveryOwner(const std::string& root, const BootstrapPlan& plan) { + auto opened = RuntimeOwner::OpenExisting(root, plan.domain_id); + CHECK(std::holds_alternative>(opened)); + auto owner = std::move(std::get>(opened)); + CHECK(owner->mode() == RuntimeOwnerMode::RecoveryRequired); + return owner; +} + +std::shared_ptr ReadRecovery(const RuntimeOwner& owner, + IRecoveryReaderIo* hooks = nullptr) { + auto result = BootstrapRecoveryReader::Read(owner, hooks); + CHECK(std::holds_alternative>(result)); + return std::get>(std::move(result)); +} + +bool HasIssue(const std::vector& issues, RecoveryIssueCode code) { + return std::any_of(issues.begin(), issues.end(), [code](const auto& issue) { return issue.code == code; }); +} +bool HasEpochIssue(const RecoveryEpochDiagnostic& epoch, RecoveryIssueCode code) { + return std::find(epoch.issues.begin(), epoch.issues.end(), code) != epoch.issues.end(); +} + +struct FailOne final : IRecoveryReaderIo { + RecoveryReaderIoPoint point; + bool consumed{}; + explicit FailOne(RecoveryReaderIoPoint p) : point(p) {} + bool FailAt(RecoveryReaderIoPoint candidate) noexcept override { + if (!consumed && candidate == point) { consumed = true; return true; } + return false; + } +}; + +struct ActionOnce final : IRecoveryReaderIo { + RecoveryReaderIoPoint point; + bool consumed{}; + std::function action; + ActionOnce(RecoveryReaderIoPoint p, std::function fn) + : point(p), action(std::move(fn)) {} + bool FailAt(RecoveryReaderIoPoint candidate) noexcept override { + if (!consumed && candidate == point) { + consumed = true; + action(); + } + return false; + } +}; + +void WriteInventoryArtifact(const std::string& root, const BootstrapPlan& plan, bool complete, + std::uint64_t pid_base = 100) { + const auto directory = EpochDirectory(root, plan.epoch_id); + CHECK(::mkdir(directory.c_str(), 0700) == 0); + auto model = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(model)); + auto inventory = std::get(std::move(model)); + if (complete) { + for (std::size_t i = 0; i < plan.participants.size(); ++i) + inventory = inventory.RecordIdentity(Observe(plan, i, pid_base + i)).next; + } + auto encoded = EncodeBootstrapInventoryV1(inventory); + CHECK(std::holds_alternative(encoded)); + const auto& bytes = std::get(encoded); + const auto path = directory + "/intent.json"; + std::ofstream out(path, std::ios::binary | std::ios::trunc); + out.write(bytes.data(), static_cast(bytes.size())); + out.close(); + CHECK(out.good()); + CHECK(::chmod(path.c_str(), 0600) == 0); +} + +void TestPendingAndCompleteAreStructuralDiagnosticsOnly() { + for (const bool complete : {false, true}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, complete); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(snapshot->domain_id == plan.domain_id); + CHECK(snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.directory_name == "epoch-11111111111111111111111111111111"); + CHECK(epoch.inventory != nullptr); + CHECK(epoch.canonical_digest.has_value()); + CHECK(epoch.inventory->recorded_count() == (complete ? plan.participants.size() : 0)); + CHECK(epoch.inventory->epoch_id() == plan.epoch_id); + CHECK(epoch.inventory->expected_clock_identity() == plan.expected_clock_identity); + CHECK(snapshot->issues.empty()); + // This type has only diagnostic fields; neither scan_complete nor decoded + // inventory is an EpochCandidate/permission to activate or reset. + } +} + +void TestReaderRequiresRecoveryModeAndDoesNotModifyFiles() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto recovery = OpenRecoveryOwner(temp.root, plan); + const auto dir = EpochDirectory(temp.root, plan.epoch_id); + const auto intent = dir + "/intent.json"; + const auto before = std::filesystem::last_write_time(intent); + std::ifstream in(intent, std::ios::binary); + const std::string bytes((std::istreambuf_iterator(in)), {}); + in.close(); + auto first = ReadRecovery(*recovery); + auto second = ReadRecovery(*recovery); + CHECK(first->scan_complete && second->scan_complete); + CHECK(first->epochs.front().inventory->revision() == second->epochs.front().inventory->revision()); + CHECK(first->epochs.front().canonical_digest == second->epochs.front().canonical_digest); + CHECK(std::filesystem::last_write_time(intent) == before); + std::ifstream after_in(intent, std::ios::binary); + CHECK(std::string((std::istreambuf_iterator(after_in)), {}) == bytes); + + auto fresh_result = RuntimeOwner::CreateNew(temp.parent + "/fresh", plan.domain_id); + CHECK(std::holds_alternative>(fresh_result)); + auto fresh = std::move(std::get>(fresh_result)); + auto rejected = BootstrapRecoveryReader::Read(*fresh); + CHECK(std::holds_alternative(rejected)); + CHECK(std::get(rejected) == RecoveryReaderFatal::OwnerNotRecoveryMode); +} + +void TestUnknownAndTemporaryChildArtifactsPreserveKnownInventory() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + const auto dir = EpochDirectory(temp.root, plan.epoch_id); + { std::ofstream out(dir + "/intent.tmp", std::ios::binary); out << "pending"; } + { std::ofstream out(dir + "/operator-note", std::ios::binary); out << "unknown"; } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().inventory->recorded_count() == plan.participants.size()); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::EpochHasUnexpectedEntry)); +} + +void TestUnknownRootEntryPreservesKnownEpochWithoutExposingRawName() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + { std::ofstream out(temp.root + "/unexpected-secret-label"); out << "x"; } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1 && snapshot->epochs.front().inventory != nullptr); + CHECK(HasIssue(snapshot->issues, RecoveryIssueCode::UnexpectedRootEntry)); + for (const auto& issue : snapshot->issues) { + (void)issue; + } +} + +void TestIssueCapIsBoundedAndKnownIntentIsRetained() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + for (std::size_t i = 0; i < kMaxRecoveryIssues + 8; ++i) { + std::ofstream out(temp.root + "/unexpected-" + std::to_string(i)); + out << "x"; + } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->issues.size() <= kMaxRecoveryIssues); + CHECK(snapshot->issues_truncated); + CHECK(!snapshot->epochs.empty()); + CHECK(snapshot->epochs.front().inventory != nullptr); +} + +void TestRootEntryCapIsBoundedAndKeepsSortedKnownIntent() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + for (std::size_t i = 0; i < kMaxRecoveryRootEntries + 2; ++i) { + std::ofstream out(temp.root + "/overflow-" + std::to_string(i)); + out << "x"; + } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(HasIssue(snapshot->issues, RecoveryIssueCode::TooManyRootEntries)); + CHECK(snapshot->issues.size() <= kMaxRecoveryIssues); + for (const auto& epoch : snapshot->epochs) { + if (epoch.inventory != nullptr) { + CHECK(epoch.canonical_digest.has_value()); + CHECK(epoch.inventory->epoch_id() != EpochId{}); + } + } +} + +void TestEpochDirectoryCapStopsBoundedScan() { + TempRoot temp; + const auto plan = MakePlan(0x70); + CreateArtifacts(temp.root, plan, true); + for (std::uint32_t i = 1; i <= kMaxRecoveryEpochDirectories; ++i) { + EpochId id{}; + id[12] = static_cast((i >> 24) & 0xffU); + id[13] = static_cast((i >> 16) & 0xffU); + id[14] = static_cast((i >> 8) & 0xffU); + id[15] = static_cast(i & 0xffU); + CHECK(::mkdir(EpochDirectory(temp.root, id).c_str(), 0700) == 0); + } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() <= kMaxRecoveryEpochDirectories); + CHECK(snapshot->issues.size() <= kMaxRecoveryIssues); + CHECK(snapshot->issues_truncated); + for (const auto& epoch : snapshot->epochs) + if (epoch.inventory) CHECK(epoch.canonical_digest.has_value()); +} + +void TestAggregateReadByteCapRetainsEarlierValidInventory() { + TempRoot temp; + const auto valid = MakePlan(0x01); // sorts before the malformed large artifacts + CreateArtifacts(temp.root, valid, true); + constexpr std::size_t chunk = kMaxBootstrapBytes; + const auto chunks = kMaxRecoveryAggregateBytes / chunk; + for (std::size_t i = 2; i < 2 + chunks; ++i) { + EpochId id{}; + id.fill(0x02); + id[15] = static_cast(i); + const auto dir = EpochDirectory(temp.root, id); + CHECK(::mkdir(dir.c_str(), 0700) == 0); + const auto intent = dir + "/intent.json"; + { std::ofstream out(intent, std::ios::binary); out.put('{'); } + CHECK(::chmod(intent.c_str(), 0600) == 0); + std::filesystem::resize_file(intent, chunk); + } + auto owner = OpenRecoveryOwner(temp.root, valid); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.back(), RecoveryIssueCode::AggregateByteLimit) || + HasIssue(snapshot->issues, RecoveryIssueCode::AggregateByteLimit)); + CHECK(snapshot->epochs.front().inventory->epoch_id() == valid.epoch_id); +} + +void TestMissingCorruptAndWrongBindingArtifactsAreIncomplete() { + for (const int mode : {0, 1, 2, 3}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + const auto dir = EpochDirectory(temp.root, plan.epoch_id); + const auto intent = dir + "/intent.json"; + if (mode == 0) CHECK(::unlink(intent.c_str()) == 0); + if (mode == 1) { std::ofstream out(intent, std::ios::binary | std::ios::trunc); out << "{"; } + if (mode >= 2) { + auto wrong = MakePlan(mode == 2 ? 0x11 : 0x12); + if (mode == 2) + wrong.domain_id[0] ^= 0x55; + else { + const auto moved = dir + ".moved"; + CHECK(::rename(dir.c_str(), moved.c_str()) == 0); + CHECK(::mkdir(dir.c_str(), 0700) == 0); + } + auto model = BootstrapInventory::Create(wrong); + CHECK(std::holds_alternative(model)); + auto encoded = EncodeBootstrapInventoryV1(std::get(model)); + CHECK(std::holds_alternative(encoded)); + std::ofstream out(intent, std::ios::binary | std::ios::trunc); + const auto& bytes = std::get(encoded); + out.write(bytes.data(), static_cast(bytes.size())); + out.close(); + CHECK(out.good()); + CHECK(::chmod(intent.c_str(), 0600) == 0); + } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + if (mode == 0) { + CHECK(snapshot->epochs.front().inventory == nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::MissingIntent)); + } else if (mode == 1) { + CHECK(snapshot->epochs.front().inventory == nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::InvalidEncoding)); + } else if (mode == 2) { + CHECK(snapshot->epochs.front().inventory == nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::DomainMismatch)); + } else { + CHECK(snapshot->epochs.front().inventory == nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::EpochMismatch)); + } + } +} + +void TestDuplicateContainerAcrossEpochsIsReportedWithoutChoosingLatest() { + TempRoot temp; + const auto first = MakePlan(0x11); + CreateArtifacts(temp.root, first, true); + const auto second = MakePlan(0x12); + WriteInventoryArtifact(temp.root, second, true, 100); // duplicate process and container identities + auto owner = OpenRecoveryOwner(temp.root, first); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 2); + CHECK(snapshot->epochs[0].inventory != nullptr && snapshot->epochs[1].inventory != nullptr); + CHECK(HasEpochIssue(snapshot->epochs[0], RecoveryIssueCode::IdentityCollisionAcrossEpochs) || + HasEpochIssue(snapshot->epochs[1], RecoveryIssueCode::IdentityCollisionAcrossEpochs)); +} + +void TestRootEntryChangesDuringScanAreReported() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto owner = OpenRecoveryOwner(temp.root, plan); + ActionOnce hook(RecoveryReaderIoPoint::EnumerateRootSecond, [&] { + std::ofstream out(temp.root + "/arrived-during-scan"); + out << "x"; + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(HasIssue(snapshot->issues, RecoveryIssueCode::RootChangedDuringScan)); + CHECK(snapshot->epochs.size() == 1 && snapshot->epochs.front().inventory != nullptr); +} + +void TestIntentReplacementDuringReadIsIncomplete() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + const auto intent = EpochDirectory(temp.root, plan.epoch_id) + "/intent.json"; + auto owner = OpenRecoveryOwner(temp.root, plan); + ActionOnce hook(RecoveryReaderIoPoint::RevalidateEntry, [&] { + const auto replacement = intent + ".replacement"; + { std::ofstream out(replacement, std::ios::binary | std::ios::trunc); out << "replacement"; } + CHECK(::chmod(replacement.c_str(), 0600) == 0); + CHECK(::rename(replacement.c_str(), intent.c_str()) == 0); + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory == nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::IntentChanged)); +} + +void TestUnsafeFileTypesDoNotBlockAndPreserveOtherRecords() { + for (const bool use_symlink : {false, true}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + const auto dir = EpochDirectory(temp.root, plan.epoch_id); + const auto intent = dir + "/intent.json"; + CHECK(::unlink(intent.c_str()) == 0); + if (use_symlink) CHECK(::symlink("/etc/passwd", intent.c_str()) == 0); + else CHECK(::mkfifo(intent.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory == nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::InvalidIntentFile)); + } +} + +void TestHardLinkedIntentIsRejected() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + const auto dir = EpochDirectory(temp.root, plan.epoch_id); + CHECK(::link((dir + "/intent.json").c_str(), (dir + "/second-link").c_str()) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory == nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::EpochHasUnexpectedEntry)); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::InvalidIntentFile)); +} + +void TestBoundedChildEntriesRetainDecodedInventory() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + const auto dir = EpochDirectory(temp.root, plan.epoch_id); + for (std::size_t i = 0; i < kMaxRecoveryChildEntries; ++i) { + std::ofstream out(dir + "/extra-" + std::to_string(i)); + out << "x"; + } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::TooManyChildEntries)); + CHECK(snapshot->epochs.front().issues.size() <= kMaxRecoveryEpochIssues); + CHECK(snapshot->epochs.front().issues_truncated); + CHECK(snapshot->issues.size() <= kMaxRecoveryIssues); +} + +void TestReadFaultsNeverProduceCompleteSnapshot() { + const std::array points{ + RecoveryReaderIoPoint::ValidateOwnerBefore, + RecoveryReaderIoPoint::DuplicateRoot, + RecoveryReaderIoPoint::EnumerateRootFirst, + RecoveryReaderIoPoint::EnumerateRootSecond, + RecoveryReaderIoPoint::StatRootEntry, + RecoveryReaderIoPoint::OpenEpochDirectory, + RecoveryReaderIoPoint::EnumerateEpoch, + RecoveryReaderIoPoint::StatIntent, + RecoveryReaderIoPoint::OpenIntent, + RecoveryReaderIoPoint::ReadIntent, + RecoveryReaderIoPoint::RevalidateEntry, + RecoveryReaderIoPoint::ValidateOwnerAfter, + }; + for (const auto point : points) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto owner = OpenRecoveryOwner(temp.root, plan); + FailOne hook(point); + auto result = BootstrapRecoveryReader::Read(*owner, &hook); + CHECK(hook.consumed); + if (std::holds_alternative>(result)) + CHECK(!std::get>(result)->scan_complete); + else + CHECK(std::get(result) != RecoveryReaderFatal::OwnerNotRecoveryMode); + } +} + +} // namespace + +int main() { + TestPendingAndCompleteAreStructuralDiagnosticsOnly(); + TestReaderRequiresRecoveryModeAndDoesNotModifyFiles(); + TestUnknownAndTemporaryChildArtifactsPreserveKnownInventory(); + TestUnknownRootEntryPreservesKnownEpochWithoutExposingRawName(); + TestIssueCapIsBoundedAndKnownIntentIsRetained(); + TestRootEntryCapIsBoundedAndKeepsSortedKnownIntent(); + TestEpochDirectoryCapStopsBoundedScan(); + TestAggregateReadByteCapRetainsEarlierValidInventory(); + TestMissingCorruptAndWrongBindingArtifactsAreIncomplete(); + TestDuplicateContainerAcrossEpochsIsReportedWithoutChoosingLatest(); + TestRootEntryChangesDuringScanAreReported(); + TestIntentReplacementDuringReadIsIncomplete(); + TestUnsafeFileTypesDoNotBlockAndPreserveOtherRecords(); + TestHardLinkedIntentIsRejected(); + TestBoundedChildEntriesRetainDecodedInventory(); + TestReadFaultsNeverProduceCompleteSnapshot(); + return 0; +} diff --git a/tests/supervisor/bootstrap_recovery_reader_test.cpp b/tests/supervisor/bootstrap_recovery_reader_test.cpp new file mode 100644 index 0000000..fc4928b --- /dev/null +++ b/tests/supervisor/bootstrap_recovery_reader_test.cpp @@ -0,0 +1,751 @@ +#include "supervisor/bootstrap_recovery_reader.h" +#include "supervisor/bootstrap_store.h" +#include "supervisor/manifest_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::supervisor; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #condition); \ + std::abort(); \ + } \ +} while (false) + +struct TempRoot final { + std::string parent; + std::string root; + TempRoot() { + std::array pattern{}; + const std::string seed = "/tmp/rateguard-bootstrap-recovery-XXXXXX"; + std::copy(seed.begin(), seed.end(), pattern.begin()); + char* made = ::mkdtemp(pattern.data()); + CHECK(made != nullptr); + parent = made; + root = parent + "/runtime"; + } + ~TempRoot() { std::error_code ignored; std::filesystem::remove_all(parent, ignored); } +}; + +BootstrapPlan MakePlan(std::uint8_t epoch_byte = 0x11) { + BootstrapPlan plan; + plan.domain_id.fill(0x10); + plan.epoch_id.fill(epoch_byte); + plan.authority_incarnation.fill(0x22); + plan.policy_digest.fill(0x33); + plan.expected_clock_identity = {}; + plan.expected_clock_identity.boot_uuid.fill(0x44); + plan.expected_clock_identity.namespace_device = 7; + plan.expected_clock_identity.namespace_inode = 9; + plan.expected_clock_identity.monotonic_offset_seconds = 0; + plan.expected_clock_identity.monotonic_offset_nanoseconds = 0; + plan.expected_clock_identity.boottime_offset_seconds = 0; + plan.expected_clock_identity.boottime_offset_nanoseconds = 0; + plan.expected_clock_identity.clock_id = 1; + const auto make = [](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, char suffix) { + PlannedParticipant p; + p.role = role; + p.slot_id = slot; + p.participant_id = std::move(id); + p.incarnation.fill(incarnation); + p.container_id = std::string(63, 'a') + suffix; + return p; + }; + plan.participants = { + make(ParticipantRole::Authority, 0, "authority", 0x22, '1'), + make(ParticipantRole::Replica, 77, "replica", 0x55, '2'), + make(ParticipantRole::Adapter, 0, "adapter", 0x66, '3'), + make(ParticipantRole::Witness, 0, "witness", 0x77, '4'), + }; + return plan; +} + +ObservedBootstrapIdentity Observe(const BootstrapPlan& plan, std::size_t index, std::uint64_t pid) { + return {plan.participants[index], pid, pid + 1000, plan.expected_clock_identity}; +} + +std::string EpochName(const EpochId& epoch) { + constexpr char digits[] = "0123456789abcdef"; + std::string result = "epoch-"; + for (auto byte : epoch) { + result.push_back(digits[byte >> 4]); + result.push_back(digits[byte & 15]); + } + return result; +} + +void CreateHistory(const std::string& root, const BootstrapPlan& plan, bool record_one = true) { + auto owner_result = RuntimeOwner::CreateNew(root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto store_result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan); + CHECK(store_result.ok() && store_result.visibility == BootstrapVisibility::Durable); + if (record_one) { + const auto initial = store_result.store->Snapshot(); + const auto digest = BootstrapDigestV1(*initial); + CHECK((std::holds_alternative>(digest))); + auto update = store_result.store->RecordIdentity(initial->revision(), + std::get>(digest), Observe(plan, 0, 515)); + CHECK(update.store_error == BootstrapStoreError::None); + CHECK(update.visibility == BootstrapVisibility::Durable); + } + store_result.store.reset(); + owner.reset(); +} + +void CreateReadyHistoryWithManifest(const std::string& root, const BootstrapPlan& plan, + ManifestPhase phase = ManifestPhase::Prepared) { + auto owner_result = RuntimeOwner::CreateNew(root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto boot = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan); + CHECK(boot.ok() && boot.visibility == BootstrapVisibility::Durable); + for (std::size_t i = 0; i < plan.participants.size(); ++i) { + const auto before = boot.store->Snapshot(); + const auto digest = BootstrapDigestV1(*before); + CHECK((std::holds_alternative>(digest))); + const auto update = boot.store->RecordIdentity(before->revision(), + std::get>(digest), Observe(plan, i, 515 + i)); + CHECK(update.store_error == BootstrapStoreError::None); + CHECK(update.visibility == BootstrapVisibility::Durable); + } + const auto ready = boot.store->Snapshot()->ReadyCandidate(); + CHECK(std::holds_alternative(ready)); + const auto manifest_path = root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + OperationId operation{}; + operation.fill(0x90); + auto store_result = ManifestStore::CreateNew(manifest_path, + std::get(ready), operation); + CHECK(std::holds_alternative>(store_result)); + auto manifest = std::move(std::get>(store_result)); + const std::array next_phases{ + ManifestPhase::Active, ManifestPhase::Draining, ManifestPhase::Closed}; + for (const auto next : next_phases) { + if (static_cast(next) <= static_cast(phase)) { + const auto digest = manifest->digest(); + ++operation[0]; + const auto update = manifest->Transition(manifest->snapshot().generation, digest, + next, operation); + CHECK(update.visibility == ManifestVisibility::Durable && !update.error.has_value()); + } + } + manifest.reset(); + boot.store.reset(); + owner.reset(); +} + +std::unique_ptr OpenRecoveryOwner(const TempRoot& temp, const BootstrapPlan& plan) { + auto result = RuntimeOwner::OpenExisting(temp.root, plan.domain_id); + CHECK(std::holds_alternative>(result)); + auto owner = std::move(std::get>(result)); + CHECK(owner->mode() == RuntimeOwnerMode::RecoveryRequired); + CHECK(std::holds_alternative(owner->ValidateOwnership())); + return owner; +} + +bool HasIssue(const BootstrapRecoverySnapshot& snapshot, RecoveryIssueCode wanted) { + if (std::any_of(snapshot.issues.begin(), snapshot.issues.end(), + [&](const auto& issue) { return issue.code == wanted; })) return true; + for (const auto& epoch : snapshot.epochs) + if (std::find(epoch.issues.begin(), epoch.issues.end(), wanted) != epoch.issues.end()) return true; + return false; +} + +struct FailOnce final : IRecoveryReaderIo { + RecoveryReaderIoPoint point; + bool consumed{}; + explicit FailOnce(RecoveryReaderIoPoint p) : point(p) {} + bool FailAt(RecoveryReaderIoPoint candidate) noexcept override { + if (!consumed && candidate == point) { consumed = true; return true; } + return false; + } +}; + +struct MutateIntentAtReadback final : IRecoveryReaderIo { + std::string path; + bool consumed{}; + explicit MutateIntentAtReadback(std::string p) : path(std::move(p)) {} + bool FailAt(RecoveryReaderIoPoint point) noexcept override { + if (consumed || point != RecoveryReaderIoPoint::RevalidateEntry) return false; + consumed = true; + return ::chmod(path.c_str(), 0640) != 0; + } +}; + +struct MutateManifestAtReadback final : IRecoveryReaderIo { + std::string path; + bool consumed{}; + explicit MutateManifestAtReadback(std::string p) : path(std::move(p)) {} + bool FailAt(RecoveryReaderIoPoint point) noexcept override { + if (consumed || point != RecoveryReaderIoPoint::RevalidateManifestFile) return false; + consumed = true; + return ::chmod(path.c_str(), 0640) != 0; + } +}; + +struct CreateManifestStoreAtIntentRevalidation final : IRecoveryReaderIo { + std::string source; + std::string destination; + bool consumed{}; + CreateManifestStoreAtIntentRevalidation(std::string from, std::string to) + : source(std::move(from)), destination(std::move(to)) {} + bool FailAt(RecoveryReaderIoPoint point) noexcept override { + if (consumed || point != RecoveryReaderIoPoint::RevalidateEntry) return false; + consumed = true; + std::error_code error; + std::filesystem::copy(source, destination, std::filesystem::copy_options::recursive, error); + return static_cast(error); + } +}; + +void TestRecoveryScanRetainsPendingRosterAndCanRepeat() { + TempRoot temp; + const auto plan = MakePlan(); + CreateHistory(temp.root, plan, true); // Other planned participants remain pending. + auto owner = OpenRecoveryOwner(temp, plan); + const auto first = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(first)); + const auto snapshot = std::get>(first); + CHECK(snapshot->scan_complete); + CHECK(snapshot->domain_id == plan.domain_id); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].inventory->recorded_count() == 1); + CHECK(snapshot->epochs[0].inventory->records().size() == plan.participants.size()); + + const auto second = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(second)); + const auto repeated = std::get>(second); + CHECK(repeated->scan_complete && repeated->epochs.size() == 1); + CHECK(repeated->epochs[0].inventory->recorded_count() == 1); +} + +void TestUnexpectedSiblingDoesNotHideKnownIntent() { + TempRoot temp; + const auto plan = MakePlan(); + CreateHistory(temp.root, plan); + const auto child = temp.root + "/" + EpochName(plan.epoch_id); + const auto extra = child + "/intent.tmp"; + { std::ofstream out(extra); out << "untrusted partial data"; } + CHECK(::chmod(extra.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1 && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::EpochHasUnexpectedEntry)); +} + +void TestUnknownRootEntryDoesNotHideKnownIntent() { + TempRoot temp; + const auto plan = MakePlan(); + CreateHistory(temp.root, plan); + const auto extra = temp.root + "/unrecognized-entry"; + { std::ofstream out(extra); out << "opaque"; } + CHECK(::chmod(extra.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1 && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::UnexpectedRootEntry)); +} + +void TestEmptyAndMissingIntentRemainUnknown() { + TempRoot empty; + const auto plan = MakePlan(); + auto create_owner = RuntimeOwner::CreateNew(empty.root, plan.domain_id); + CHECK(std::holds_alternative>(create_owner)); + std::get>(create_owner).reset(); + auto empty_owner = OpenRecoveryOwner(empty, plan); + auto empty_result = BootstrapRecoveryReader::Read(*empty_owner); + CHECK(std::holds_alternative>(empty_result)); + const auto empty_snapshot = std::get>(empty_result); + CHECK(!empty_snapshot->scan_complete && empty_snapshot->epochs.empty()); + CHECK(HasIssue(*empty_snapshot, RecoveryIssueCode::NoValidIntents)); + + TempRoot missing; + CreateHistory(missing.root, plan); + const auto intent = missing.root + "/" + EpochName(plan.epoch_id) + "/intent.json"; + CHECK(::unlink(intent.c_str()) == 0); + auto missing_owner = OpenRecoveryOwner(missing, plan); + auto missing_result = BootstrapRecoveryReader::Read(*missing_owner); + CHECK(std::holds_alternative>(missing_result)); + const auto missing_snapshot = std::get>(missing_result); + CHECK(!missing_snapshot->scan_complete); + CHECK(HasIssue(*missing_snapshot, RecoveryIssueCode::MissingIntent)); +} + +void TestWrongModeAndInjectedReadFailure() { + TempRoot temp; + const auto plan = MakePlan(); + auto fresh_result = RuntimeOwner::CreateNew(temp.root, plan.domain_id); + CHECK(std::holds_alternative>(fresh_result)); + auto fresh = std::move(std::get>(fresh_result)); + const auto wrong_mode = BootstrapRecoveryReader::Read(*fresh); + CHECK(std::get(wrong_mode) == RecoveryReaderFatal::OwnerNotRecoveryMode); + fresh.reset(); + + TempRoot history; + CreateHistory(history.root, plan); + auto owner = OpenRecoveryOwner(history, plan); + FailOnce fail(RecoveryReaderIoPoint::ReadIntent); + const auto read_error = BootstrapRecoveryReader::Read(*owner, &fail); + CHECK(std::holds_alternative>(read_error)); + const auto snapshot = std::get>(read_error); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1 && snapshot->epochs[0].inventory == nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::IntentReadFailed)); +} + +void TestPostReadModeChangeIsDetected() { + TempRoot temp; + const auto plan = MakePlan(); + CreateHistory(temp.root, plan); + auto owner = OpenRecoveryOwner(temp, plan); + const auto intent = temp.root + "/" + EpochName(plan.epoch_id) + "/intent.json"; + MutateIntentAtReadback mutate(intent); + const auto result = BootstrapRecoveryReader::Read(*owner, &mutate); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::IntentChanged)); +} + +void TestManifestPhasesAndCandidateBinding() { + for (const auto phase : {ManifestPhase::Prepared, ManifestPhase::Active, + ManifestPhase::Draining, ManifestPhase::Closed}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan, phase); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(snapshot->scan_complete && snapshot->epochs.size() == 1); + CHECK(snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store.has_value()); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest->phase == phase); + CHECK(snapshot->epochs[0].manifest_store->canonical_digest.has_value()); + } + + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto path = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store/manifest.json"; + auto owner = OpenRecoveryOwner(temp, plan); + const auto original = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(original)); + const auto original_snapshot = std::get>(original); + auto mismatched = *original_snapshot->epochs[0].manifest_store->decoded_manifest; + mismatched.candidate.policy_digest[0] ^= 0x5a; + const auto encoded = EncodeManifestV1(mismatched); + CHECK(std::holds_alternative(encoded)); + owner.reset(); + CHECK(::unlink(path.c_str()) == 0); + { std::ofstream output(path, std::ios::binary); output << std::get(encoded); } + CHECK(::chmod(path.c_str(), 0600) == 0); + owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestCandidateMismatch)); +} + +void TestManifestUnknownAndMissingFilesKeepBootstrapInventory() { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto partial = directory + "/manifest.tmp"; + { std::ofstream output(partial); output << "partial"; } + CHECK(::chmod(partial.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestStoreHasUnexpectedEntry)); + owner.reset(); + CHECK(::unlink(partial.c_str()) == 0); + CHECK(::unlink((directory + "/manifest.json").c_str()) == 0); + owner = OpenRecoveryOwner(temp, plan); + result = BootstrapRecoveryReader::Read(*owner); + snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::MissingManifestStoreFile)); +} + +void TestPendingBootstrapDoesNotClaimManifestMismatch() { + TempRoot pending; + TempRoot complete; + const auto plan = MakePlan(); + CreateHistory(pending.root, plan, true); + CreateReadyHistoryWithManifest(complete.root, plan); + const auto source = complete.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto destination = pending.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + std::filesystem::copy(source, destination, std::filesystem::copy_options::recursive); + CHECK(std::filesystem::exists(destination + "/manifest.json")); + auto owner = OpenRecoveryOwner(pending, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestBootstrapNotReady)); + CHECK(!HasIssue(*snapshot, RecoveryIssueCode::ManifestCandidateMismatch)); +} + +void TestManifestMetadataMutationsAndUnsafeObjectsFailClosed() { + { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto manifest = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store/manifest.json"; + auto owner = OpenRecoveryOwner(temp, plan); + MutateManifestAtReadback mutate(manifest); + const auto result = BootstrapRecoveryReader::Read(*owner, &mutate); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestStoreFileChanged)); + } + { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto lock = directory + "/owner.lock"; + CHECK(::unlink(lock.c_str()) == 0); + const auto target = temp.parent + "/safe-empty-lock"; + { std::ofstream output(target); } + CHECK(::chmod(target.c_str(), 0600) == 0); + CHECK(::symlink(target.c_str(), lock.c_str()) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::InvalidManifestStoreFile)); + } + { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto manifest = directory + "/manifest.json"; + CHECK(::unlink(manifest.c_str()) == 0); + CHECK(::mkfifo(manifest.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::InvalidManifestStoreFile)); + } + { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto manifest = directory + "/manifest.json"; + CHECK(::link(manifest.c_str(), (directory + "/extra-link").c_str()) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestStoreHasUnexpectedEntry)); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::InvalidManifestStoreFile)); + } +} + +void TestManifestStoreEntryCapRetainsDecodedManifest() { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + for (std::size_t i = 0; i <= kMaxRecoveryManifestStoreEntries; ++i) { + const auto path = directory + "/extra-" + std::to_string(i); + { std::ofstream output(path); output << "x"; } + CHECK(::chmod(path.c_str(), 0600) == 0); + } + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::TooManyManifestStoreEntries)); +} + +void TestManifestStoreCreatedDuringScanIsExplicitlyUncertain() { + TempRoot pending; + TempRoot complete; + const auto plan = MakePlan(); + CreateHistory(pending.root, plan); + CreateReadyHistoryWithManifest(complete.root, plan); + const auto source = complete.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto destination = pending.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + auto owner = OpenRecoveryOwner(pending, plan); + CreateManifestStoreAtIntentRevalidation create(source, destination); + const auto result = BootstrapRecoveryReader::Read(*owner, &create); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs.size() == 1); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestStoreChanged)); +} + +void TestCrossEpochContainerCollisionIsReported() { + TempRoot temp; + const auto first = MakePlan(0x11); + CreateHistory(temp.root, first); + auto owner = OpenRecoveryOwner(temp, first); + + auto second = MakePlan(0x12); // Deliberately reuse the same planned container IDs. + const auto model = BootstrapInventory::Create(second); + CHECK(std::holds_alternative(model)); + const auto encoded = EncodeBootstrapInventoryV1(std::get(model)); + CHECK(std::holds_alternative(encoded)); + const auto child = temp.root + "/" + EpochName(second.epoch_id); + CHECK(::mkdir(child.c_str(), 0700) == 0); + const auto intent = child + "/intent.json"; + { std::ofstream out(intent, std::ios::binary); out << std::get(encoded); } + CHECK(::chmod(intent.c_str(), 0600) == 0); + + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 2); + CHECK(std::all_of(snapshot->epochs.begin(), snapshot->epochs.end(), + [](const auto& epoch) { return epoch.inventory != nullptr; })); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::IdentityCollisionAcrossEpochs)); +} + + +std::string ContainerId(std::uint8_t epoch_byte, std::uint64_t index) { + constexpr char digits[] = "0123456789abcdef"; + std::string result(46, '0'); + result.push_back(digits[epoch_byte >> 4]); + result.push_back(digits[epoch_byte & 15]); + for (int shift = 60; shift >= 0; shift -= 4) + result.push_back(digits[(index >> shift) & 15]); + CHECK(result.size() == 64); + return result; +} + +BootstrapPlan MakeMaxParticipantPlan(std::uint8_t epoch_byte) { + BootstrapPlan plan = MakePlan(epoch_byte); + plan.participants.clear(); + const auto add = [&](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, std::uint64_t ordinal) { + PlannedParticipant p; + p.role = role; + p.slot_id = slot; + p.participant_id = std::move(id); + p.incarnation.fill(incarnation); + p.container_id = ContainerId(epoch_byte, ordinal); + plan.participants.push_back(std::move(p)); + }; + std::uint64_t ordinal = 0; + add(ParticipantRole::Authority, 0, "authority", 0x22, ordinal++); + for (std::uint32_t slot = 1; slot <= kMaxReplicaSlots; ++slot) + add(ParticipantRole::Replica, slot, "replica-" + std::to_string(slot), + static_cast(0x30 + slot), ordinal++); + for (std::uint32_t n = 0; n < 1014; ++n) + add(ParticipantRole::Adapter, 0, "adapter-" + std::to_string(n), 0x66, ordinal++); + add(ParticipantRole::Witness, 0, "witness", 0x77, ordinal++); + CHECK(plan.participants.size() == kMaxParticipants); + return plan; +} + +BootstrapPlan MakePlanOrdinal(std::uint16_t ordinal) { + BootstrapPlan plan = MakePlan(0x30); + plan.epoch_id.fill(0); + plan.epoch_id[0] = 0x30; + plan.epoch_id[1] = static_cast(ordinal >> 8); + plan.epoch_id[2] = static_cast(ordinal & 0xff); + for (std::size_t index = 0; index < plan.participants.size(); ++index) + plan.participants[index].container_id = ContainerId(0x30, + (static_cast(ordinal) << 32) | index); + return plan; +} + +void CreateOwnerOnly(const std::string& root, const RuntimeDomainId& domain) { + auto result = RuntimeOwner::CreateNew(root, domain); + CHECK(std::holds_alternative>(result)); + std::get>(result).reset(); +} + +void WriteInventoryDirectory(const std::string& root, const BootstrapPlan& plan) { + const auto child = root + "/" + EpochName(plan.epoch_id); + CHECK(::mkdir(child.c_str(), 0700) == 0); + auto model = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(model)); + auto encoded = EncodeBootstrapInventoryV1(std::get(model)); + CHECK(std::holds_alternative(encoded)); + const auto intent = child + "/intent.json"; + { std::ofstream out(intent, std::ios::binary); out << std::get(encoded); } + CHECK(::chmod(intent.c_str(), 0600) == 0); +} + +void WriteRawBytes(const std::string& path, const std::string& bytes) { + std::ofstream out(path, std::ios::binary); + out.write(bytes.data(), static_cast(bytes.size())); + CHECK(out.good()); +} + +struct ManifestReadCounter final : IRecoveryReaderIo { + std::size_t intent_reads{}; + std::size_t manifest_reads{}; + bool FailAt(RecoveryReaderIoPoint point) noexcept override { + if (point == RecoveryReaderIoPoint::ReadIntent) ++intent_reads; + if (point == RecoveryReaderIoPoint::ReadManifestFile) ++manifest_reads; + return false; + } +}; + +void TestAggregateBudgetIncludesManifestAttemptedBytes() { + TempRoot temp; + const auto target = MakePlan(0xf0); + CreateOwnerOnly(temp.root, target.domain_id); + const std::string invalid(kMaxBootstrapBytes, 'x'); + for (std::uint8_t n = 0x10; n < 0x1f; ++n) { + const auto child = temp.root + "/" + EpochName(MakePlan(n).epoch_id); + CHECK(::mkdir(child.c_str(), 0700) == 0); + const auto path = child + "/intent.json"; + WriteRawBytes(path, invalid); + CHECK(::chmod(path.c_str(), 0600) == 0); + } + WriteInventoryDirectory(temp.root, target); + const auto manifest_directory = temp.root + "/" + EpochName(target.epoch_id) + "/manifest-store"; + CHECK(::mkdir(manifest_directory.c_str(), 0700) == 0); + const auto lock = manifest_directory + "/owner.lock"; + WriteRawBytes(lock, ""); + CHECK(::chmod(lock.c_str(), 0600) == 0); + const auto manifest = manifest_directory + "/manifest.json"; + const std::string oversized(kMaxManifestBytes + 1, 'x'); + WriteRawBytes(manifest, oversized); + CHECK(::chmod(manifest.c_str(), 0600) == 0); + + auto owner = OpenRecoveryOwner(temp, target); + ManifestReadCounter counter; + const auto result = BootstrapRecoveryReader::Read(*owner, &counter); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(!snapshot->epochs.empty() && snapshot->epochs.back().inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::AggregateByteLimit)); + CHECK(counter.manifest_reads == 0); // Budget is reserved before the over-cap read. +} + +void TestAggregateParticipantLimitRetainsPriorInventories() { + TempRoot temp; + const auto first = MakeMaxParticipantPlan(0x11); + CreateOwnerOnly(temp.root, first.domain_id); + for (std::uint8_t n = 0x11; n < 0x22; ++n) + WriteInventoryDirectory(temp.root, MakeMaxParticipantPlan(n)); + auto owner = OpenRecoveryOwner(temp, first); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 17); + CHECK(std::count_if(snapshot->epochs.begin(), snapshot->epochs.end(), + [](const auto& epoch) { return epoch.inventory != nullptr; }) == 16); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::AggregateParticipantLimit)); +} + +struct ReadIntentCounter final : IRecoveryReaderIo { + std::size_t reads{}; + bool FailAt(RecoveryReaderIoPoint point) noexcept override { + if (point == RecoveryReaderIoPoint::ReadIntent) ++reads; + return false; + } +}; + +void TestAggregateByteLimitIsReservedBeforeRead() { + TempRoot temp; + const auto valid = MakePlan(0x11); + CreateOwnerOnly(temp.root, valid.domain_id); + WriteInventoryDirectory(temp.root, valid); + const std::string invalid(4U * 1024U * 1024U, 'x'); + for (std::uint8_t n = 0x21; n < 0x31; ++n) { + const auto child = temp.root + "/" + EpochName(MakePlan(n).epoch_id); + CHECK(::mkdir(child.c_str(), 0700) == 0); + const auto intent = child + "/intent.json"; + { std::ofstream out(intent, std::ios::binary); out.write(invalid.data(), static_cast(invalid.size())); } + CHECK(::chmod(intent.c_str(), 0600) == 0); + } + auto owner = OpenRecoveryOwner(temp, valid); + ReadIntentCounter counter; + const auto result = BootstrapRecoveryReader::Read(*owner, &counter); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(!snapshot->epochs.empty() && snapshot->epochs.front().inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::AggregateByteLimit)); + CHECK(counter.reads < 17); // The next over-budget file is rejected before reading. +} + +void TestEpochDirectoryLimitRetainsEarlierInventory() { + TempRoot temp; + const auto valid = MakePlan(0x11); + CreateOwnerOnly(temp.root, valid.domain_id); + WriteInventoryDirectory(temp.root, valid); + for (std::uint16_t n = 0; n < kMaxRecoveryEpochDirectories; ++n) { + const auto plan = MakePlanOrdinal(n); + WriteInventoryDirectory(temp.root, plan); + } + auto owner = OpenRecoveryOwner(temp, valid); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(!snapshot->epochs.empty() && snapshot->epochs.front().inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::TooManyEpochDirectories)); +} + +} // namespace + +int main() { + TestRecoveryScanRetainsPendingRosterAndCanRepeat(); + TestUnexpectedSiblingDoesNotHideKnownIntent(); + TestUnknownRootEntryDoesNotHideKnownIntent(); + TestEmptyAndMissingIntentRemainUnknown(); + TestWrongModeAndInjectedReadFailure(); + TestPostReadModeChangeIsDetected(); + TestManifestPhasesAndCandidateBinding(); + TestManifestUnknownAndMissingFilesKeepBootstrapInventory(); + TestPendingBootstrapDoesNotClaimManifestMismatch(); + TestManifestMetadataMutationsAndUnsafeObjectsFailClosed(); + TestManifestStoreEntryCapRetainsDecodedManifest(); + TestManifestStoreCreatedDuringScanIsExplicitlyUncertain(); + TestAggregateBudgetIncludesManifestAttemptedBytes(); + TestCrossEpochContainerCollisionIsReported(); + TestAggregateParticipantLimitRetainsPriorInventories(); + TestAggregateByteLimitIsReservedBeforeRead(); + TestEpochDirectoryLimitRetainsEarlierInventory(); +} diff --git a/tests/supervisor/bootstrap_store_independent_test.cpp b/tests/supervisor/bootstrap_store_independent_test.cpp new file mode 100644 index 0000000..882f988 --- /dev/null +++ b/tests/supervisor/bootstrap_store_independent_test.cpp @@ -0,0 +1,357 @@ +#include "supervisor/bootstrap_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::supervisor; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #condition); \ + std::abort(); \ + } \ +} while (false) + +struct TempRoot { + std::string parent; + std::string root; + TempRoot() { + std::array pattern{}; + const std::string seed = "/tmp/rateguard-bootstrap-store-XXXXXX"; + std::copy(seed.begin(), seed.end(), pattern.begin()); + char* made = ::mkdtemp(pattern.data()); + CHECK(made != nullptr); + parent = made; + root = parent + "/runtime"; + } + ~TempRoot() { std::error_code ignored; std::filesystem::remove_all(parent, ignored); } +}; + +BootstrapPlan MakePlan() { + BootstrapPlan plan; + plan.domain_id.fill(0x10); + plan.epoch_id.fill(0x11); + plan.authority_incarnation.fill(0x22); + plan.policy_digest.fill(0x33); + plan.expected_clock_identity = {}; + plan.expected_clock_identity.boot_uuid.fill(0x44); + plan.expected_clock_identity.namespace_device = 7; + plan.expected_clock_identity.namespace_inode = 9; + plan.expected_clock_identity.monotonic_offset_seconds = 0; + plan.expected_clock_identity.monotonic_offset_nanoseconds = 0; + plan.expected_clock_identity.boottime_offset_seconds = 0; + plan.expected_clock_identity.boottime_offset_nanoseconds = 0; + plan.expected_clock_identity.clock_id = 1; + const auto make = [](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, char suffix) { + PlannedParticipant p; + p.role = role; p.slot_id = slot; p.participant_id = std::move(id); + p.incarnation.fill(incarnation); p.container_id = std::string(63, 'a') + suffix; + return p; + }; + plan.participants = { + make(ParticipantRole::Authority, 0, "authority", 0x22, '1'), + make(ParticipantRole::Replica, 77, "replica", 0x55, '2'), + make(ParticipantRole::Adapter, 0, "adapter", 0x66, '3'), + make(ParticipantRole::Witness, 0, "witness", 0x77, '4'), + }; + return plan; +} + +struct FailureOnce final : IBootstrapStoreIo { + BootstrapStoreIoPoint point; + std::size_t occurrence; + std::size_t seen{}; + bool consumed{}; + explicit FailureOnce(BootstrapStoreIoPoint p, std::size_t nth = 1) : point(p), occurrence(nth) {} + bool FailAt(BootstrapStoreIoPoint candidate) noexcept override { + if (!consumed && candidate == point && ++seen == occurrence) { consumed = true; return true; } + return false; + } +}; + +struct ActionOnce final : IBootstrapStoreIo { + BootstrapStoreIoPoint point; + std::size_t occurrence; + std::size_t seen{}; + bool consumed{}; + std::function action; + ActionOnce(BootstrapStoreIoPoint p, std::size_t nth, std::function fn) + : point(p), occurrence(nth), action(std::move(fn)) {} + bool FailAt(BootstrapStoreIoPoint candidate) noexcept override { + if (!consumed && candidate == point && ++seen == occurrence) { + consumed = true; + action(); + } + return false; + } +}; + +std::string ReadBytes(const std::string& path) { + std::ifstream in(path, std::ios::binary); + CHECK(in.good()); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +std::unique_ptr OpenStore(const std::string& root, const BootstrapPlan& plan, + IBootstrapStoreIo* io = nullptr) { + auto owner_result = RuntimeOwner::CreateNew(root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto store_result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan, io); + CHECK(store_result.ok()); + CHECK(store_result.visibility == BootstrapVisibility::Durable); + return std::move(store_result.store); +} + +std::array Digest(const BootstrapInventory& inventory) { + const auto result = BootstrapDigestV1(inventory); + CHECK((std::holds_alternative>(result))); + return std::get>(result); +} + +ObservedBootstrapIdentity Observe(const BootstrapPlan& plan, std::size_t index, std::uint64_t pid) { + return ObservedBootstrapIdentity{plan.participants[index], pid, pid + 1000, plan.expected_clock_identity}; +} + +void TestDurableProgressAndReadyCandidate() { + TempRoot temp; + const auto plan = MakePlan(); + auto store = OpenStore(temp.root, plan); + auto snapshot = store->Snapshot(); + CHECK(snapshot != nullptr && snapshot->revision() == 1 && snapshot->recorded_count() == 0); + CHECK(std::holds_alternative(store->ReadyCandidate())); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::IncompleteRoster); + + const auto epoch_name = "epoch-11111111111111111111111111111111"; + const auto intent = temp.root + "/" + epoch_name + "/intent.json"; + struct stat st{}; + CHECK(::stat(intent.c_str(), &st) == 0); + CHECK(S_ISREG(st.st_mode) && (st.st_mode & 07777) == 0600 && st.st_nlink == 1); + + for (std::size_t n = 0; n < plan.participants.size(); ++n) { + const auto expected_revision = snapshot->revision(); + const auto expected_digest = Digest(*snapshot); + const auto updated = store->RecordIdentity(expected_revision, expected_digest, Observe(plan, n, 500 + n)); + CHECK(updated.store_error == BootstrapStoreError::None); + CHECK(updated.visibility == BootstrapVisibility::Durable); + CHECK(updated.transition_status == BootstrapError::None); + CHECK(updated.snapshot->revision() == expected_revision + 1); + snapshot = updated.snapshot; + } + const auto candidate = store->ReadyCandidate(); + CHECK(std::holds_alternative(candidate)); + CHECK(std::get(candidate).participants.size() == 4); + CHECK(std::get(candidate).participants[1].slot_id == 77); + + const auto repeated = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, 0, 500)); + CHECK(repeated.store_error == BootstrapStoreError::None); + CHECK(repeated.visibility == BootstrapVisibility::Durable); + CHECK(repeated.snapshot->revision() == snapshot->revision()); + CHECK(std::holds_alternative(store->ReadyCandidate())); +} + +void TestConflictDoesNotPoisonStore() { + TempRoot temp; + const auto plan = MakePlan(); + auto store = OpenStore(temp.root, plan); + auto snapshot = store->Snapshot(); + auto stale_digest = Digest(*snapshot); + stale_digest[0] ^= 1; + auto conflict = store->RecordIdentity(snapshot->revision(), stale_digest, Observe(plan, 0, 600)); + CHECK(conflict.store_error == BootstrapStoreError::Conflict); + CHECK(conflict.visibility == BootstrapVisibility::NotVisible); + CHECK(conflict.snapshot == snapshot); + CHECK(store->Snapshot()->revision() == 1); + CHECK(store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, 0, 600)).store_error == + BootstrapStoreError::None); +} + +void TestMismatchCanBeDurablyRecordedWithoutBecomingReady() { + TempRoot temp; + const auto plan = MakePlan(); + auto store = OpenStore(temp.root, plan); + const auto before = store->Snapshot(); + auto mismatched = Observe(plan, 0, 840); + mismatched.participant.container_id.back() = 'z'; + const auto update = store->RecordIdentity(before->revision(), Digest(*before), mismatched); + CHECK(update.store_error == BootstrapStoreError::None); + CHECK(update.visibility == BootstrapVisibility::Durable); + CHECK(update.transition_status == BootstrapError::IdentityMismatch); + CHECK(update.snapshot->revision() == before->revision() + 1); + CHECK(update.snapshot->recovery_required()); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::RecoveryRequired); +} + +void TestDurabilityFailureLatchesStoreUnready() { + TempRoot temp; + const auto plan = MakePlan(); + FailureOnce fail(BootstrapStoreIoPoint::SyncChild, 2); + auto store = OpenStore(temp.root, plan, &fail); + auto snapshot = store->Snapshot(); + auto failed = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, 0, 700)); + CHECK(failed.store_error == BootstrapStoreError::DurabilityUncertain); + CHECK(failed.visibility == BootstrapVisibility::VisibleDurabilityUnknown); + CHECK(failed.snapshot == snapshot); + CHECK(store->Snapshot() == snapshot); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::StorageUncertain); +} + +void TestPreRenameFailureIsNotVisibleAndDoesNotPublish() { + TempRoot temp; + const auto plan = MakePlan(); + // CreateNew performs the first WriteTemp; fail the second, during identity + // registration. The old durable manifest must remain the visible state. + FailureOnce fail(BootstrapStoreIoPoint::WriteTemp, 2); + auto store = OpenStore(temp.root, plan, &fail); + const auto before = store->Snapshot(); + const std::string intent = temp.root + "/epoch-11111111111111111111111111111111/intent.json"; + const auto old_bytes = ReadBytes(intent); + const auto update = store->RecordIdentity(before->revision(), Digest(*before), Observe(plan, 0, 810)); + CHECK(update.store_error != BootstrapStoreError::None); + CHECK(update.visibility == BootstrapVisibility::NotVisible); + CHECK(update.snapshot == before); + CHECK(store->Snapshot() == before); + CHECK(ReadBytes(intent) == old_bytes); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::StorageUncertain); +} + +void TestPostRenameUncertaintyLeavesDiskAheadButNeverReady() { + TempRoot temp; + const auto plan = MakePlan(); + // Initial create syncs the child once; the second SyncChild is after the + // registration rename. A failure there means visibility is uncertain. + FailureOnce fail(BootstrapStoreIoPoint::SyncChild, 2); + auto store = OpenStore(temp.root, plan, &fail); + const auto before = store->Snapshot(); + const std::string intent = temp.root + "/epoch-11111111111111111111111111111111/intent.json"; + const auto old_bytes = ReadBytes(intent); + const auto update = store->RecordIdentity(before->revision(), Digest(*before), Observe(plan, 0, 820)); + CHECK(update.store_error == BootstrapStoreError::DurabilityUncertain); + CHECK(update.visibility == BootstrapVisibility::VisibleDurabilityUnknown); + CHECK(update.snapshot == before); + CHECK(store->Snapshot() == before); + const auto disk_bytes = ReadBytes(intent); + CHECK(disk_bytes != old_bytes); // rename was visible, directory durability was not proven + const auto decoded = DecodeBootstrapInventoryV1(disk_bytes); + CHECK(std::holds_alternative(decoded)); + CHECK(std::get(decoded).recorded_count() == 1); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::StorageUncertain); + const auto again = store->RecordIdentity(before->revision(), Digest(*before), Observe(plan, 0, 820)); + CHECK(again.store_error == BootstrapStoreError::StorageUncertain); + CHECK(again.visibility == BootstrapVisibility::VisibleDurabilityUnknown); +} + +void TestCreateNewDoesNotPublishOnPostRenameUncertainty() { + TempRoot temp; + const auto plan = MakePlan(); + auto owner_result = RuntimeOwner::CreateNew(temp.root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + // CreateNew's initial intent is the first child sync. The second sync + // failure occurs after rename, so no usable store handle may escape. + FailureOnce fail(BootstrapStoreIoPoint::SyncChild, 1); + auto result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan, &fail); + CHECK(!result.ok()); + CHECK(result.store == nullptr); + CHECK(result.visibility == BootstrapVisibility::VisibleDurabilityUnknown); + CHECK(result.error == BootstrapStoreError::DurabilityUncertain); +} + +void TestExistingIntentReplacementRaceIsNotOverwritten() { + TempRoot temp; + const auto plan = MakePlan(); + const std::string intent = temp.root + "/epoch-11111111111111111111111111111111/intent.json"; + ActionOnce replace(BootstrapStoreIoPoint::RenameTemp, 2, [&] { + const std::string external = "external replacement survives"; + const auto replacement = intent + ".external"; + { + std::ofstream out(replacement, std::ios::binary | std::ios::trunc); + out.write(external.data(), static_cast(external.size())); + out.close(); + } + CHECK(::chmod(replacement.c_str(), 0600) == 0); + CHECK(::rename(replacement.c_str(), intent.c_str()) == 0); + }); + auto store = OpenStore(temp.root, plan, &replace); + const auto before = store->Snapshot(); + const auto update = store->RecordIdentity(before->revision(), Digest(*before), Observe(plan, 0, 830)); + CHECK(replace.consumed); + CHECK(update.visibility == BootstrapVisibility::NotVisible); + CHECK(update.store_error == BootstrapStoreError::StorageUncertain); + CHECK(update.snapshot == before); + CHECK(ReadBytes(intent) == "external replacement survives"); + CHECK(store->Snapshot() == before); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::StorageUncertain); +} + +void TestInitialIntentAppearingBeforePublishIsNeverOverwritten() { + TempRoot temp; + const auto plan = MakePlan(); + auto owner_result = RuntimeOwner::CreateNew(temp.root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + const std::string intent = temp.root + "/epoch-11111111111111111111111111111111/intent.json"; + const std::string external = "intent installed by competing publisher"; + ActionOnce install(BootstrapStoreIoPoint::RenameTemp, 1, [&] { + std::ofstream out(intent, std::ios::binary | std::ios::trunc); + out.write(external.data(), static_cast(external.size())); + out.close(); + CHECK(out.good()); + CHECK(::chmod(intent.c_str(), 0600) == 0); + }); + auto result = BootstrapStore::CreateNew( + std::move(std::get(claim_result)), plan, &install); + CHECK(install.consumed); + CHECK(!result.ok()); + CHECK(result.store == nullptr); + CHECK(result.visibility == BootstrapVisibility::NotVisible); + CHECK(result.error == BootstrapStoreError::InvalidIntent); + CHECK(ReadBytes(intent) == external); +} + +void TestInvalidClaimBindingAndNoExistingChildReuse() { + TempRoot temp; + const auto plan = MakePlan(); + auto owner_result = RuntimeOwner::CreateNew(temp.root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto wrong = plan; + wrong.epoch_id[0] ^= 0x10; + auto mismatch = BootstrapStore::CreateNew(std::move(std::get(claim_result)), wrong); + CHECK(mismatch.error == BootstrapStoreError::EpochMismatch); +} + +} // namespace + +int main() { + TestDurableProgressAndReadyCandidate(); + TestConflictDoesNotPoisonStore(); + TestMismatchCanBeDurablyRecordedWithoutBecomingReady(); + TestDurabilityFailureLatchesStoreUnready(); + TestPreRenameFailureIsNotVisibleAndDoesNotPublish(); + TestPostRenameUncertaintyLeavesDiskAheadButNeverReady(); + TestCreateNewDoesNotPublishOnPostRenameUncertainty(); + TestExistingIntentReplacementRaceIsNotOverwritten(); + TestInitialIntentAppearingBeforePublishIsNeverOverwritten(); + TestInvalidClaimBindingAndNoExistingChildReuse(); + return 0; +} diff --git a/tests/supervisor/bootstrap_store_test.cpp b/tests/supervisor/bootstrap_store_test.cpp new file mode 100644 index 0000000..ee3f840 --- /dev/null +++ b/tests/supervisor/bootstrap_store_test.cpp @@ -0,0 +1,281 @@ +#include "supervisor/bootstrap_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::supervisor; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #condition); \ + std::abort(); \ + } \ +} while (false) + +struct TempRoot { + std::string parent; + std::string root; + TempRoot() { + std::array pattern{}; + const std::string seed = "/tmp/rateguard-bootstrap-store-XXXXXX"; + std::copy(seed.begin(), seed.end(), pattern.begin()); + char* made = ::mkdtemp(pattern.data()); + CHECK(made != nullptr); + parent = made; + root = parent + "/runtime"; + } + ~TempRoot() { std::error_code ignored; std::filesystem::remove_all(parent, ignored); } +}; + +BootstrapPlan MakePlan() { + BootstrapPlan plan; + plan.domain_id.fill(0x10); + plan.epoch_id.fill(0x11); + plan.authority_incarnation.fill(0x22); + plan.policy_digest.fill(0x33); + plan.expected_clock_identity = {}; + plan.expected_clock_identity.boot_uuid.fill(0x44); + plan.expected_clock_identity.namespace_device = 7; + plan.expected_clock_identity.namespace_inode = 9; + plan.expected_clock_identity.monotonic_offset_seconds = 0; + plan.expected_clock_identity.monotonic_offset_nanoseconds = 0; + plan.expected_clock_identity.boottime_offset_seconds = 0; + plan.expected_clock_identity.boottime_offset_nanoseconds = 0; + plan.expected_clock_identity.clock_id = 1; + const auto make = [](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, char suffix) { + PlannedParticipant p; + p.role = role; p.slot_id = slot; p.participant_id = std::move(id); + p.incarnation.fill(incarnation); p.container_id = std::string(63, 'a') + suffix; + return p; + }; + plan.participants = { + make(ParticipantRole::Authority, 0, "authority", 0x22, '1'), + make(ParticipantRole::Replica, 77, "replica", 0x55, '2'), + make(ParticipantRole::Adapter, 0, "adapter", 0x66, '3'), + make(ParticipantRole::Witness, 0, "witness", 0x77, '4'), + }; + return plan; +} + +struct FailureOnce final : IBootstrapStoreIo { + BootstrapStoreIoPoint point; + std::size_t occurrence; + std::size_t seen{}; + bool consumed{}; + explicit FailureOnce(BootstrapStoreIoPoint p, std::size_t nth = 1) : point(p), occurrence(nth) {} + bool FailAt(BootstrapStoreIoPoint candidate) noexcept override { + if (!consumed && candidate == point && ++seen == occurrence) { consumed = true; return true; } + return false; + } +}; + +struct ReplaceAtRename final : IBootstrapStoreIo { + std::string path; + std::size_t target_occurrence; + std::size_t seen{}; + explicit ReplaceAtRename(std::string file, std::size_t occurrence) + : path(std::move(file)), target_occurrence(occurrence) {} + bool FailAt(BootstrapStoreIoPoint point) noexcept override { + if (point != BootstrapStoreIoPoint::RenameTemp) return false; + if (++seen != target_occurrence) return false; + try { + std::ofstream output(path, std::ios::binary | std::ios::trunc); + output << "external replacement"; + output.close(); + return false; // Simulate a concurrent edit without forcing the hook itself to fail. + } catch (...) { return true; } + } +}; + +std::unique_ptr OpenStore(const std::string& root, const BootstrapPlan& plan, + IBootstrapStoreIo* io = nullptr) { + auto owner_result = RuntimeOwner::CreateNew(root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto store_result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan, io); + CHECK(store_result.ok()); + CHECK(store_result.visibility == BootstrapVisibility::Durable); + return std::move(store_result.store); +} + +std::array Digest(const BootstrapInventory& inventory) { + const auto result = BootstrapDigestV1(inventory); + CHECK((std::holds_alternative>(result))); + return std::get>(result); +} + +ObservedBootstrapIdentity Observe(const BootstrapPlan& plan, std::size_t index, std::uint64_t pid) { + return ObservedBootstrapIdentity{plan.participants[index], pid, pid + 1000, plan.expected_clock_identity}; +} + +void TestDurableProgressAndReadyCandidate() { + TempRoot temp; + const auto plan = MakePlan(); + auto store = OpenStore(temp.root, plan); + auto snapshot = store->Snapshot(); + CHECK(snapshot != nullptr && snapshot->revision() == 1 && snapshot->recorded_count() == 0); + CHECK(std::holds_alternative(store->ReadyCandidate())); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::IncompleteRoster); + + const auto epoch_name = "epoch-11111111111111111111111111111111"; + const auto intent = temp.root + "/" + epoch_name + "/intent.json"; + struct stat st{}; + CHECK(::stat(intent.c_str(), &st) == 0); + CHECK(S_ISREG(st.st_mode) && (st.st_mode & 07777) == 0600 && st.st_nlink == 1); + + for (std::size_t n = 0; n < plan.participants.size(); ++n) { + const auto expected_revision = snapshot->revision(); + const auto expected_digest = Digest(*snapshot); + const auto updated = store->RecordIdentity(expected_revision, expected_digest, Observe(plan, n, 500 + n)); + CHECK(updated.store_error == BootstrapStoreError::None); + CHECK(updated.visibility == BootstrapVisibility::Durable); + CHECK(updated.transition_status == BootstrapError::None); + CHECK(updated.snapshot->revision() == expected_revision + 1); + snapshot = updated.snapshot; + } + const auto candidate = store->ReadyCandidate(); + CHECK(std::holds_alternative(candidate)); + CHECK(std::get(candidate).participants.size() == 4); + CHECK(std::get(candidate).participants[1].slot_id == 77); + + const auto repeated = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, 0, 500)); + CHECK(repeated.store_error == BootstrapStoreError::None); + CHECK(repeated.visibility == BootstrapVisibility::Durable); + CHECK(repeated.snapshot->revision() == snapshot->revision()); + CHECK(std::holds_alternative(store->ReadyCandidate())); +} + +void TestConflictDoesNotPoisonStore() { + TempRoot temp; + const auto plan = MakePlan(); + auto store = OpenStore(temp.root, plan); + auto snapshot = store->Snapshot(); + auto stale_digest = Digest(*snapshot); + stale_digest[0] ^= 1; + auto conflict = store->RecordIdentity(snapshot->revision(), stale_digest, Observe(plan, 0, 600)); + CHECK(conflict.store_error == BootstrapStoreError::Conflict); + CHECK(conflict.visibility == BootstrapVisibility::NotVisible); + CHECK(conflict.snapshot == snapshot); + CHECK(store->Snapshot()->revision() == 1); + CHECK(store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, 0, 600)).store_error == + BootstrapStoreError::None); +} + +void TestDurabilityFailureLatchesStoreUnready() { + TempRoot temp; + const auto plan = MakePlan(); + FailureOnce fail(BootstrapStoreIoPoint::SyncChild, 2); + auto store = OpenStore(temp.root, plan, &fail); + auto snapshot = store->Snapshot(); + auto failed = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, 0, 700)); + CHECK(failed.store_error == BootstrapStoreError::DurabilityUncertain); + CHECK(failed.visibility == BootstrapVisibility::VisibleDurabilityUnknown); + CHECK(failed.snapshot == snapshot); + CHECK(store->Snapshot() == snapshot); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::StorageUncertain); +} + +void TestPreRenameFailureIsNotVisibleAndLatches() { + TempRoot temp; + const auto plan = MakePlan(); + FailureOnce fail(BootstrapStoreIoPoint::WriteTemp, 2); + auto store = OpenStore(temp.root, plan, &fail); + auto snapshot = store->Snapshot(); + auto failed = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, 0, 800)); + CHECK(failed.store_error == BootstrapStoreError::IoFailure); + CHECK(failed.visibility == BootstrapVisibility::NotVisible); + CHECK(failed.snapshot == snapshot); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::StorageUncertain); +} + +void TestInvalidClaimBindingAndNoExistingChildReuse() { + TempRoot temp; + const auto plan = MakePlan(); + auto owner_result = RuntimeOwner::CreateNew(temp.root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto wrong = plan; + wrong.epoch_id[0] ^= 0x10; + auto mismatch = BootstrapStore::CreateNew(std::move(std::get(claim_result)), wrong); + CHECK(mismatch.error == BootstrapStoreError::EpochMismatch); +} + +void TestPreexistingEpochChildIsNeverReused() { + TempRoot temp; + const auto plan = MakePlan(); + auto owner_result = RuntimeOwner::CreateNew(temp.root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + const auto child = temp.root + "/epoch-11111111111111111111111111111111"; + CHECK(std::filesystem::create_directory(child)); + auto result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan); + CHECK(result.error == BootstrapStoreError::ExistingEpoch); + CHECK(result.visibility == BootstrapVisibility::NotVisible); +} + +void TestInitialIntentAppearingBeforePublishIsNotOverwritten() { + TempRoot temp; + const auto plan = MakePlan(); + auto owner_result = RuntimeOwner::CreateNew(temp.root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + const auto child = temp.root + "/epoch-11111111111111111111111111111111"; + const auto intent = child + "/intent.json"; + ReplaceAtRename mutate(intent, 1); + auto result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan, &mutate); + CHECK(!result.ok()); + CHECK(result.visibility == BootstrapVisibility::NotVisible); + CHECK(result.error == BootstrapStoreError::InvalidIntent); + std::ifstream input(intent, std::ios::binary); + const std::string contents((std::istreambuf_iterator(input)), {}); + CHECK(contents == "external replacement"); +} + +void TestExistingIntentChangedBeforeReplaceIsPreserved() { + TempRoot temp; + const auto plan = MakePlan(); + const auto child = temp.root + "/epoch-11111111111111111111111111111111"; + const auto intent = child + "/intent.json"; + ReplaceAtRename mutate(intent, 2); // First rename point is initial intent publication. + auto store = OpenStore(temp.root, plan, &mutate); + const auto snapshot = store->Snapshot(); + const auto update = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, 0, 900)); + CHECK(update.visibility == BootstrapVisibility::NotVisible); + CHECK(update.store_error == BootstrapStoreError::StorageUncertain); + CHECK(update.snapshot == snapshot); + std::ifstream input(intent, std::ios::binary); + const std::string contents((std::istreambuf_iterator(input)), {}); + CHECK(contents == "external replacement"); + CHECK(std::get(store->ReadyCandidate()) == BootstrapStoreError::StorageUncertain); +} + +} // namespace + +int main() { + TestDurableProgressAndReadyCandidate(); + TestConflictDoesNotPoisonStore(); + TestDurabilityFailureLatchesStoreUnready(); + TestPreRenameFailureIsNotVisibleAndLatches(); + TestInvalidClaimBindingAndNoExistingChildReuse(); + TestPreexistingEpochChildIsNeverReused(); + TestInitialIntentAppearingBeforePublishIsNotOverwritten(); + TestExistingIntentChangedBeforeReplaceIsPreserved(); + return 0; +} diff --git a/tests/supervisor/epoch_artifact_integration_independent_test.cpp b/tests/supervisor/epoch_artifact_integration_independent_test.cpp new file mode 100644 index 0000000..9ea57e9 --- /dev/null +++ b/tests/supervisor/epoch_artifact_integration_independent_test.cpp @@ -0,0 +1,709 @@ +#include "supervisor/bootstrap_recovery_reader.h" +#include "supervisor/bootstrap_store.h" +#include "supervisor/manifest_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::supervisor; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #condition); \ + std::abort(); \ + } \ +} while (false) + +struct TempRoot { + std::string parent; + std::string root; + TempRoot() { + std::array pattern{}; + const std::string seed = "/tmp/rateguard-recovery-qa-XXXXXX"; + std::copy(seed.begin(), seed.end(), pattern.begin()); + char* made = ::mkdtemp(pattern.data()); + CHECK(made != nullptr); + parent = made; + root = parent + "/runtime"; + } + ~TempRoot() { std::error_code ignored; std::filesystem::remove_all(parent, ignored); } +}; + +BootstrapPlan MakePlan(std::uint8_t epoch_byte = 0x11) { + BootstrapPlan plan; + plan.domain_id.fill(0x10); + plan.epoch_id.fill(epoch_byte); + plan.authority_incarnation.fill(0x22); + plan.policy_digest.fill(0x33); + plan.expected_clock_identity = {}; + plan.expected_clock_identity.boot_uuid.fill(0x44); + plan.expected_clock_identity.namespace_device = 7; + plan.expected_clock_identity.namespace_inode = 9; + plan.expected_clock_identity.monotonic_offset_seconds = 0; + plan.expected_clock_identity.monotonic_offset_nanoseconds = 0; + plan.expected_clock_identity.boottime_offset_seconds = 0; + plan.expected_clock_identity.boottime_offset_nanoseconds = 0; + plan.expected_clock_identity.clock_id = 1; + const auto make = [](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, char suffix) { + PlannedParticipant p; + p.role = role; p.slot_id = slot; p.participant_id = std::move(id); + p.incarnation.fill(incarnation); p.container_id = std::string(63, 'a') + suffix; + return p; + }; + plan.participants = { + make(ParticipantRole::Authority, 0, "authority", 0x22, '1'), + make(ParticipantRole::Replica, 77, "replica", 0x55, '2'), + make(ParticipantRole::Adapter, 0, "adapter", 0x66, '3'), + make(ParticipantRole::Witness, 0, "witness", 0x77, '4'), + }; + return plan; +} + +BootstrapPlan MakeLargePlan(std::uint8_t epoch_byte, std::size_t participant_count, + std::uint64_t container_base) { + BootstrapPlan plan = MakePlan(epoch_byte); + plan.participants.clear(); + constexpr char hex[] = "0123456789abcdef"; + auto add = [&](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, std::size_t local_index) { + PlannedParticipant p; + p.role = role; + p.slot_id = slot; + p.participant_id = std::move(id); + p.incarnation.fill(incarnation); + p.container_id.assign(64, '0'); + const auto unique = container_base + local_index; + for (std::size_t n = 0; n < 16; ++n) { + const auto shift = static_cast((15 - n) * 4); + p.container_id[48 + n] = hex[(unique >> shift) & 0xfU]; + } + plan.participants.push_back(std::move(p)); + }; + add(ParticipantRole::Authority, 0, "authority", 0x22, 0); + for (std::uint32_t i = 0; i < 8; ++i) + add(ParticipantRole::Replica, i, "replica-" + std::to_string(i), 0x55, 1 + i); + const std::size_t adapter_count = participant_count - 10; + for (std::size_t i = 0; i < adapter_count; ++i) + add(ParticipantRole::Adapter, 0, "adapter-" + std::to_string(i), 0x66, 9 + i); + add(ParticipantRole::Witness, 0, "witness", 0x77, 9 + adapter_count); + CHECK(plan.participants.size() == participant_count); + return plan; +} + +std::string EpochDirectory(const std::string& root, const EpochId& epoch) { + constexpr char digits[] = "0123456789abcdef"; + std::string hex; + for (auto b : epoch) { hex.push_back(digits[b >> 4]); hex.push_back(digits[b & 15]); } + return root + "/epoch-" + hex; +} + +ObservedBootstrapIdentity Observe(const BootstrapPlan& plan, std::size_t index, std::uint64_t pid) { + return ObservedBootstrapIdentity{plan.participants[index], pid, pid + 1000, + plan.expected_clock_identity}; +} + +std::array Digest(const BootstrapInventory& inventory) { + const auto result = BootstrapDigestV1(inventory); + CHECK((std::holds_alternative>(result))); + return std::get>(result); +} + +OperationId Operation(std::uint8_t value) { + OperationId id{}; + id.fill(value); + return id; +} + +EpochCandidate CandidateFor(const BootstrapPlan& plan, std::uint64_t pid_base = 100) { + auto result = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(result)); + auto inventory = std::get(std::move(result)); + for (std::size_t i = 0; i < plan.participants.size(); ++i) + inventory = inventory.RecordIdentity(Observe(plan, i, pid_base + i)).next; + auto candidate = inventory.ReadyCandidate(); + CHECK(std::holds_alternative(candidate)); + return std::get(std::move(candidate)); +} + +void CreateLayoutWithInventoryAndManifest(const std::string& root, const BootstrapPlan& plan, + std::uint64_t pid_base, std::uint8_t operation_byte) { + auto created = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(created)); + auto inventory = std::get(std::move(created)); + for (std::size_t i = 0; i < plan.participants.size(); ++i) + inventory = inventory.RecordIdentity(Observe(plan, i, pid_base + i)).next; + auto ready = inventory.ReadyCandidate(); + CHECK(std::holds_alternative(ready)); + auto encoded = EncodeBootstrapInventoryV1(inventory); + CHECK(std::holds_alternative(encoded)); + const auto epoch_dir = EpochDirectory(root, plan.epoch_id); + CHECK(::mkdir(epoch_dir.c_str(), 0700) == 0); + const auto intent = epoch_dir + "/intent.json"; + { + std::ofstream out(intent, std::ios::binary); + const auto& bytes = std::get(encoded); + out.write(bytes.data(), static_cast(bytes.size())); + } + CHECK(::chmod(intent.c_str(), 0600) == 0); + const auto manifest_dir = epoch_dir + "/manifest-store"; + auto operation = Operation(operation_byte); + auto manifest = ManifestStore::CreateNew(manifest_dir, std::get(ready), operation); + CHECK(std::holds_alternative>(manifest)); +} + +std::unique_ptr CreateManifestAt(const std::string& root, + const BootstrapPlan& plan, + ManifestPhase phase = ManifestPhase::Prepared, + bool alter_policy = false, + bool alter_epoch = false, + bool alter_identity = false) { + auto candidate = CandidateFor(plan); + if (alter_policy) candidate.policy_digest[0] ^= 0xff; + if (alter_epoch) candidate.epoch_id[0] ^= 0x80; + if (alter_identity) candidate.participants.front().process.container_id.back() = 'f'; + const auto path = EpochDirectory(root, plan.epoch_id) + "/manifest-store"; + auto result = ManifestStore::CreateNew(path, candidate, Operation(0x81)); + CHECK(std::holds_alternative>(result)); + auto store = std::move(std::get>(result)); + std::uint8_t op = 0x82; + while (store->snapshot().phase != phase) { + const auto current = store->snapshot(); + ManifestPhase next{}; + switch (current.phase) { + case ManifestPhase::Prepared: next = ManifestPhase::Active; break; + case ManifestPhase::Active: next = ManifestPhase::Draining; break; + case ManifestPhase::Draining: next = ManifestPhase::Closed; break; + case ManifestPhase::Closed: CHECK(false); break; + } + const auto updated = store->Transition(current.generation, store->digest(), next, Operation(op++)); + CHECK(updated.visibility == ManifestVisibility::Durable); + CHECK(!updated.error.has_value()); + } + return store; +} + +// Populate one durable bootstrap inventory, then close all fresh-owner handles +// so the reader receives only an OpenExisting recovery-mode RuntimeOwner. +void CreateArtifacts(const std::string& root, const BootstrapPlan& plan, bool complete = false) { + auto owner_result = RuntimeOwner::CreateNew(root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto store_result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan); + CHECK(store_result.ok()); + CHECK(store_result.visibility == BootstrapVisibility::Durable); + auto store = std::move(store_result.store); + if (complete) { + auto snapshot = store->Snapshot(); + for (std::size_t i = 0; i < plan.participants.size(); ++i) { + auto updated = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, i, 100 + i)); + CHECK(updated.store_error == BootstrapStoreError::None); + CHECK(updated.visibility == BootstrapVisibility::Durable); + snapshot = std::move(updated.snapshot); + } + } + store.reset(); + owner.reset(); +} + +std::unique_ptr OpenRecoveryOwner(const std::string& root, const BootstrapPlan& plan) { + auto opened = RuntimeOwner::OpenExisting(root, plan.domain_id); + CHECK(std::holds_alternative>(opened)); + auto owner = std::move(std::get>(opened)); + CHECK(owner->mode() == RuntimeOwnerMode::RecoveryRequired); + return owner; +} + +std::shared_ptr ReadRecovery(const RuntimeOwner& owner, + IRecoveryReaderIo* hooks = nullptr) { + auto result = BootstrapRecoveryReader::Read(owner, hooks); + CHECK(std::holds_alternative>(result)); + return std::get>(std::move(result)); +} + +bool HasIssue(const std::vector& issues, RecoveryIssueCode code) { + return std::any_of(issues.begin(), issues.end(), [code](const auto& issue) { return issue.code == code; }); +} +bool HasEpochIssue(const RecoveryEpochDiagnostic& epoch, RecoveryIssueCode code) { + return std::find(epoch.issues.begin(), epoch.issues.end(), code) != epoch.issues.end(); +} + +struct FailOne final : IRecoveryReaderIo { + RecoveryReaderIoPoint point; + bool consumed{}; + explicit FailOne(RecoveryReaderIoPoint p) : point(p) {} + bool FailAt(RecoveryReaderIoPoint candidate) noexcept override { + if (!consumed && candidate == point) { consumed = true; return true; } + return false; + } +}; + +struct ActionOnce final : IRecoveryReaderIo { + RecoveryReaderIoPoint point; + bool consumed{}; + std::function action; + ActionOnce(RecoveryReaderIoPoint p, std::function fn) + : point(p), action(std::move(fn)) {} + bool FailAt(RecoveryReaderIoPoint candidate) noexcept override { + if (!consumed && candidate == point) { + consumed = true; + action(); + } + return false; + } +}; + +void TestManifestStoreIsOptionalAndAllPhasesAreDiagnostic() { + { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(!snapshot->epochs.front().manifest_store.has_value()); + } + for (const auto phase : {ManifestPhase::Prepared, ManifestPhase::Active, + ManifestPhase::Draining, ManifestPhase::Closed}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan, phase); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.inventory != nullptr); + CHECK(epoch.manifest_store.has_value()); + CHECK(epoch.manifest_store->decoded_manifest != nullptr); + CHECK(epoch.manifest_store->canonical_digest.has_value()); + CHECK(epoch.manifest_store->decoded_manifest->phase == phase); + CHECK(epoch.manifest_store->decoded_manifest->candidate.epoch_id == plan.epoch_id); + CHECK(epoch.manifest_store->decoded_manifest->candidate.policy_digest == plan.policy_digest); + CHECK(!HasEpochIssue(epoch, RecoveryIssueCode::IdentityCollisionAcrossEpochs)); + // A readable manifest phase is historical data. It does not activate, + // adopt, close, or otherwise authorize the recovery-mode runtime. + (void)manifest_store; + } +} + +void TestValidManifestSurvivesPendingOrInvalidBootstrapIntent() { + for (const int kind : {0, 1, 2}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, kind != 0); + auto manifest_store = CreateManifestAt(temp.root, plan, ManifestPhase::Active); + const auto intent = EpochDirectory(temp.root, plan.epoch_id) + "/intent.json"; + if (kind == 1) { std::ofstream out(intent, std::ios::binary | std::ios::trunc); out << "invalid"; } + if (kind == 2) CHECK(::unlink(intent.c_str()) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete || kind == 0); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.manifest_store.has_value()); + CHECK(epoch.manifest_store->decoded_manifest != nullptr); + CHECK(epoch.manifest_store->decoded_manifest->phase == ManifestPhase::Active); + if (kind == 0) { + CHECK(epoch.inventory != nullptr); + CHECK(epoch.inventory->recorded_count() == 0); + CHECK(!HasEpochIssue(epoch, RecoveryIssueCode::ManifestCandidateMismatch)); + CHECK(HasEpochIssue(epoch, RecoveryIssueCode::ManifestBootstrapNotReady)); + } else { + CHECK(epoch.inventory == nullptr); + CHECK(HasEpochIssue(epoch, kind == 1 ? RecoveryIssueCode::InvalidEncoding + : RecoveryIssueCode::MissingIntent)); + } + (void)manifest_store; + } +} + +void TestManifestCandidateMismatchIsReportedButDecodedDataIsKept() { + for (const int field : {0, 1, 2}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan, ManifestPhase::Closed, + field == 0, field == 1, field == 2); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.inventory != nullptr); + CHECK(epoch.manifest_store.has_value()); + CHECK(epoch.manifest_store->decoded_manifest != nullptr); + CHECK(epoch.manifest_store->decoded_manifest->phase == ManifestPhase::Closed); + CHECK(HasEpochIssue(epoch, RecoveryIssueCode::ManifestCandidateMismatch)); + if (field == 0) + CHECK(epoch.manifest_store->decoded_manifest->candidate.policy_digest[0] != plan.policy_digest[0]); + if (field == 1) + CHECK(epoch.manifest_store->decoded_manifest->candidate.epoch_id != plan.epoch_id); + if (field == 2) + CHECK(epoch.manifest_store->decoded_manifest->candidate.participants.front().process.container_id != + plan.participants.front().container_id); + (void)manifest_store; + } +} + +void TestInvalidManifestArtifactsDoNotHideBootstrapInventory() { + for (const int mode : {0, 1, 2, 3, 4}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + if (mode == 0) CHECK(::unlink((dir + "/owner.lock").c_str()) == 0); + if (mode == 1) CHECK(::unlink((dir + "/manifest.json").c_str()) == 0); + if (mode == 2) { std::ofstream out(dir + "/manifest.tmp"); out << "pending"; } + if (mode == 3 || mode == 4) CHECK(::unlink((dir + "/manifest.json").c_str()) == 0); + if (mode == 3) CHECK(::symlink("/etc/passwd", (dir + "/manifest.json").c_str()) == 0); + if (mode == 4) CHECK(::mkfifo((dir + "/manifest.json").c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.inventory != nullptr); + CHECK(epoch.manifest_store.has_value()); + if (mode == 0 || mode == 2) { + CHECK(epoch.manifest_store->decoded_manifest != nullptr); + if (mode == 2) CHECK(HasEpochIssue(epoch, RecoveryIssueCode::ManifestStoreHasUnexpectedEntry)); + } else { + CHECK(!epoch.manifest_store->decoded_manifest); + } + if (mode == 0 || mode == 1) CHECK(HasEpochIssue(epoch, RecoveryIssueCode::MissingManifestStoreFile)); + if (mode == 3 || mode == 4) CHECK(HasEpochIssue(epoch, RecoveryIssueCode::InvalidManifestStoreFile)); + (void)manifest_store; + } +} + +void TestManifestHardlinkAndModeAreRejected() { + for (const bool use_hardlink : {false, true}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + const auto manifest = dir + "/manifest.json"; + if (use_hardlink) CHECK(::link(manifest.c_str(), (dir + "/extra-link").c_str()) == 0); + else CHECK(::chmod(manifest.c_str(), 0644) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(!snapshot->epochs.front().manifest_store->decoded_manifest); + CHECK(HasEpochIssue(snapshot->epochs.front(), use_hardlink + ? RecoveryIssueCode::ManifestStoreHasUnexpectedEntry + : RecoveryIssueCode::InvalidManifestStoreFile)); + (void)manifest_store; + } +} + +void TestNonemptyOwnerLockIsIncompleteButManifestIsRetained() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto lock = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store/owner.lock"; + { std::ofstream out(lock, std::ios::binary | std::ios::trunc); out << "unexpected"; } + CHECK(::chmod(lock.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::InvalidManifestStoreFile)); + (void)manifest_store; +} + +void TestNestedReadHooksFailClosedWithoutLosingBootstrapDiagnostic() { + const std::array points{ + RecoveryReaderIoPoint::OpenManifestStoreDirectory, + RecoveryReaderIoPoint::EnumerateManifestStore, + RecoveryReaderIoPoint::StatManifestStoreEntry, + RecoveryReaderIoPoint::OpenManifestLock, + RecoveryReaderIoPoint::RevalidateManifestLock, + RecoveryReaderIoPoint::OpenManifestFile, + RecoveryReaderIoPoint::ReadManifestFile, + RecoveryReaderIoPoint::RevalidateManifestFile, + RecoveryReaderIoPoint::RevalidateManifestStore, + }; + for (const auto point : points) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + auto owner = OpenRecoveryOwner(temp.root, plan); + FailOne hook(point); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory != nullptr); + (void)manifest_store; + } +} + +void TestNestedListingMutationRetainsDecodedManifestButMarksIncomplete() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto store_dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + auto owner = OpenRecoveryOwner(temp.root, plan); + ActionOnce hook(RecoveryReaderIoPoint::EnumerateManifestStore, [&] { + std::ofstream out(store_dir + "/manifest.tmp"); + out << "new temp artifact"; + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreHasUnexpectedEntry) || + HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreChanged)); + (void)manifest_store; +} + +void TestManifestReplacementDuringFileRevalidationIsNotKnown() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto path = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store/manifest.json"; + auto owner = OpenRecoveryOwner(temp.root, plan); + ActionOnce hook(RecoveryReaderIoPoint::RevalidateManifestFile, [&] { + const auto replacement = path + ".replacement"; + { std::ofstream out(replacement, std::ios::binary | std::ios::trunc); out << "replaced"; } + CHECK(::chmod(replacement.c_str(), 0600) == 0); + CHECK(::rename(replacement.c_str(), path.c_str()) == 0); + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(!snapshot->epochs.front().manifest_store->decoded_manifest); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreFileChanged)); + (void)manifest_store; +} + +void TestReplacementAfterDecodeRetainsHistoricalManifestAsIncomplete() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto path = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store/manifest.json"; + auto owner = OpenRecoveryOwner(temp.root, plan); + ActionOnce hook(RecoveryReaderIoPoint::RevalidateManifestStore, [&] { + const auto replacement = path + ".replacement"; + { std::ofstream out(replacement, std::ios::binary | std::ios::trunc); out << "replaced"; } + CHECK(::chmod(replacement.c_str(), 0600) == 0); + CHECK(::rename(replacement.c_str(), path.c_str()) == 0); + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreChanged)); + (void)manifest_store; +} + +void TestManifestStoreAppearingDuringIntentReadIsReported() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto owner = OpenRecoveryOwner(temp.root, plan); + std::unique_ptr inserted_manifest; + ActionOnce hook(RecoveryReaderIoPoint::ReadIntent, [&] { + inserted_manifest = CreateManifestAt(temp.root, plan, ManifestPhase::Prepared); + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreChanged)); + (void)inserted_manifest; +} + +void TestManifestStoreSymlinkAndFifoDirectoriesAreRejected() { + for (const bool fifo : {false, true}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + manifest_store.reset(); + const auto store_dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + std::error_code remove_error; + std::filesystem::remove_all(store_dir, remove_error); + CHECK(!remove_error); + if (fifo) CHECK(::mkfifo(store_dir.c_str(), 0700) == 0); + else CHECK(::symlink("/tmp", store_dir.c_str()) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::InvalidManifestStoreDirectory)); + } +} + +void TestNestedEntryCapStillReadsAllowlistedFiles() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto store_dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + for (std::size_t i = 0; i < kMaxRecoveryManifestStoreEntries; ++i) { + std::ofstream out(store_dir + "/temporary-" + std::to_string(i)); + out << "x"; + } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::TooManyManifestStoreEntries)); + (void)manifest_store; +} + +void TestBootstrapAndManifestBytesShareAggregateReadBudget() { + TempRoot temp; + const auto first = MakePlan(0x01); + CreateArtifacts(temp.root, first, false); + const auto chunks = kMaxRecoveryAggregateBytes / kMaxManifestBytes; + for (std::size_t i = 0; i < chunks; ++i) { + auto plan = MakePlan(0x02); + plan.epoch_id.fill(0x02); + plan.epoch_id[15] = static_cast(i + 1); + constexpr char hex[] = "0123456789abcdef"; + for (std::size_t j = 0; j < plan.participants.size(); ++j) { + const auto value = 64 + i * plan.participants.size() + j; + plan.participants[j].container_id[plan.participants[j].container_id.size() - 2] = hex[value >> 4]; + plan.participants[j].container_id.back() = hex[value & 0x0f]; + } + auto model = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(model)); + auto encoded = EncodeBootstrapInventoryV1(std::get(model)); + CHECK(std::holds_alternative(encoded)); + const auto dir = EpochDirectory(temp.root, plan.epoch_id); + CHECK(::mkdir(dir.c_str(), 0700) == 0); + const auto intent = dir + "/intent.json"; + { + std::ofstream out(intent, std::ios::binary); + const auto& bytes = std::get(encoded); + out.write(bytes.data(), static_cast(bytes.size())); + } + CHECK(::chmod(intent.c_str(), 0600) == 0); + const auto store_dir = dir + "/manifest-store"; + CHECK(::mkdir(store_dir.c_str(), 0700) == 0); + const auto lock = store_dir + "/owner.lock"; + { std::ofstream out(lock, std::ios::binary); } + CHECK(::chmod(lock.c_str(), 0600) == 0); + const auto manifest = store_dir + "/manifest.json"; + { std::ofstream out(manifest, std::ios::binary); out.put('{'); } + CHECK(::chmod(manifest.c_str(), 0600) == 0); + std::filesystem::resize_file(manifest, kMaxManifestBytes); + } + auto owner = OpenRecoveryOwner(temp.root, first); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(!snapshot->epochs.empty()); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(HasIssue(snapshot->issues, RecoveryIssueCode::AggregateByteLimit)); + for (const auto& epoch : snapshot->epochs) { + if (epoch.inventory) CHECK(epoch.canonical_digest.has_value()); + if (epoch.manifest_store && epoch.manifest_store->decoded_manifest) + CHECK(epoch.manifest_store->canonical_digest.has_value()); + } +} + +void TestBootstrapAndManifestRecordsShareAggregateParticipantBudget() { + TempRoot temp; + const auto first_plan = MakeLargePlan(0x10, 256, 0x100000); + { + auto created = RuntimeOwner::CreateNew(temp.root, first_plan.domain_id); + CHECK(std::holds_alternative>(created)); + auto owner = std::move(std::get>(created)); + auto claim = owner->ClaimInitialEpoch(first_plan.epoch_id); + CHECK(std::holds_alternative(claim)); + } + + constexpr std::size_t paired_epochs = kMaxRecoveryAggregateParticipants / (2 * 256); + static_assert(paired_epochs == 32); + for (std::size_t i = 0; i < paired_epochs; ++i) { + const auto epoch_byte = static_cast(0x10 + i); + auto plan = MakeLargePlan(epoch_byte, 256, 0x100000 + i * 1000); + CreateLayoutWithInventoryAndManifest(temp.root, plan, + 10'000'000 + i * 1000, epoch_byte); + } + // A final valid bootstrap history adds participant records beyond the shared + // cap. Its inventory must not be presented as retained if the conservative + // count check stops before retention. + const auto overflow_plan = MakeLargePlan(0x40, 11, 0x200000); + CreateLayoutWithInventoryAndManifest(temp.root, overflow_plan, 20'000'000, 0x40); + + auto owner = OpenRecoveryOwner(temp.root, first_plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(HasIssue(snapshot->issues, RecoveryIssueCode::AggregateParticipantLimit)); + std::size_t retained_records = 0; + std::size_t retained_manifest_participants = 0; + for (const auto& epoch : snapshot->epochs) { + if (epoch.inventory) retained_records += epoch.inventory->records().size(); + if (epoch.manifest_store && epoch.manifest_store->decoded_manifest) + retained_manifest_participants += epoch.manifest_store->decoded_manifest->candidate.participants.size(); + } + CHECK(retained_records + retained_manifest_participants == kMaxRecoveryAggregateParticipants); + CHECK(snapshot->epochs.size() == paired_epochs + 1); + CHECK(snapshot->epochs.back().inventory == nullptr); + CHECK(snapshot->epochs.back().manifest_store == std::nullopt); +} + +} // namespace + +int main() { + TestManifestStoreIsOptionalAndAllPhasesAreDiagnostic(); + TestValidManifestSurvivesPendingOrInvalidBootstrapIntent(); + TestManifestCandidateMismatchIsReportedButDecodedDataIsKept(); + TestInvalidManifestArtifactsDoNotHideBootstrapInventory(); + TestManifestHardlinkAndModeAreRejected(); + TestNonemptyOwnerLockIsIncompleteButManifestIsRetained(); + TestNestedReadHooksFailClosedWithoutLosingBootstrapDiagnostic(); + TestNestedListingMutationRetainsDecodedManifestButMarksIncomplete(); + TestManifestReplacementDuringFileRevalidationIsNotKnown(); + TestReplacementAfterDecodeRetainsHistoricalManifestAsIncomplete(); + TestManifestStoreAppearingDuringIntentReadIsReported(); + TestManifestStoreSymlinkAndFifoDirectoriesAreRejected(); + TestNestedEntryCapStillReadsAllowlistedFiles(); + TestBootstrapAndManifestBytesShareAggregateReadBudget(); + TestBootstrapAndManifestRecordsShareAggregateParticipantBudget(); + return 0; +} diff --git a/tests/supervisor/epoch_artifact_layout_test.cpp b/tests/supervisor/epoch_artifact_layout_test.cpp new file mode 100644 index 0000000..883a4d8 --- /dev/null +++ b/tests/supervisor/epoch_artifact_layout_test.cpp @@ -0,0 +1,104 @@ +#include "supervisor/epoch_artifact_layout.h" + +#include +#include +#include +#include +#include + +namespace layout = rateguard::supervisor::epoch_layout_v1; +using rateguard::supervisor::EpochId; + +namespace { + +int failures = 0; + +void Check(bool condition, std::string_view label) { + if (!condition) { + ++failures; + std::cerr << "FAIL: " << label << '\n'; + } +} + +void RoundTrip(const EpochId& id, std::string_view expected) { + const auto encoded = layout::FormatEpochDirectoryName(id); + const auto* name = std::get_if(&encoded); + Check(name != nullptr, "format accepted nonzero ID"); + if (name == nullptr) return; + Check(*name == expected, "format canonical expected spelling"); + const auto parsed = layout::ParseEpochDirectoryName(*name); + Check(parsed.has_value(), "parse formatted name"); + if (parsed) Check(*parsed == id, "round trip preserves all bytes"); +} + +void TestNames() { + constexpr std::array, 7> kNames{{ + {"epoch-", layout::kEpochDirectoryPrefix}, + {"intent.json", layout::kIntentFileName}, + {"intent.tmp", layout::kIntentTemporaryFileName}, + {"manifest-store", layout::kManifestStoreDirectoryName}, + {"owner.lock", layout::kManifestStoreLockFileName}, + {"manifest.json", layout::kManifestFileName}, + {"manifest.tmp", layout::kManifestTemporaryFileName}, + }}; + for (const auto& [expected, actual] : kNames) + Check(expected == actual, "shared v1 artifact name constant"); +} + +void TestRoundTrips() { + EpochId zero_first{}; + zero_first[15] = 1; + RoundTrip(zero_first, "epoch-00000000000000000000000000000001"); + + EpochId all_ff{}; + all_ff.fill(0xff); + RoundTrip(all_ff, "epoch-ffffffffffffffffffffffffffffffff"); + + EpochId alternating{}; + for (std::size_t i = 0; i < alternating.size(); ++i) + alternating[i] = i % 2 == 0 ? 0x0a : 0xb0; + RoundTrip(alternating, "epoch-0ab00ab00ab00ab00ab00ab00ab00ab0"); + + EpochId max_first{}; + max_first[0] = 0x80; + max_first[15] = 0x01; + RoundTrip(max_first, "epoch-80000000000000000000000000000001"); +} + +void TestRejectedNames() { + constexpr std::string_view kValid = "epoch-00000000000000000000000000000001"; + Check(layout::ParseEpochDirectoryName(kValid).has_value(), "canonical sample parses"); + Check(!layout::ParseEpochDirectoryName("epoch-00000000000000000000000000000000"), + "all-zero ID rejected"); + Check(!layout::ParseEpochDirectoryName("Epoch-00000000000000000000000000000001"), + "uppercase prefix rejected"); + Check(!layout::ParseEpochDirectoryName("epoch-0000000000000000000000000000000A"), + "uppercase hex rejected"); + Check(!layout::ParseEpochDirectoryName("epoch-0000000000000000000000000000000g"), + "non-hex character rejected"); + Check(!layout::ParseEpochDirectoryName("epoch-0000000000000000000000000000001"), + "short name rejected"); + Check(!layout::ParseEpochDirectoryName("epoch-000000000000000000000000000000001"), + "long name rejected"); + Check(!layout::ParseEpochDirectoryName("xepoch-00000000000000000000000000000001"), + "noncanonical prefix rejected"); + Check(!layout::ParseEpochDirectoryName("epoch_00000000000000000000000000000001"), + "alternate separator rejected"); + + const EpochId all_zero{}; + const auto formatted_zero = layout::FormatEpochDirectoryName(all_zero); + const auto* error = std::get_if(&formatted_zero); + Check(error != nullptr && *error == layout::LayoutError::ZeroEpochId, + "format rejects zero ID with typed error"); +} + +} // namespace + +int main() { + TestNames(); + TestRoundTrips(); + TestRejectedNames(); + if (failures != 0) return 1; + std::cout << "epoch artifact layout checks passed\n"; + return 0; +} diff --git a/tests/supervisor/epoch_gate_independent_test.cpp b/tests/supervisor/epoch_gate_independent_test.cpp new file mode 100644 index 0000000..dc89597 --- /dev/null +++ b/tests/supervisor/epoch_gate_independent_test.cpp @@ -0,0 +1,273 @@ +#include "supervisor/epoch_gate.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::supervisor; +namespace { +std::atomic failures{0}; +#define CHECK(x) do { if (!(x)) { std::cerr<<"FAIL line "<<__LINE__<<": " #x "\n"; ++failures; } } while(0) + +std::string HexContainer(unsigned value) { + static constexpr char digits[]="0123456789abcdef"; + std::string s(64,'0'); + for (unsigned i=0;i<8;++i) { s[63-i]=digits[value&15]; value>>=4; } + return s; +} +IncarnationId Inc(unsigned value) { IncarnationId a{}; a[15]=static_cast(value); a[14]=static_cast(value>>8); return a; } +EpochId Epoch(unsigned value) { EpochId a{}; a[15]=static_cast(value); a[14]=static_cast(value>>8); return a; } +PolicyDigest Digest() { PolicyDigest a{}; a[0]=0x55; return a; } +OperationId Op(unsigned value) { OperationId a{}; a[15]=static_cast(value); return a; } +rateguard::platform::ClockIdentity Clock() { + rateguard::platform::ClockIdentity c{}; c.boot_uuid[0]=1; c.namespace_device=2; + c.namespace_inode=3; c.clock_id=1; return c; +} + +struct Controller final : IProcessController { + struct Call { bool stop; Participant participant; OperationId operation; }; + std::mutex mutex; + std::vector calls; + std::vector> states; + std::optional unknown_on_inspect; + std::optional mismatch_on_inspect; + std::optional timeout_inspect; + std::optional stop_error; + std::optional wrong_ack; + std::optional throw_inspect; + std::optional throw_stop; + std::function inspect_hook; + std::function stop_hook; + + void SetState(const Participant& p, ProcessState state) { + std::lock_guard lock(mutex); + for (auto& row:states) if (row.first==p) { row.second=state; return; } + states.emplace_back(p,state); + } + std::vector Calls() { std::lock_guard lock(mutex); return calls; } + std::variant RequestStop(const Participant& expected,const OperationId& op) override { + { + std::lock_guard lock(mutex); calls.push_back({true,expected,op}); + if (throw_stop && expected.participant_id==*throw_stop) throw std::runtime_error("stop fixture"); + if (stop_error && expected.participant_id==*stop_error) return ControllerError::Unavailable; + for (auto& row:states) if (row.first==expected) { row.second=ProcessState::Exited; break; } + } + if (stop_hook) stop_hook(); + return StopAck{wrong_ack && expected.participant_id==*wrong_ack ? Op(0xEE) : op}; + } + std::variant Inspect(const Participant& expected) override { + { + std::lock_guard lock(mutex); calls.push_back({false,expected,{}}); + if (throw_inspect && expected.participant_id==*throw_inspect) throw std::runtime_error("inspect fixture"); + if (timeout_inspect && expected.participant_id==*timeout_inspect) return ControllerError::TimedOut; + if (unknown_on_inspect && expected.participant_id==*unknown_on_inspect) + return ProcessObservation{expected,ProcessState::Unknown}; + if (mismatch_on_inspect && expected.participant_id==*mismatch_on_inspect) { + auto wrong=expected; ++wrong.process.pid_start_ticks; + return ProcessObservation{wrong,ProcessState::Exited}; + } + } + if (inspect_hook) inspect_hook(); + std::lock_guard lock(mutex); + for (const auto& row:states) if(row.first==expected) return ProcessObservation{expected,row.second}; + return ProcessObservation{expected,ProcessState::Unknown}; + } +}; + +Participant MakeParticipant(ParticipantRole role, std::uint32_t slot, unsigned i, + const rateguard::platform::ClockIdentity& clock, + unsigned participant_key=0) { + Participant p; p.role=role; p.slot_id=slot; p.participant_id="p"+std::to_string(participant_key?participant_key:i); + p.incarnation=Inc(i+1); p.process={HexContainer(i+1),1000+i,2000+i}; p.clock_identity=clock; return p; +} +EpochCandidate Candidate(std::size_t adapters=2,std::vector slots={0,9}) { + EpochCandidate c; c.epoch_id=Epoch(1); c.authority_incarnation=Inc(1); c.policy_digest=Digest(); c.clock_identity=Clock(); + unsigned n=1; + auto authority=MakeParticipant(ParticipantRole::Authority,0,n++,c.clock_identity); authority.incarnation=c.authority_incarnation; authority.participant_id="authority"; c.participants.push_back(authority); + auto witness=MakeParticipant(ParticipantRole::Witness,0,n++,c.clock_identity); witness.participant_id="witness"; c.participants.push_back(witness); + unsigned rid=10; + for(auto slot:slots) { auto r=MakeParticipant(ParticipantRole::Replica,slot,rid++,c.clock_identity); r.participant_id="replica-"+std::to_string(slot); c.participants.push_back(r); } + for(std::size_t i=0;i(30+i),c.clock_identity); a.participant_id="adapter-"+std::to_string(i); c.participants.push_back(a); } + return c; +} +std::shared_ptr Create(EpochCandidate c,Controller& ctl) { + for(const auto& p:c.participants) ctl.SetState(p,ProcessState::Running); + auto result=EpochGate::Create(std::move(c),ctl); + CHECK(std::holds_alternative>(result)); + if(!std::holds_alternative>(result)) return {}; + return std::get>(std::move(result)); +} +bool IsError(const auto& result,GateError e) { + return std::holds_alternative(result) && std::get(result)==e; +} +bool IsOk(const GateResult& result) { return std::holds_alternative(result); } +void Activate(std::shared_ptr& gate) { CHECK(IsOk(gate->Activate())); } +void TestCandidateValidationAndArbitrarySlotIds() { + Controller ctl; + auto valid=Candidate(2,{0,9,std::numeric_limits::max()}); + auto gate=Create(std::move(valid),ctl); + CHECK(gate && gate->phase()==EpochPhase::PreActivation); + CHECK(gate->candidate().participants.size()==7); + auto duplicate_slot=Candidate(1,{7,7}); + CHECK(IsError(EpochGate::Create(std::move(duplicate_slot),ctl),GateError::InvalidInventory)); + auto too_many_replicas=Candidate(1,{0,1,2,3,4,5,6,7,8}); + CHECK(IsError(EpochGate::Create(std::move(too_many_replicas),ctl),GateError::InvalidInventory)); + auto no_replica=Candidate(1,{}); + CHECK(IsError(EpochGate::Create(std::move(no_replica),ctl),GateError::InvalidInventory)); + auto many_adapters=Candidate(1022,{1}); + CHECK(IsError(EpochGate::Create(std::move(many_adapters),ctl),GateError::TooManyParticipants)); + auto duplicate=Candidate(2,{1}); + duplicate.participants.back().process.container_id=duplicate.participants[duplicate.participants[3].role==ParticipantRole::Adapter?3:0].process.container_id; + CHECK(IsError(EpochGate::Create(std::move(duplicate),ctl),GateError::InvalidInventory)); + auto duplicate_pid=Candidate(2,{1}); + duplicate_pid.participants.back().process.pid=duplicate_pid.participants[3].process.pid; + ++duplicate_pid.participants.back().process.pid_start_ticks; + CHECK(IsError(EpochGate::Create(std::move(duplicate_pid),ctl),GateError::InvalidInventory)); + auto bad_identity=Candidate(1,{1}); + bad_identity.participants.back().clock_identity.clock_id=8; + CHECK(IsError(EpochGate::Create(std::move(bad_identity),ctl),GateError::InvalidInventory)); + auto bad_container=Candidate(1,{1}); bad_container.participants.back().process.container_id[0]='A'; + CHECK(IsError(EpochGate::Create(std::move(bad_container),ctl),GateError::InvalidInventory)); + auto wrong_authority=Candidate(1,{1}); ++wrong_authority.participants[0].incarnation[0]; + CHECK(IsError(EpochGate::Create(std::move(wrong_authority),ctl),GateError::InvalidInventory)); +} +void TestActivationIdentityTimeoutAndUnknown() { + auto run=[](auto configure,GateError expected) { + Controller ctl; auto c=Candidate(1,{7}); + auto gate=Create(std::move(c),ctl); if(!gate)return; + configure(gate->candidate(),ctl); + CHECK(IsError(gate->Activate(),expected)); CHECK(gate->phase()==EpochPhase::PreActivation); + CHECK(IsError(gate->TryAcquireCommitPermit(gate->candidate().epoch_id),GateError::WrongPhase)); + }; + run([](const auto& c,auto& ctl){ctl.SetState(c.participants[0],ProcessState::Exited);},GateError::NotRunning); + run([](const auto& c,auto& ctl){ctl.unknown_on_inspect=c.participants[0].participant_id;},GateError::NotRunning); + run([](const auto& c,auto& ctl){ctl.timeout_inspect=c.participants[0].participant_id;},GateError::ControllerFailure); + run([](const auto& c,auto& ctl){ctl.mismatch_on_inspect=c.participants[0].participant_id;},GateError::IdentityMismatch); + run([](const auto& c,auto& ctl){ctl.throw_inspect=c.participants[0].participant_id;},GateError::ControllerFailure); +} +void TestLeaseDrainAndOrderedFence() { + Controller ctl; auto gate=Create(Candidate(2,{0,9}),ctl); if(!gate)return; Activate(gate); + auto bad=Epoch(99); CHECK(IsError(gate->TryAcquireCommitPermit(bad),GateError::WrongEpoch)); + auto lease_result=gate->TryAcquireCommitPermit(gate->candidate().epoch_id); + CHECK(std::holds_alternative(lease_result)); + if(!std::holds_alternative(lease_result)) return; + std::optional lease; lease.emplace(std::get(std::move(lease_result))); + const auto op=Op(11); CHECK(IsOk(gate->BeginDrain(op,DrainCause::Requested))); + CHECK(gate->phase()==EpochPhase::Draining); + CHECK(IsOk(gate->BeginDrain(op,DrainCause::IntegrityFailure))); + CHECK(IsError(gate->BeginDrain(Op(12),DrainCause::Requested),GateError::WrongOperation)); + CHECK(IsError(gate->TryAcquireCommitPermit(gate->candidate().epoch_id),GateError::WrongPhase)); + CHECK(IsError(gate->FenceAndClose(op),GateError::InFlightCommit)); + auto before_release=ctl.Calls(); + CHECK(std::none_of(before_release.begin(),before_release.end(),[](const auto& c){return c.stop;})); + lease.reset(); + CHECK(IsOk(gate->FenceAndClose(op))); + CHECK(gate->phase()==EpochPhase::Closed); + auto calls=ctl.Calls(); + std::size_t first_auth_stop=calls.size(), last_ingress_stop=0, first_ingress_inspect=calls.size(); + bool auth_stop=false,witness_stop=false,ingress_stop_started=false; + for(std::size_t i=0;iBeginDrain(op,DrainCause::Requested))); + CHECK(IsError(gate->BeginDrain(Op(13),DrainCause::Requested),GateError::WrongOperation)); + const auto before_replay=ctl.Calls().size(); + CHECK(IsOk(gate->FenceAndClose(op))); // closed operation replays idempotently + CHECK(IsError(gate->FenceAndClose(Op(13)),GateError::WrongOperation)); + CHECK(ctl.Calls().size()==before_replay); // replay does not repeat lifecycle I/O + CHECK(IsError(gate->Activate(),GateError::WrongPhase)); +} +void TestUnknownStaleAndTimeoutPreventClose() { + auto fail_case=[](auto configure,GateError expected) { + Controller ctl; auto gate=Create(Candidate(2,{1,2}),ctl); if(!gate)return; + Activate(gate); const auto op=Op(21); CHECK(IsOk(gate->BeginDrain(op,DrainCause::AuthorityFailure))); + configure(ctl,gate->candidate()); + auto close_result=gate->FenceAndClose(op); CHECK(IsError(close_result,expected)); CHECK(gate->phase()==EpochPhase::Draining); + auto calls=ctl.Calls(); + CHECK(std::none_of(calls.begin(),calls.end(),[](const auto& c){return c.stop && (c.participant.role==ParticipantRole::Authority || c.participant.role==ParticipantRole::Witness);})); + if(expected==GateError::NotExited || expected==GateError::IdentityMismatch || expected==GateError::ControllerFailure) { + // Clear the injected uncertainty and prove a later exact retry can close. + ctl.unknown_on_inspect.reset(); ctl.timeout_inspect.reset(); ctl.mismatch_on_inspect.reset(); ctl.throw_inspect.reset(); ctl.stop_error.reset(); ctl.wrong_ack.reset(); ctl.throw_stop.reset(); + for(const auto& p:gate->candidate().participants) ctl.SetState(p,ProcessState::Exited); + CHECK(IsOk(gate->FenceAndClose(op))); CHECK(gate->phase()==EpochPhase::Closed); + } + }; + fail_case([](auto& ctl,const auto& c){ctl.unknown_on_inspect=c.participants.back().participant_id;},GateError::NotExited); + fail_case([](auto& ctl,const auto& c){ctl.timeout_inspect=c.participants.back().participant_id;},GateError::ControllerFailure); + fail_case([](auto& ctl,const auto& c){ctl.mismatch_on_inspect=c.participants.back().participant_id;},GateError::IdentityMismatch); + fail_case([](auto& ctl,const auto& c){ctl.throw_inspect=c.participants.back().participant_id;},GateError::ControllerFailure); + fail_case([](auto& ctl,const auto& c){ctl.wrong_ack=c.participants.back().participant_id;},GateError::WrongOperation); + fail_case([](auto& ctl,const auto& c){ctl.stop_error=c.participants.back().participant_id;},GateError::NotExited); + fail_case([](auto& ctl,const auto& c){ctl.throw_stop=c.participants.back().participant_id;},GateError::NotExited); +} +void TestPreActivationDrainCleanup() { + Controller ctl; auto gate=Create(Candidate(2,{0,9}),ctl); if(!gate)return; + CHECK(gate->phase()==EpochPhase::PreActivation); + CHECK(IsError(gate->BeginDrain(OperationId{},DrainCause::Requested),GateError::WrongOperation)); + const auto op=Op(31); + CHECK(IsOk(gate->BeginDrain(op,DrainCause::IntegrityFailure))); + CHECK(gate->phase()==EpochPhase::Draining); + CHECK(IsOk(gate->FenceAndClose(op))); + CHECK(gate->phase()==EpochPhase::Closed); + auto calls=ctl.Calls(); + CHECK(!calls.empty()); + CHECK(calls.front().stop); // no activation/readiness inspect was required before the drain path +} +void TestLeaseKeepsStateAfterGateDestruction() { + Controller ctl; auto gate=Create(Candidate(1,{5}),ctl); if(!gate)return; Activate(gate); + auto lease_result=gate->TryAcquireCommitPermit(gate->candidate().epoch_id); + CHECK(std::holds_alternative(lease_result)); + if(!std::holds_alternative(lease_result)) return; + std::optional lease; lease.emplace(std::get(std::move(lease_result))); + gate.reset(); // Lease owns GateState until its destructor releases the count. + lease.reset(); +} +void TestConcurrentActivationReturnsBusyAndNoLockAcrossController() { + Controller ctl; auto gate=Create(Candidate(1,{1}),ctl); if(!gate)return; + std::mutex m; std::condition_variable cv; bool entered=false,release=false; + ctl.inspect_hook=[&]{ CHECK(gate->phase()==EpochPhase::PreActivation); std::unique_lock l(m); entered=true; cv.notify_all(); cv.wait(l,[&]{return release;}); }; + GateResult first; std::thread t([&]{first=gate->Activate();}); + {std::unique_lock l(m); cv.wait(l,[&]{return entered;});} + CHECK(IsError(gate->Activate(),GateError::Busy)); + {std::lock_guard l(m);release=true;} cv.notify_all();t.join();CHECK(IsOk(first)); +} +} +int main(){ + TestCandidateValidationAndArbitrarySlotIds(); + TestActivationIdentityTimeoutAndUnknown(); + TestLeaseDrainAndOrderedFence(); + TestUnknownStaleAndTimeoutPreventClose(); + TestPreActivationDrainCleanup(); + TestLeaseKeepsStateAfterGateDestruction(); + TestConcurrentActivationReturnsBusyAndNoLockAcrossController(); + if(failures){std::cerr<<"RG006 epoch gate QA failed: "< +#include +#include +#include +#include + +static void Check(bool condition, int line) { + if (!condition) { + std::cerr << "check failed at line " << line << std::endl; + std::exit(EXIT_FAILURE); + } +} +#define CHECK(expression) Check(static_cast(expression), __LINE__) + +using namespace rateguard::supervisor; + +class FakeController final : public IProcessController { + public: + std::map states; + std::vector calls; + bool throw_on_inspect{}; + bool wrong_ack{}; + std::string fail_stop_id; + + std::variant RequestStop( + const Participant& expected, const OperationId& op) override { + calls.push_back("stop:" + expected.participant_id); + if (expected.participant_id == fail_stop_id) return ControllerError::Unavailable; + states[expected.participant_id] = ProcessState::Exited; + auto ack = op; + if (wrong_ack) ack[0] ^= 1; + return StopAck{ack}; + } + std::variant Inspect( + const Participant& expected) override { + calls.push_back("inspect:" + expected.participant_id); + if (throw_on_inspect) throw 1; + return ProcessObservation{expected, states.at(expected.participant_id)}; + } +}; + +static EpochCandidate Candidate() { + EpochCandidate c; + c.epoch_id[0] = 1; + c.authority_incarnation[0] = 2; + c.policy_digest[0] = 3; + c.clock_identity.boot_uuid[0] = 4; + c.clock_identity.namespace_device = 11; + c.clock_identity.namespace_inode = 12; + c.clock_identity.clock_id = 1; + const auto add = [&](ParticipantRole role, std::uint32_t slot, const char* id, + std::uint8_t incarnation, char container, std::uint64_t pid) { + Participant p; + p.role = role; + p.slot_id = slot; + p.participant_id = id; + p.incarnation[0] = incarnation; + if (role == ParticipantRole::Authority) p.incarnation = c.authority_incarnation; + p.process.container_id = std::string(64, container); + p.process.pid = pid; + p.process.pid_start_ticks = pid + 100; + p.clock_identity = c.clock_identity; + c.participants.push_back(p); + }; + add(ParticipantRole::Authority, 0, "authority", 2, 'a', 101); + add(ParticipantRole::Witness, 0, "witness", 5, 'b', 102); + add(ParticipantRole::Replica, 0, "replica-zero", 6, 'c', 103); + add(ParticipantRole::Replica, 17, "replica-seventeen", 7, 'd', 104); + add(ParticipantRole::Adapter, 0, "adapter-a", 8, 'e', 105); + add(ParticipantRole::Adapter, 0, "adapter-b", 9, 'f', 106); + return c; +} + +static OperationId Op() { OperationId o{}; o[0] = 7; return o; } +static bool IsError(const GateResult& result, GateError error) { + const auto* value = std::get_if(&result); + return value && *value == error; +} + +int main() { + auto candidate = Candidate(); + FakeController controller; + for (const auto& p : candidate.participants) + controller.states[p.participant_id] = ProcessState::Running; + auto created = EpochGate::Create(candidate, controller); + CHECK(std::holds_alternative>(created)); + auto gate = std::get>(created); + CHECK(gate->phase() == EpochPhase::PreActivation); + CHECK(std::holds_alternative(gate->TryAcquireCommitPermit(candidate.epoch_id))); + CHECK(std::holds_alternative(gate->Activate())); + auto lease_result = gate->TryAcquireCommitPermit(candidate.epoch_id); + CHECK(std::holds_alternative(lease_result)); + CHECK(std::holds_alternative(gate->BeginDrain(Op(), DrainCause::Requested))); + CHECK(IsError(gate->FenceAndClose(Op()), GateError::InFlightCommit)); + lease_result.emplace(GateError::Busy); + CHECK(std::holds_alternative(gate->FenceAndClose(Op()))); + CHECK(gate->phase() == EpochPhase::Closed); + CHECK(std::holds_alternative(gate->FenceAndClose(Op()))); + + // Readiness failure remains preactivation but can be explicitly drained and fenced. + FakeController not_ready; + for (const auto& p : candidate.participants) + not_ready.states[p.participant_id] = p.role == ParticipantRole::Adapter + ? ProcessState::Unknown : ProcessState::Running; + auto second_created = EpochGate::Create(candidate, not_ready); + CHECK(std::holds_alternative>(second_created)); + auto second = std::get>(second_created); + CHECK(IsError(second->Activate(), GateError::NotRunning)); + CHECK(std::holds_alternative(second->BeginDrain(Op(), DrainCause::Requested))); + CHECK(std::holds_alternative(second->FenceAndClose(Op()))); + + // A controller exception cannot activate or close an epoch. + FakeController throwing; + for (const auto& p : candidate.participants) + throwing.states[p.participant_id] = ProcessState::Running; + auto third_created = EpochGate::Create(candidate, throwing); + auto third = std::get>(third_created); + throwing.throw_on_inspect = true; + CHECK(IsError(third->Activate(), GateError::ControllerFailure)); + CHECK(third->phase() == EpochPhase::PreActivation); + CHECK(std::holds_alternative(third->BeginDrain(Op(), DrainCause::Requested))); + CHECK(IsError(third->FenceAndClose(Op()), GateError::ControllerFailure)); + CHECK(third->phase() == EpochPhase::Draining); + + // An unconfirmed ingress process blocks authority/witness stop and closure. + FakeController partial; + for (const auto& p : candidate.participants) + partial.states[p.participant_id] = ProcessState::Running; + auto partial_created = EpochGate::Create(candidate, partial); + auto partial_gate = std::get>(partial_created); + CHECK(std::holds_alternative(partial_gate->Activate())); + CHECK(std::holds_alternative( + partial_gate->BeginDrain(Op(), DrainCause::AuthorityFailure))); + partial.fail_stop_id = "adapter-a"; + CHECK(IsError(partial_gate->FenceAndClose(Op()), GateError::NotExited)); + CHECK(partial_gate->phase() == EpochPhase::Draining); + CHECK(std::find(partial.calls.begin(), partial.calls.end(), "stop:replica-zero") != + partial.calls.end()); + CHECK(std::find(partial.calls.begin(), partial.calls.end(), "stop:authority") == + partial.calls.end()); + CHECK(std::find(partial.calls.begin(), partial.calls.end(), "stop:witness") == + partial.calls.end()); + + // Inventory catches reused container/PID identity and duplicate replica slot. + auto duplicate = Candidate(); + duplicate.participants.back().process.container_id = duplicate.participants[4].process.container_id; + CHECK(std::holds_alternative(EpochGate::Create(duplicate, controller))); + duplicate = Candidate(); + duplicate.participants[3].slot_id = duplicate.participants[2].slot_id; + CHECK(std::holds_alternative(EpochGate::Create(duplicate, controller))); + + // A lease owns the in-flight state even if the gate object is released first. + FakeController lifetime_controller; + auto fourth_created = EpochGate::Create(candidate, lifetime_controller); + auto fourth = std::get>(fourth_created); + for (const auto& p : candidate.participants) + lifetime_controller.states[p.participant_id] = ProcessState::Running; + CHECK(std::holds_alternative(fourth->Activate())); + auto survivor = fourth->TryAcquireCommitPermit(candidate.epoch_id); + CHECK(std::holds_alternative(survivor)); + fourth.reset(); + survivor.emplace(GateError::Busy); + + std::cout << "epoch gate tests passed\n"; +} diff --git a/tests/supervisor/http1_parser_allocation_independent_test.cpp b/tests/supervisor/http1_parser_allocation_independent_test.cpp new file mode 100644 index 0000000..5e125e0 --- /dev/null +++ b/tests/supervisor/http1_parser_allocation_independent_test.cpp @@ -0,0 +1,52 @@ +#include "supervisor/http1_parser.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::atomic_bool fail_allocations{false}; +} + +void* operator new(std::size_t size) { + if (fail_allocations.load(std::memory_order_relaxed)) throw std::bad_alloc(); + if (void* allocation = std::malloc(size == 0 ? 1 : size); allocation != nullptr) + return allocation; + throw std::bad_alloc(); +} + +void* operator new[](std::size_t size) { + if (fail_allocations.load(std::memory_order_relaxed)) throw std::bad_alloc(); + if (void* allocation = std::malloc(size == 0 ? 1 : size); allocation != nullptr) + return allocation; + throw std::bad_alloc(); +} + +void operator delete(void* allocation) noexcept { std::free(allocation); } +void operator delete[](void* allocation) noexcept { std::free(allocation); } +void operator delete(void* allocation, std::size_t) noexcept { std::free(allocation); } +void operator delete[](void* allocation, std::size_t) noexcept { std::free(allocation); } + +int main() { + const std::string wire = + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata"; + const std::vector input(wire.begin(), wire.end()); + fail_allocations.store(true, std::memory_order_relaxed); + const auto result = rateguard::supervisor::detail::ParseHttpResponse(input); + fail_allocations.store(false, std::memory_order_relaxed); + + const bool correctly_classified = + std::holds_alternative(result) && + std::get(result) == + rateguard::supervisor::detail::HttpParseError::AllocationFailure; + if (!correctly_classified) { + std::cerr << "parser did not classify injected allocation failure\n"; + return 1; + } + std::cout << "Independent parser allocation-failure check passed\n"; + return 0; +} diff --git a/tests/supervisor/http1_parser_independent_test.cpp b/tests/supervisor/http1_parser_independent_test.cpp new file mode 100644 index 0000000..edbc763 --- /dev/null +++ b/tests/supervisor/http1_parser_independent_test.cpp @@ -0,0 +1,220 @@ +#include "supervisor/http1_parser.h" + +#include +#include +#include +#include +#include +#include + +namespace { +int failures = 0; + +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::cerr << __FILE__ << ':' << __LINE__ << ": CHECK failed: " #expr \ + << '\n'; \ + ++failures; \ + } \ + } while (false) + +using rateguard::supervisor::UnixHttpResponse; +using rateguard::supervisor::detail::HttpParseError; +using rateguard::supervisor::detail::HttpParseResult; +using rateguard::supervisor::detail::IsValidOriginFormTarget; +using rateguard::supervisor::detail::ParseHttpResponse; + +std::vector Bytes(std::string_view value) { + return {value.begin(), value.end()}; +} + +bool ParsesAs(std::string_view wire, std::uint16_t status, + std::string_view body) { + const auto input = Bytes(wire); + const auto result = ParseHttpResponse(input); + if (!std::holds_alternative(result)) return false; + const auto& response = std::get(result); + return response.status == status && + std::string(response.body.begin(), response.body.end()) == body; +} + +bool FailsAs(std::string_view wire, HttpParseError expected) { + const auto input = Bytes(wire); + const auto result = ParseHttpResponse(input); + return std::holds_alternative(result) && + std::get(result) == expected; +} + +void TestFramingAndStatusOwnership() { + CHECK(ParsesAs("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabc", 200, + "abc")); + CHECK(ParsesAs("HTTP/1.0 200 OK\r\nContent-Length: 0\r\n\r\n", 200, "")); + CHECK(ParsesAs("HTTP/1.1 200 OK\r\nContent-Encoding: identity\r\n" + "Content-Length: 2\r\n\r\nxy", 200, "xy")); + CHECK(ParsesAs("HTTP/1.1 200 OK\r\n\r\nclose body", 200, "close body")); + CHECK(ParsesAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "2\r\nok\r\n0\r\n\r\n", 200, "ok")); + CHECK(ParsesAs("HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n", 204, + "")); + CHECK(ParsesAs("HTTP/1.1 304 Not Modified\r\n\r\n", 304, "")); + + // The parser is deliberately transport-level: it returns HTTP statuses; + // the Docker controller must reject redirects and unexpected statuses. + CHECK(ParsesAs("HTTP/1.1 302 Found\r\nContent-Length: 0\r\n\r\n", 302, + "")); +} + +void TestAmbiguousOrMalformedFraming() { + CHECK(FailsAs("HTTP/1.1 200 OK\nContent-Length: 0\n\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 100 Continue\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 099 Invalid\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 600 Invalid\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nContent-Length: 1\r\n" + "content-length: 1\r\n\r\na", HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nContent-Length: +1\r\n\r\na", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nContent-Length: 18446744073709551616\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n" + "transfer-encoding: chunked\r\n\r\n0\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip, chunked\r\n" + "\r\n0\r\n\r\n", HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n" + "Transfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\n" + "Content-Length: 0\r\n\r\n", HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\n Folded: yes\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nBad Name: x\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\na", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nab", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 204 No Content\r\nContent-Length: 1\r\n\r\nx", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 304 Not Modified\r\nTransfer-Encoding: chunked\r\n" + "\r\n0\r\n\r\n", HttpParseError::Malformed)); +} + +void TestChunkGrammar() { + CHECK(ParsesAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "1\r\na\r\n1\r\nb\r\n0\r\n\r\n", 200, "ab")); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "1;x=y\r\na\r\n0\r\n\r\n", HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "1\r\naX0\r\n\r\n", HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "0\r\nX-Trailer: forbidden\r\n\r\n", + HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "0\r\n\r\nextra", HttpParseError::Malformed)); + CHECK(FailsAs("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "10000000000000000\r\na", HttpParseError::Malformed)); +} + +void TestExactBounds() { + using namespace rateguard::supervisor; + + const std::string base = "HTTP/1.1 200 OK\r\nX: "; + const std::string suffix = "\r\n\r\n"; + CHECK(base.size() + (kUnixHttpMaxHeaderBytes - base.size() - suffix.size()) + + suffix.size() == kUnixHttpMaxHeaderBytes); + const std::string exact_header = + base + std::string(kUnixHttpMaxHeaderBytes - base.size() - suffix.size(), + 'a') + suffix; + CHECK(ParseHttpResponse(Bytes(exact_header)).index() == 0); + const std::string over_header = "HTTP/1.1 200 OK\r\nX: " + + std::string(kUnixHttpMaxHeaderBytes, 'a') + suffix; + CHECK(FailsAs(over_header, HttpParseError::TooLarge)); + + std::string exact_fields = "HTTP/1.1 200 OK\r\n"; + for (std::size_t i = 0; i < kUnixHttpMaxHeaderFields; ++i) + exact_fields += "X-" + std::to_string(i) + ": a\r\n"; + exact_fields += "\r\n"; + CHECK(ParseHttpResponse(Bytes(exact_fields)).index() == 0); + std::string over_fields = "HTTP/1.1 200 OK\r\n"; + for (std::size_t i = 0; i <= kUnixHttpMaxHeaderFields; ++i) + over_fields += "X-" + std::to_string(i) + ": a\r\n"; + over_fields += "\r\n"; + CHECK(FailsAs(over_fields, HttpParseError::TooLarge)); + + const std::string body_header = "HTTP/1.1 200 OK\r\nContent-Length: " + + std::to_string(kUnixHttpMaxDecodedBodyBytes) + "\r\n\r\n"; + const auto exact_body = body_header + + std::string(kUnixHttpMaxDecodedBodyBytes, 'b'); + CHECK(ParseHttpResponse(Bytes(exact_body)).index() == 0); + const std::string body_over = "HTTP/1.1 200 OK\r\nContent-Length: " + + std::to_string(kUnixHttpMaxDecodedBodyBytes + 1) + "\r\n\r\n"; + CHECK(FailsAs(body_over, HttpParseError::TooLarge)); + + std::string exact_chunks = + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"; + for (std::size_t i = 0; i < kUnixHttpMaxChunks; ++i) + exact_chunks += "1\r\na\r\n"; + exact_chunks += "0\r\n\r\n"; + CHECK(ParseHttpResponse(Bytes(exact_chunks)).index() == 0); + std::string chunks_over = + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"; + for (std::size_t i = 0; i <= kUnixHttpMaxChunks; ++i) + chunks_over += "1\r\na\r\n"; + chunks_over += "0\r\n\r\n"; + CHECK(FailsAs(chunks_over, HttpParseError::TooLarge)); + + std::string exact_chunk_line = + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"; + exact_chunk_line += std::string(kUnixHttpMaxChunkLineBytes - 1, '0'); + exact_chunk_line += "1\r\na\r\n0\r\n\r\n"; + CHECK(ParseHttpResponse(Bytes(exact_chunk_line)).index() == 0); + std::string over_chunk_line = + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"; + over_chunk_line += std::string(kUnixHttpMaxChunkLineBytes, '0'); + over_chunk_line += "1\r\na\r\n0\r\n\r\n"; + CHECK(FailsAs(over_chunk_line, HttpParseError::TooLarge)); + + CHECK(FailsAs(std::string(kUnixHttpMaxWireResponseBytes + 1, 'x'), + HttpParseError::TooLarge)); +} + +void TestTargetGrammar() { + using namespace rateguard::supervisor; + CHECK(IsValidOriginFormTarget("/version")); + CHECK(IsValidOriginFormTarget("/v1.57/containers/" + std::string(64, 'a') + + "/json")); + CHECK(IsValidOriginFormTarget("/v1.57/containers/id/stop?signal=SIGTERM&t=1")); + CHECK(IsValidOriginFormTarget("/" + std::string(kUnixHttpMaxTargetBytes - 1, 'a'))); + CHECK(!IsValidOriginFormTarget("")); + CHECK(!IsValidOriginFormTarget("relative/path")); + CHECK(!IsValidOriginFormTarget("//authority/path")); + CHECK(!IsValidOriginFormTarget("/path#fragment")); + CHECK(!IsValidOriginFormTarget("/path\\segment")); + CHECK(!IsValidOriginFormTarget("/path\r\nInjected: x")); + const std::string embedded_nul("/path\0tail", 10); + CHECK(!IsValidOriginFormTarget(embedded_nul)); + CHECK(!IsValidOriginFormTarget("/" + std::string(kUnixHttpMaxTargetBytes, 'a'))); +} + +} // namespace + +int main() { + TestFramingAndStatusOwnership(); + TestAmbiguousOrMalformedFraming(); + TestChunkGrammar(); + TestExactBounds(); + TestTargetGrammar(); + if (failures != 0) { + std::cerr << failures << " independent HTTP parser assertion(s) failed\n"; + return 1; + } + std::cout << "Independent HTTP parser checks passed\n"; + return 0; +} diff --git a/tests/supervisor/http1_parser_test.cpp b/tests/supervisor/http1_parser_test.cpp new file mode 100644 index 0000000..f129c08 --- /dev/null +++ b/tests/supervisor/http1_parser_test.cpp @@ -0,0 +1,166 @@ +#include "supervisor/http1_parser.h" + +#include +#include +#include +#include +#include + +namespace { +int failures = 0; +#define CHECK(expr) do { if (!(expr)) { std::cerr << __FILE__ << ':' << __LINE__ << ": CHECK failed: " #expr "\n"; ++failures; } } while (false) + +std::vector Bytes(std::string_view text) { + return {text.begin(), text.end()}; +} + +bool IsError(std::string_view wire, + rateguard::supervisor::detail::HttpParseError expected) { + auto input = Bytes(wire); + const auto result = rateguard::supervisor::detail::ParseHttpResponse(input); + return std::holds_alternative(result) && + std::get(result) == expected; +} + +void TestContentLengthAndStatus() { + using namespace rateguard::supervisor; + auto input = Bytes("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabc"); + auto result = detail::ParseHttpResponse(input); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& response = std::get(result); + CHECK(response.status == 200); + CHECK(std::string(response.body.begin(), response.body.end()) == "abc"); + } + input = Bytes("HTTP/1.0 404 Not Found\r\nContent-Length: 0\r\n\r\n"); + result = detail::ParseHttpResponse(input); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) + CHECK(std::get(result).status == 404); +} + +void TestCloseDelimitedAndEmptyStatuses() { + using namespace rateguard::supervisor; + auto result = detail::ParseHttpResponse(Bytes("HTTP/1.1 500 Error\r\n\r\nbody")); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& response = std::get(result); + CHECK(response.status == 500); + CHECK(std::string(response.body.begin(), response.body.end()) == "body"); + } + for (const auto status : {204, 304}) { + const auto wire = "HTTP/1.1 " + std::to_string(status) + " No Content\r\n\r\n"; + result = detail::ParseHttpResponse(Bytes(wire)); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) + CHECK(std::get(result).body.empty()); + } + CHECK(IsError("HTTP/1.1 204 No Content\r\nContent-Length: 1\r\n\r\nx", + detail::HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 304 Not Modified\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + detail::HttpParseError::Malformed)); +} + +void TestChunked() { + using namespace rateguard::supervisor; + auto result = detail::ParseHttpResponse(Bytes( + "HTTP/1.1 200 OK\r\nTransfer-Encoding: Chunked\r\n\r\n" + "3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n")); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& response = std::get(result); + CHECK(std::string(response.body.begin(), response.body.end()) == "abcde"); + } + CHECK(IsError("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "1;ext=x\r\na\r\n0\r\n\r\n", + detail::HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "0\r\nX-Trailer: no\r\n\r\n", + detail::HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "1\r\na\r\n0\r\n\r\nEXTRA", + detail::HttpParseError::Malformed)); +} + +void TestMalformedAndAmbiguousFraming() { + using rateguard::supervisor::detail::HttpParseError; + CHECK(IsError("", HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\nContent-Length: 0\n\n", HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 100 Continue\r\n\r\n", HttpParseError::Malformed)); + CHECK(IsError("HTTP/2 200 OK\r\nContent-Length: 0\r\n\r\n", HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nContent-Length: 1\r\nContent-Length: 1\r\n\r\na", + HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nContent-Length: 0\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip, chunked\r\n\r\n0\r\n\r\n", + HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: 0\r\n\r\n", + HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nFolded: yes\r\n invalid\r\nContent-Length: 0\r\n\r\n", + HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nab", + HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nab", + HttpParseError::Malformed)); + CHECK(IsError("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\nextra", + HttpParseError::Malformed)); +} + +void TestBounds() { + using namespace rateguard::supervisor; + using detail::HttpParseError; + std::string long_headers = "HTTP/1.1 200 OK\r\n"; + for (int i = 0; i < 65; ++i) long_headers += "X-A: b\r\n"; + long_headers += "\r\n"; + CHECK(IsError(long_headers, HttpParseError::TooLarge)); + + std::string too_many_wire(kUnixHttpMaxWireResponseBytes + 1, 'x'); + CHECK(IsError(too_many_wire, HttpParseError::TooLarge)); + + std::string too_long_head(kUnixHttpMaxHeaderBytes, 'x'); + CHECK(IsError(too_long_head, HttpParseError::TooLarge)); + + const std::string too_large_body = "HTTP/1.1 200 OK\r\nContent-Length: " + + std::to_string(kUnixHttpMaxDecodedBodyBytes + 1) + "\r\n\r\n"; + CHECK(IsError(too_large_body, HttpParseError::TooLarge)); + + std::string long_chunkline = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"; + long_chunkline += std::string(kUnixHttpMaxChunkLineBytes + 1, 'a') + "\r\n"; + CHECK(IsError(long_chunkline, HttpParseError::TooLarge)); + + std::string many_chunks = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"; + for (std::size_t i = 0; i <= kUnixHttpMaxChunks; ++i) + many_chunks += "1\r\na\r\n"; + many_chunks += "0\r\n\r\n"; + CHECK(IsError(many_chunks, HttpParseError::TooLarge)); +} + +void TestTargetValidation() { + using rateguard::supervisor::detail::IsValidOriginFormTarget; + CHECK(IsValidOriginFormTarget("/version")); + CHECK(IsValidOriginFormTarget("/v1.45/containers/id/json?size=0")); + CHECK(!IsValidOriginFormTarget("")); + CHECK(!IsValidOriginFormTarget("version")); + CHECK(!IsValidOriginFormTarget("//host/path")); + CHECK(!IsValidOriginFormTarget("/path#fragment")); + CHECK(!IsValidOriginFormTarget("/path\r\nInjected: yes")); + CHECK(!IsValidOriginFormTarget("/path\\other")); + CHECK(!IsValidOriginFormTarget(std::string(2'049, 'a').replace(0, 1, "/"))); +} + +} // namespace + +int main() { + TestContentLengthAndStatus(); + TestCloseDelimitedAndEmptyStatuses(); + TestChunked(); + TestMalformedAndAmbiguousFraming(); + TestBounds(); + TestTargetValidation(); + if (failures != 0) { + std::cerr << failures << " test assertion(s) failed\n"; + return 1; + } + std::cout << "HTTP parser contract tests passed\n"; + return 0; +} diff --git a/tests/supervisor/manifest_codec_test.cpp b/tests/supervisor/manifest_codec_test.cpp new file mode 100644 index 0000000..9df0ee2 --- /dev/null +++ b/tests/supervisor/manifest_codec_test.cpp @@ -0,0 +1,170 @@ +#include "supervisor/manifest_codec.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::supervisor; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #condition); \ + std::abort(); \ + } \ +} while (false) + +std::string Hex(const std::array& bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string out; + out.reserve(64); + for (auto byte : bytes) { + out.push_back(digits[byte >> 4]); + out.push_back(digits[byte & 0x0f]); + } + return out; +} + +ManifestV1 Fixture() { + ManifestV1 m; + m.candidate.epoch_id.fill(0x11); + m.candidate.authority_incarnation.fill(0x22); + m.candidate.policy_digest.fill(0x33); + m.candidate.clock_identity.boot_uuid.fill(0x44); + m.candidate.clock_identity.namespace_device = 7; + m.candidate.clock_identity.namespace_inode = 9; + m.candidate.clock_identity.monotonic_offset_seconds = -2; + m.candidate.clock_identity.monotonic_offset_nanoseconds = 123; + m.candidate.clock_identity.boottime_offset_seconds = 3; + m.candidate.clock_identity.boottime_offset_nanoseconds = 456; + m.candidate.clock_identity.clock_id = 1; + m.generation = 1; + m.transition_operation_id.fill(0x55); + m.phase = ManifestPhase::Prepared; + + const auto participant = [&](ParticipantRole role, std::uint32_t slot, + std::string id, std::uint8_t incarnation_byte, + std::uint64_t pid) { + Participant p; + p.role = role; + p.slot_id = slot; + p.participant_id = std::move(id); + p.incarnation.fill(incarnation_byte); + p.process.container_id = std::string(63, 'a') + static_cast('0' + pid % 10); + p.process.pid = pid; + p.process.pid_start_ticks = pid + 10; + p.clock_identity = m.candidate.clock_identity; + return p; + }; + m.candidate.participants = { + participant(ParticipantRole::Witness, 0, "witness", 0x66, 104), + participant(ParticipantRole::Adapter, 0, "adapter", 0x77, 103), + participant(ParticipantRole::Replica, 19, "replica", 0x88, 102), + participant(ParticipantRole::Authority, 0, "authority", 0x22, 101), + }; + return m; +} + +ManifestCodecError Error(const ManifestDecodeResult& result) { + CHECK(std::holds_alternative(result)); + return std::get(result); +} + +void TestRoundTripAndCanonicalOrdering() { + const auto input = Fixture(); + const auto encoded = EncodeManifestV1(input); + CHECK(std::holds_alternative(encoded)); + const auto& text = std::get(encoded); + const auto decoded = DecodeManifestV1(text); + CHECK(std::holds_alternative(decoded)); + const auto& result = std::get(decoded); + CHECK(result.candidate.epoch_id == input.candidate.epoch_id); + CHECK(result.candidate.policy_digest == input.candidate.policy_digest); + CHECK(result.candidate.clock_identity == input.candidate.clock_identity); + CHECK(result.phase == input.phase && result.generation == input.generation); + CHECK(result.transition_operation_id == input.transition_operation_id); + CHECK(result.candidate.participants.front().role == ParticipantRole::Authority); + CHECK(result.candidate.participants.back().role == ParticipantRole::Witness); + CHECK(EncodeManifestV1(result) == encoded); + + const auto digest = ManifestDigestV1(input); + CHECK((std::holds_alternative>(digest))); + CHECK(Hex(std::get>(digest)) == + "727dfdb75bbcb4197d5000724c63c9d0b3db726238e5d0fa0670cabf1f655b0d"); + + // A changed but valid manifest with a recomputed digest is parseable. The + // digest is integrity checking, not authenticated rollback protection. + auto changed = input; + changed.candidate.participants.front().process.pid += 100; + const auto changed_encoded = EncodeManifestV1(changed); + CHECK(std::holds_alternative(changed_encoded)); + const auto changed_decoded = DecodeManifestV1(std::get(changed_encoded)); + CHECK(std::holds_alternative(changed_decoded)); + const auto changed_digest = ManifestDigestV1(changed); + CHECK((std::holds_alternative>(changed_digest))); + CHECK((std::get>(changed_digest) != + std::get>(digest))); +} + +void TestStrictEnvelopeFailures() { + const auto encoded = EncodeManifestV1(Fixture()); + CHECK(std::holds_alternative(encoded)); + const auto good = std::get(encoded); + CHECK(Error(DecodeManifestV1(good + " ")) == ManifestCodecError::NonCanonical); + + std::string wrong_digest = good; + const auto marker = wrong_digest.find("\"sha256\":\""); + CHECK(marker != std::string::npos); + const auto nibble = marker + 10; + wrong_digest[nibble] = wrong_digest[nibble] == '0' ? '1' : '0'; + CHECK(Error(DecodeManifestV1(wrong_digest)) == ManifestCodecError::DigestMismatch); + + const auto duplicate = std::string("{\"manifest\":{},\"manifest\":{},\"sha256\":\"") + + std::string(64, '0') + "\"}"; + CHECK(Error(DecodeManifestV1(duplicate)) == ManifestCodecError::DuplicateKey); + + auto unknown = good; + const auto phase = unknown.find("\"phase\":\"PREPARED\""); + CHECK(phase != std::string::npos); + unknown.insert(phase, "\"extra\":1,"); + CHECK(Error(DecodeManifestV1(unknown)) == ManifestCodecError::UnknownKey); + + CHECK(Error(DecodeManifestV1(std::string(kMaxManifestBytes + 1, ' '))) == + ManifestCodecError::TooLarge); +} + +void TestNonCanonicalIntegerAndClockValues() { + const auto encoded = EncodeManifestV1(Fixture()); + CHECK(std::holds_alternative(encoded)); + auto bad_generation = std::get(encoded); + const auto gen = bad_generation.find("\"generation\":\"1\""); + CHECK(gen != std::string::npos); + bad_generation.replace(gen, std::string("\"generation\":\"1\"").size(), + "\"generation\":\"01\""); + CHECK(Error(DecodeManifestV1(bad_generation)) == ManifestCodecError::InvalidValue); + + auto duplicate_escaped_key = std::get(encoded); + duplicate_escaped_key.insert(1, "\"sha256\":\"" + std::string(64, '0') + "\",\"sha\\u0036a256\":\"" + + std::string(64, '0') + "\","); + CHECK(Error(DecodeManifestV1(duplicate_escaped_key)) == ManifestCodecError::DuplicateKey); + + auto invalid = Fixture(); + invalid.candidate.clock_identity.monotonic_offset_nanoseconds = 1'000'000'000U; + CHECK(std::get(EncodeManifestV1(invalid)) == ManifestCodecError::InvalidValue); + invalid = Fixture(); + invalid.generation = 0; + CHECK(std::get(EncodeManifestV1(invalid)) == ManifestCodecError::InvalidValue); +} + +} // namespace + +int main() { + TestRoundTripAndCanonicalOrdering(); + TestStrictEnvelopeFailures(); + TestNonCanonicalIntegerAndClockValues(); + return 0; +} diff --git a/tests/supervisor/manifest_store_independent_test.cpp b/tests/supervisor/manifest_store_independent_test.cpp new file mode 100644 index 0000000..eb83cf3 --- /dev/null +++ b/tests/supervisor/manifest_store_independent_test.cpp @@ -0,0 +1,624 @@ +#include "supervisor/manifest_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::supervisor; +namespace fs = std::filesystem; + +#define CHECK(expr) do { if (!(expr)) { \ + std::cerr << "FAIL " << __FILE__ << ':' << __LINE__ << ": " #expr << '\n'; \ + std::abort(); \ +} } while (false) + +namespace { + +class TempRoot { + public: + TempRoot() { + std::string pattern = "/tmp/rg006-manifest-qa.XXXXXX"; + std::vector writable(pattern.begin(), pattern.end()); + writable.push_back('\0'); + char* made = ::mkdtemp(writable.data()); + CHECK(made != nullptr); + path_ = made; + } + ~TempRoot() { std::error_code ignored; fs::remove_all(path_, ignored); } + const fs::path& path() const { return path_; } + private: + fs::path path_; +}; + +EpochCandidate Candidate() { + EpochCandidate c; + c.epoch_id[0] = 1; + c.authority_incarnation[0] = 2; + c.policy_digest[0] = 3; + c.clock_identity.boot_uuid[0] = 4; + c.clock_identity.namespace_device = 11; + c.clock_identity.namespace_inode = 12; + c.clock_identity.clock_id = 1; + const auto add = [&](ParticipantRole role, std::uint32_t slot, const char* id, + std::uint8_t incarnation, char container, std::uint64_t pid) { + Participant p; + p.role = role; + p.slot_id = slot; + p.participant_id = id; + p.incarnation[0] = incarnation; + if (role == ParticipantRole::Authority) p.incarnation = c.authority_incarnation; + p.process.container_id = std::string(64, container); + p.process.pid = pid; + p.process.pid_start_ticks = pid + 100; + p.clock_identity = c.clock_identity; + c.participants.push_back(p); + }; + add(ParticipantRole::Authority, 0, "authority", 2, 'a', 101); + add(ParticipantRole::Witness, 0, "witness", 5, 'b', 102); + add(ParticipantRole::Replica, 0, "replica-zero", 6, 'c', 103); + add(ParticipantRole::Replica, UINT32_MAX, "replica-max", 7, 'd', 104); + add(ParticipantRole::Adapter, 0, "adapter-a", 8, 'e', 105); + add(ParticipantRole::Adapter, 0, "adapter-b", 9, 'f', 106); + return c; +} + +OperationId Op(std::uint8_t n) { OperationId op{}; op[0] = n; return op; } + +class FailOnce final : public IManifestFileOps { + public: + explicit FailOnce(ManifestIoPoint point) : point_(point) {} + bool FailAt(ManifestIoPoint point) noexcept override { + if (point == point_ && !used_.exchange(true)) return true; + return false; + } + bool used() const { return used_.load(); } + private: + ManifestIoPoint point_; + std::atomic used_{false}; +}; + +class FailNth final : public IManifestFileOps { + public: + FailNth(ManifestIoPoint point, unsigned nth) : point_(point), nth_(nth) {} + bool FailAt(ManifestIoPoint point) noexcept override { + if (point != point_) return false; + if (++seen_ == nth_) { triggered_ = true; return true; } + return false; + } + unsigned seen() const { return seen_; } + bool triggered() const { return triggered_; } + private: + ManifestIoPoint point_; + unsigned nth_; + unsigned seen_{}; + bool triggered_{}; +}; + +class ExitAtNth final : public IManifestFileOps { + public: + ExitAtNth(ManifestIoPoint point, unsigned nth, int exit_code) + : point_(point), nth_(nth), exit_code_(exit_code) {} + bool FailAt(ManifestIoPoint point) noexcept override { + if (point == point_ && ++seen_ == nth_) ::_exit(exit_code_); + return false; + } + private: + ManifestIoPoint point_; + unsigned nth_; + int exit_code_; + unsigned seen_{}; +}; + +class BlockAt final : public IManifestFileOps { + public: + BlockAt(ManifestIoPoint point, unsigned nth) : point_(point), nth_(nth) {} + bool FailAt(ManifestIoPoint point) noexcept override { + if (point != point_) return false; + std::unique_lock lock(mutex_); + if (++seen_ != nth_) return false; + if (arrived_) return false; + arrived_ = true; + condition_.notify_all(); + condition_.wait(lock, [&] { return released_; }); + return false; + } + void WaitUntilArrived() { + std::unique_lock lock(mutex_); + CHECK(condition_.wait_for(lock, std::chrono::seconds(5), [&] { return arrived_; })); + } + void Release() { + std::lock_guard lock(mutex_); + released_ = true; + condition_.notify_all(); + } + private: + ManifestIoPoint point_; + unsigned nth_; + unsigned seen_{}; + std::mutex mutex_; + std::condition_variable condition_; + bool arrived_{}; + bool released_{}; +}; + +std::unique_ptr Create(const fs::path& path, + const EpochCandidate& candidate = Candidate(), + const OperationId& op = Op(10), + IManifestFileOps* hooks = nullptr) { + auto result = ManifestStore::CreateNew(path.string(), candidate, op, hooks); + CHECK(std::holds_alternative>(result)); + return std::move(std::get>(result)); +} + +std::string ReadFile(const fs::path& path) { + std::ifstream in(path, std::ios::binary); + CHECK(in.good()); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); +} + +void WriteFile(const fs::path& path, std::string_view bytes) { + int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + CHECK(fd >= 0); + std::size_t offset = 0; + while (offset < bytes.size()) { + const ssize_t wrote = ::write(fd, bytes.data() + offset, bytes.size() - offset); + CHECK(wrote > 0); + offset += static_cast(wrote); + } + CHECK(::fsync(fd) == 0); + CHECK(::close(fd) == 0); +} + +void TestExclusiveCreateAndRecoveryReadOnly() { + TempRoot root; + const fs::path dir = root.path() / "epoch"; + auto store = Create(dir); + CHECK(store->writable()); + CHECK(!store->recovery_only()); + CHECK(store->snapshot().phase == ManifestPhase::Prepared); + CHECK(store->snapshot().generation == 1); + CHECK(store->snapshot().transition_operation_id == Op(10)); + struct stat st{}; + CHECK(::stat(dir.c_str(), &st) == 0 && (st.st_mode & 0777) == 0700); + CHECK(::stat((dir / "owner.lock").c_str(), &st) == 0 && (st.st_mode & 0777) == 0600); + CHECK(::stat((dir / "manifest.json").c_str(), &st) == 0 && (st.st_mode & 0777) == 0600); + const std::string before_duplicate = ReadFile(dir / "manifest.json"); + auto duplicate = ManifestStore::CreateNew(dir.string(), Candidate(), Op(11)); + CHECK(std::get_if(&duplicate) != nullptr); + CHECK(std::get(duplicate) == ManifestStoreError::AlreadyExists); + CHECK(ReadFile(dir / "manifest.json") == before_duplicate); + + const auto old_digest = store->digest(); + auto stale = store->Transition(7, old_digest, ManifestPhase::Active, Op(12)); + CHECK(stale.visibility == ManifestVisibility::NotVisible); + CHECK(stale.error == ManifestStoreError::CompareAndSwapMismatch); + CHECK(store->snapshot().phase == ManifestPhase::Prepared); + auto active = store->Transition(1, old_digest, ManifestPhase::Active, Op(13)); + CHECK(active.visibility == ManifestVisibility::Durable && !active.error); + CHECK(active.phase == ManifestPhase::Active && active.generation == 2); + store.reset(); + + auto opened = ManifestStore::OpenExisting(dir.string()); + CHECK(std::holds_alternative>(opened)); + auto recovery = std::move(std::get>(opened)); + CHECK(recovery->recovery_only() && !recovery->writable()); + CHECK(recovery->snapshot().phase == ManifestPhase::Active); + const auto recovered_digest = recovery->digest(); + auto forbidden = recovery->Transition(2, recovered_digest, ManifestPhase::Draining, Op(14)); + CHECK(forbidden.visibility == ManifestVisibility::NotVisible); + CHECK(forbidden.error == ManifestStoreError::RecoveryReadOnly); + CHECK(recovery->snapshot().phase == ManifestPhase::Active); +} + +void TestUnsortedInventoryCanonicalizationAndZeroCreationId() { + TempRoot root; + auto candidate = Candidate(); + std::reverse(candidate.participants.begin(), candidate.participants.end()); + auto store = Create(root.path() / "unsorted", candidate, Op(50)); + const auto original_digest = store->digest(); + const auto active = store->Transition(1, original_digest, ManifestPhase::Active, Op(51)); + CHECK(active.visibility == ManifestVisibility::Durable && !active.error); + CHECK(active.generation == 2); + CHECK(active.phase == ManifestPhase::Active); + store.reset(); + + auto reopened = ManifestStore::OpenExisting((root.path() / "unsorted").string()); + CHECK(std::holds_alternative>(reopened)); + const auto reopened_manifest = std::get>(reopened)->snapshot(); + const auto& participants = reopened_manifest.candidate.participants; + CHECK(participants.size() == candidate.participants.size()); + CHECK(std::is_sorted(participants.begin(), participants.end(), [](const Participant& a, + const Participant& b) { + if (a.role != b.role) return static_cast(a.role) < static_cast(b.role); + if (a.participant_id != b.participant_id) return a.participant_id < b.participant_id; + return a.slot_id < b.slot_id; + })); + + TempRoot zero_root; + const OperationId zero{}; + auto zero_op = ManifestStore::CreateNew((zero_root.path() / "zero").string(), Candidate(), zero); + CHECK(std::get_if(&zero_op) != nullptr); + CHECK(std::get(zero_op) == ManifestStoreError::OperationIdInvalid); + CHECK(!fs::exists(zero_root.path() / "zero")); +} + +void TestMissingAndCorruptManifestNeverInitialize() { + TempRoot root; + const auto dir = root.path() / "missing"; + auto store = Create(dir); + store.reset(); + CHECK(::unlink((dir / "manifest.json").c_str()) == 0); + auto missing = ManifestStore::OpenExisting(dir.string()); + CHECK(std::get_if(&missing) != nullptr); + CHECK(std::get(missing) == ManifestStoreError::MissingManifest); + CHECK(!fs::exists(dir / "manifest.json")); + + TempRoot root2; + const auto corrupt_dir = root2.path() / "corrupt"; + auto corrupt_store = Create(corrupt_dir); + corrupt_store.reset(); + WriteFile(corrupt_dir / "manifest.json", "{not valid json"); + auto corrupt = ManifestStore::OpenExisting(corrupt_dir.string()); + CHECK(std::get_if(&corrupt) != nullptr); + CHECK(!std::holds_alternative>(corrupt)); + CHECK(ReadFile(corrupt_dir / "manifest.json") == "{not valid json"); + + TempRoot root3; + const auto huge_dir = root3.path() / "oversized"; + auto huge_store = Create(huge_dir); + huge_store.reset(); + std::string oversized(kMaxManifestBytes + 1, ' '); + WriteFile(huge_dir / "manifest.json", oversized); + auto too_large = ManifestStore::OpenExisting(huge_dir.string()); + CHECK(std::get_if(&too_large) != nullptr); + CHECK(std::get(too_large) == ManifestStoreError::ManifestTooLarge); + CHECK(ReadFile(huge_dir / "manifest.json").size() == kMaxManifestBytes + 1); +} + +void TestValidDigestDoesNotAuthenticateInventoryAndStaleCasRejects() { + TempRoot root; + const auto dir = root.path() / "edited"; + auto original = Create(dir); + const auto original_digest = original->digest(); + auto edited = original->snapshot(); + auto adapter = std::find_if(edited.candidate.participants.begin(), edited.candidate.participants.end(), + [](const Participant& p) { return p.role == ParticipantRole::Adapter; }); + CHECK(adapter != edited.candidate.participants.end()); + adapter->process.pid = 9'000'001; + adapter->process.pid_start_ticks = 9'000'101; + auto encoded = EncodeManifestV1(edited); + CHECK(std::holds_alternative(encoded)); + WriteFile(dir / "manifest.json", std::get(encoded)); + const auto stale = original->Transition(1, original_digest, ManifestPhase::Active, Op(61)); + CHECK(stale.visibility == ManifestVisibility::NotVisible); + CHECK(stale.error == ManifestStoreError::CompareAndSwapMismatch); + CHECK(original->snapshot().phase == ManifestPhase::Prepared); + original.reset(); + + // The checksum is corruption detection, not authentication: a modified but + // structurally valid inventory with a recomputed digest is accepted as data. + auto opened = ManifestStore::OpenExisting(dir.string()); + CHECK(std::holds_alternative>(opened)); + auto recovery = std::move(std::get>(opened)); + const auto loaded = recovery->snapshot(); + const auto edited_adapter = std::find_if(loaded.candidate.participants.begin(), + loaded.candidate.participants.end(), + [](const Participant& p) { return p.role == ParticipantRole::Adapter; }); + CHECK(edited_adapter != loaded.candidate.participants.end()); + CHECK(edited_adapter->process.pid == 9'000'001); +} + +void TestDirectoryLockContendsAcrossProcess() { + TempRoot root; + const auto dir = root.path() / "locked"; + auto owner = Create(dir); + int pipefd[2]{}; + CHECK(::pipe(pipefd) == 0); + const pid_t child = ::fork(); + CHECK(child >= 0); + if (child == 0) { + ::close(pipefd[0]); + auto attempt = ManifestStore::OpenExisting(dir.string()); + const int code = std::get_if(&attempt) && + std::get(attempt) == ManifestStoreError::LockBusy ? 1 : 0; + if (::write(pipefd[1], &code, sizeof(code)) != sizeof(code)) ::_exit(74); + ::close(pipefd[1]); + ::_exit(0); + } + ::close(pipefd[1]); + int code = 0; + CHECK(::read(pipefd[0], &code, sizeof(code)) == sizeof(code)); + CHECK(::close(pipefd[0]) == 0); + int status = 0; + CHECK(::waitpid(child, &status, 0) == child); + CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 0); + CHECK(code == 1); + CHECK(owner->writable()); +} + +void TestProcessExitAroundRenameKeepsOnlyVisibleSnapshot() { + for (const bool exit_after_rename : {false, true}) { + TempRoot root; + const auto dir = root.path() / (exit_after_rename ? "after" : "before"); + const auto point = exit_after_rename ? ManifestIoPoint::SyncDirectory + : ManifestIoPoint::RenameManifest; + // For SyncDirectory, CreateNew uses initial dir sync and Prepared-manifest + // sync before the transition's post-rename directory sync. + const unsigned nth = exit_after_rename ? 3U : 2U; + auto crash = std::make_unique(point, nth, 73); + auto store = Create(dir, Candidate(), Op(10), crash.get()); + int pipefd[2]{}; + CHECK(::pipe(pipefd) == 0); + const pid_t child = ::fork(); + CHECK(child >= 0); + if (child == 0) { + ::close(pipefd[0]); + auto transitioned = store->Transition(1, store->digest(), ManifestPhase::Active, Op(71)); + const int code = transitioned.visibility == ManifestVisibility::Durable ? 0 : 2; + if (::write(pipefd[1], &code, sizeof(code)) != sizeof(code)) ::_exit(74); + ::_exit(0); + } + ::close(pipefd[1]); + int unexpected = 0; + const ssize_t got = ::read(pipefd[0], &unexpected, sizeof(unexpected)); + CHECK(got == 0); // The child exits at the injected crash boundary. + ::close(pipefd[0]); + int status = 0; + CHECK(::waitpid(child, &status, 0) == child); + CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 73); + store.reset(); + + auto reopened = ManifestStore::OpenExisting(dir.string()); + CHECK(std::holds_alternative>(reopened)); + const auto recovered = std::get>(reopened)->snapshot(); + CHECK(recovered.phase == (exit_after_rename ? ManifestPhase::Active : ManifestPhase::Prepared)); + CHECK(recovered.generation == (exit_after_rename ? 2U : 1U)); + CHECK(std::get>(reopened)->recovery_only()); + } +} + +void TestSymlinksModesAndLockIdentityFailClosed() { + TempRoot root; + const auto dir = root.path() / "bad-lock"; + auto store = Create(dir); + store.reset(); + CHECK(::unlink((dir / "owner.lock").c_str()) == 0); + CHECK(::symlink((root.path() / "target").c_str(), (dir / "owner.lock").c_str()) == 0); + auto bad_lock = ManifestStore::OpenExisting(dir.string()); + CHECK(std::get_if(&bad_lock) != nullptr); + CHECK(!std::holds_alternative>(bad_lock)); + + TempRoot root2; + const auto mode_dir = root2.path() / "bad-mode"; + auto mode_store = Create(mode_dir); + mode_store.reset(); + CHECK(::chmod(mode_dir.c_str(), 0755) == 0); + auto bad_mode = ManifestStore::OpenExisting(mode_dir.string()); + CHECK(std::get_if(&bad_mode) != nullptr); + CHECK(!std::holds_alternative>(bad_mode)); + + TempRoot root3; + const auto manifest_dir = root3.path() / "bad-manifest-link"; + auto manifest_store = Create(manifest_dir); + manifest_store.reset(); + CHECK(::unlink((manifest_dir / "manifest.json").c_str()) == 0); + WriteFile(root3.path() / "outside.json", "{}"); + CHECK(::symlink((root3.path() / "outside.json").c_str(), + (manifest_dir / "manifest.json").c_str()) == 0); + auto bad_manifest = ManifestStore::OpenExisting(manifest_dir.string()); + CHECK(std::get_if(&bad_manifest) != nullptr); + CHECK(!std::holds_alternative>(bad_manifest)); + CHECK(ReadFile(root3.path() / "outside.json") == "{}"); +} + +void TestFailureBoundariesAndWriterLatch() { + const std::array before_rename{ManifestIoPoint::CreateTemp, ManifestIoPoint::WriteTemp, + ManifestIoPoint::SyncTemp, ManifestIoPoint::RenameManifest}; + for (const auto point : before_rename) { + TempRoot root; + const auto dir = root.path() / "epoch"; + // The first occurrence creates the initial Prepared manifest; fail the + // second occurrence, which belongs to the requested phase transition. + auto fail = std::make_unique(point, 2); + auto store = Create(dir, Candidate(), Op(10), fail.get()); + const auto digest = store->digest(); + const auto result = store->Transition(1, digest, ManifestPhase::Active, Op(20)); + CHECK(fail->triggered()); + CHECK(result.visibility == ManifestVisibility::NotVisible); + CHECK(result.error.has_value()); + CHECK(store->snapshot().phase == ManifestPhase::Prepared); + CHECK(!store->writable()); + store.reset(); + auto opened = ManifestStore::OpenExisting(dir.string()); + CHECK(std::holds_alternative>(opened)); + CHECK(std::get>(opened)->snapshot().phase == + ManifestPhase::Prepared); + } + + TempRoot root; + const auto dir = root.path() / "uncertain"; + // Initial directory durability, Prepared-file durability, then transition + // durability: the third directory-sync is the post-transition rename fence. + auto fail = std::make_unique(ManifestIoPoint::SyncDirectory, 3); + auto store = Create(dir, Candidate(), Op(10), fail.get()); + const auto result = store->Transition(1, store->digest(), ManifestPhase::Active, Op(21)); + CHECK(fail->triggered()); + CHECK(result.visibility == ManifestVisibility::VisibleDurabilityUnknown); + CHECK(result.error == ManifestStoreError::DurabilityUncertain); + CHECK(store->snapshot().phase == ManifestPhase::Active); + CHECK(!store->writable()); + auto second = store->Transition(2, store->digest(), ManifestPhase::Draining, Op(22)); + CHECK(second.visibility == ManifestVisibility::NotVisible); + CHECK(second.error == ManifestStoreError::WriterLatched); + store.reset(); + auto recovery = ManifestStore::OpenExisting(dir.string()); + CHECK(std::holds_alternative>(recovery)); + CHECK(std::get>(recovery)->snapshot().phase == + ManifestPhase::Active); +} + +void TestReplacedLockAndStaleTempBlockCommit() { + TempRoot root; + const auto replaced_dir = root.path() / "replaced-lock"; + auto replaced = Create(replaced_dir); + const auto before = ReadFile(replaced_dir / "manifest.json"); + CHECK(::unlink((replaced_dir / "owner.lock").c_str()) == 0); + WriteFile(replaced_dir / "owner.lock", "replacement"); + auto lock_failure = replaced->Transition(1, replaced->digest(), ManifestPhase::Active, Op(81)); + CHECK(lock_failure.visibility == ManifestVisibility::NotVisible); + CHECK(lock_failure.error == ManifestStoreError::LockIdentityChanged); + CHECK(ReadFile(replaced_dir / "manifest.json") == before); + CHECK(!replaced->writable()); + replaced.reset(); + + TempRoot root2; + const auto temp_dir = root2.path() / "stale-temp"; + auto temp_store = Create(temp_dir); + WriteFile(temp_dir / "manifest.tmp", "stale incomplete write"); + const auto initial = ReadFile(temp_dir / "manifest.json"); + auto blocked = temp_store->Transition(1, temp_store->digest(), ManifestPhase::Active, Op(82)); + CHECK(blocked.visibility == ManifestVisibility::NotVisible); + CHECK(blocked.error == ManifestStoreError::WriteFailure); + CHECK(ReadFile(temp_dir / "manifest.json") == initial); + CHECK(!temp_store->writable()); +} + +void TestCreationFailureDoesNotTurnExistingPathIntoNewEpoch() { + const std::array create_points{ManifestIoPoint::Mkdir, ManifestIoPoint::SyncParentDirectory, + ManifestIoPoint::OpenDirectory, + ManifestIoPoint::ValidateDirectory, ManifestIoPoint::CreateLock, + ManifestIoPoint::AcquireLock, ManifestIoPoint::SyncLock, + ManifestIoPoint::CheckLockIdentity}; + for (const auto point : create_points) { + TempRoot root; + const auto dir = root.path() / "epoch"; + FailOnce fail(point); + auto created = ManifestStore::CreateNew(dir.string(), Candidate(), Op(30), &fail); + CHECK(fail.used()); + CHECK(std::get_if(&created) != nullptr); + CHECK(!std::holds_alternative>(created)); + // A failed partial initialization cannot be reopened as a valid epoch. + if (fs::exists(dir)) { + auto open = ManifestStore::OpenExisting(dir.string()); + CHECK(std::get_if(&open) != nullptr); + CHECK(!std::holds_alternative>(open)); + } + } +} + +void TestGenerationBoundsAndIndependentDirectoryLocks() { + CHECK(TryNextManifestGeneration(1) == 2); + CHECK(TryNextManifestGeneration(UINT64_MAX - 1) == UINT64_MAX); + CHECK(!TryNextManifestGeneration(UINT64_MAX)); + CHECK(!TryNextManifestGeneration(0)); + + TempRoot root; + auto first = Create(root.path() / "one"); + auto second = Create(root.path() / "two"); + CHECK(first->writable() && second->writable()); + // Store locks are per directory. This does not prove a global supervisor lock. +} + +void TestLegalPhaseGraphAndOperationIds() { + TempRoot root; + auto store = Create(root.path() / "phases"); + auto digest = store->digest(); + const OperationId zero{}; + auto zero_operation = store->Transition(1, digest, ManifestPhase::Draining, zero); + CHECK(zero_operation.visibility == ManifestVisibility::NotVisible); + CHECK(zero_operation.error == ManifestStoreError::OperationIdInvalid); + CHECK(store->snapshot().phase == ManifestPhase::Prepared); + + auto active = store->Transition(1, digest, ManifestPhase::Active, Op(91)); + CHECK(active.visibility == ManifestVisibility::Durable && !active.error); + auto illegal_same = store->Transition(2, active.digest, ManifestPhase::Active, Op(92)); + CHECK(illegal_same.visibility == ManifestVisibility::NotVisible); + CHECK(illegal_same.error == ManifestStoreError::IllegalTransition); + CHECK(store->writable()); + auto draining = store->Transition(2, active.digest, ManifestPhase::Draining, Op(93)); + CHECK(draining.visibility == ManifestVisibility::Durable && !draining.error); + auto closed = store->Transition(3, draining.digest, ManifestPhase::Closed, Op(94)); + CHECK(closed.visibility == ManifestVisibility::Durable && !closed.error); + auto reopened = store->Transition(4, closed.digest, ManifestPhase::Prepared, Op(95)); + CHECK(reopened.visibility == ManifestVisibility::NotVisible); + CHECK(reopened.error == ManifestStoreError::IllegalTransition); + CHECK(store->snapshot().phase == ManifestPhase::Closed); +} + +void TestNonRegularManifestDoesNotBlock() { + TempRoot root; + const auto directory = root.path() / "named-pipe"; + auto owner = Create(directory); + owner.reset(); + const auto manifest_path = directory / "manifest.json"; + CHECK(::unlink(manifest_path.c_str()) == 0); + CHECK(::mkfifo(manifest_path.c_str(), 0600) == 0); + auto result = ManifestStore::OpenExisting(directory.string()); + CHECK(std::get_if(&result) != nullptr); + CHECK(std::get(result) == ManifestStoreError::InvalidManifestFile); +} + +void TestInProcessTransitionSerialization() { + TempRoot root; + auto pause = std::make_unique(ManifestIoPoint::WriteTemp, 2); + auto store = Create(root.path() / "epoch", Candidate(), Op(40), pause.get()); + const auto digest = store->digest(); + std::optional result; + std::thread writer([&] { + result = store->Transition(1, digest, ManifestPhase::Active, Op(41)); + }); + pause->WaitUntilArrived(); + CHECK(store->snapshot().phase == ManifestPhase::Prepared); + CHECK(store->snapshot().generation == 1); + CHECK(store->digest() == digest); + auto competing = store->Transition(1, digest, ManifestPhase::Active, Op(42)); + CHECK(competing.visibility == ManifestVisibility::NotVisible); + CHECK(competing.error == ManifestStoreError::Busy); + pause->Release(); + writer.join(); + CHECK(result.has_value()); + CHECK(result->visibility == ManifestVisibility::Durable && !result->error); + CHECK(store->snapshot().phase == ManifestPhase::Active); +} + +} // namespace + +int main() { + static_assert(kMaxManifestBytes == 4U * 1024U * 1024U); + TestExclusiveCreateAndRecoveryReadOnly(); + TestUnsortedInventoryCanonicalizationAndZeroCreationId(); + TestMissingAndCorruptManifestNeverInitialize(); + TestValidDigestDoesNotAuthenticateInventoryAndStaleCasRejects(); + TestDirectoryLockContendsAcrossProcess(); + TestProcessExitAroundRenameKeepsOnlyVisibleSnapshot(); + TestSymlinksModesAndLockIdentityFailClosed(); + TestFailureBoundariesAndWriterLatch(); + TestReplacedLockAndStaleTempBlockCommit(); + TestCreationFailureDoesNotTurnExistingPathIntoNewEpoch(); + TestGenerationBoundsAndIndependentDirectoryLocks(); + TestLegalPhaseGraphAndOperationIds(); + TestNonRegularManifestDoesNotBlock(); + TestInProcessTransitionSerialization(); + std::cout << "independent manifest store checks passed\n"; +} diff --git a/tests/supervisor/manifest_store_test.cpp b/tests/supervisor/manifest_store_test.cpp new file mode 100644 index 0000000..a13bfcb --- /dev/null +++ b/tests/supervisor/manifest_store_test.cpp @@ -0,0 +1,197 @@ +#include "supervisor/manifest_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::supervisor; + +namespace { + +void Check(bool condition, const char* what) { + if (!condition) throw std::runtime_error(what); +} + +class OneShotFault final : public IManifestFileOps { + public: + ManifestIoPoint target{ManifestIoPoint::Mkdir}; + unsigned remaining{}; + bool FailAt(ManifestIoPoint point) noexcept override { + if (remaining == 0 || point != target) return false; + if (--remaining == 0) return true; + return false; + } +}; + +EpochCandidate Candidate() { + EpochCandidate c; + c.epoch_id[0] = 1; + c.authority_incarnation[0] = 2; + c.policy_digest[0] = 3; + c.clock_identity.boot_uuid[0] = 4; + c.clock_identity.namespace_device = 11; + c.clock_identity.namespace_inode = 12; + c.clock_identity.clock_id = 1; + const auto add = [&](ParticipantRole role, std::uint32_t slot, const char* participant, + std::uint8_t incarnation, char container, std::uint64_t pid) { + Participant p; + p.role = role; + p.slot_id = slot; + p.participant_id = participant; + p.incarnation[0] = incarnation; + if (role == ParticipantRole::Authority) p.incarnation = c.authority_incarnation; + p.process.container_id = std::string(64, container); + p.process.pid = pid; + p.process.pid_start_ticks = pid + 100; + p.clock_identity = c.clock_identity; + c.participants.push_back(std::move(p)); + }; + add(ParticipantRole::Authority, 0, "authority", 2, 'a', 101); + add(ParticipantRole::Witness, 0, "witness", 5, 'b', 102); + add(ParticipantRole::Replica, 0, "replica-zero", 6, 'c', 103); + add(ParticipantRole::Adapter, 0, "adapter", 8, 'd', 104); + return c; +} + +OperationId Operation(std::uint8_t first) { + OperationId op{}; + op[0] = first; + return op; +} + +std::string FreshPath(const char* suffix) { + const char* tmp = std::getenv("TMPDIR"); + const std::string root = tmp != nullptr && *tmp != '\0' ? tmp : "/tmp"; + return root + "/rateguard-manifest-" + std::to_string(::getpid()) + "-" + suffix; +} + +std::unique_ptr Create(const std::string& path, + IManifestFileOps* faults = nullptr) { + auto result = ManifestStore::CreateNew(path, Candidate(), Operation(1), faults); + if (auto* error = std::get_if(&result)) + std::cerr << "CreateNew error enum=" << static_cast(*error) << '\n'; + Check(std::holds_alternative>(result), + "CreateNew failed"); + return std::get>(std::move(result)); +} + +void TestDurableLifecycleAndRecovery() { + const auto path = FreshPath("normal"); + std::filesystem::remove_all(path); + auto store = Create(path); + Check(store->writable() && !store->recovery_only(), "new handle not writable"); + Check(store->snapshot().phase == ManifestPhase::Prepared, "initial phase not Prepared"); + Check(store->snapshot().generation == 1, "initial generation not one"); + struct stat st {}; + Check(::stat(path.c_str(), &st) == 0 && (st.st_mode & 07777) == 0700, + "store directory mode mismatch"); + Check(::stat((path + "/owner.lock").c_str(), &st) == 0 && (st.st_mode & 07777) == 0600, + "lock file mode mismatch"); + Check(::stat((path + "/manifest.json").c_str(), &st) == 0 && (st.st_mode & 07777) == 0600, + "manifest file mode mismatch"); + + const auto before_digest = store->digest(); + const auto activated = store->Transition(1, before_digest, ManifestPhase::Active, Operation(2)); + Check(activated.visibility == ManifestVisibility::Durable && !activated.error, + "Prepared to Active was not durable"); + Check(activated.generation == 2 && activated.phase == ManifestPhase::Active, + "transition metadata mismatch"); + auto duplicate_create = ManifestStore::CreateNew(path, Candidate(), Operation(1)); + Check(std::get_if(&duplicate_create) != nullptr && + std::get(duplicate_create) == ManifestStoreError::AlreadyExists, + "CreateNew reused existing directory"); + auto locked_open = ManifestStore::OpenExisting(path); + Check(std::get_if(&locked_open) != nullptr && + std::get(locked_open) == ManifestStoreError::LockBusy, + "second owner lock was not rejected"); + store.reset(); + + auto recovered = ManifestStore::OpenExisting(path); + Check(std::holds_alternative>(recovered), + "OpenExisting failed"); + auto recovery = std::get>(std::move(recovered)); + Check(recovery->recovery_only() && !recovery->writable(), "recovery handle writable"); + Check(recovery->snapshot().phase == ManifestPhase::Active, "recovery phase mismatch"); + const auto forbidden = recovery->Transition(2, recovery->digest(), ManifestPhase::Draining, + Operation(3)); + Check(forbidden.error == ManifestStoreError::RecoveryReadOnly, + "OpenExisting modified an active epoch"); + recovery.reset(); + std::filesystem::remove_all(path); +} + +void TestPreRenameFailureLatchesWriter() { + const auto path = FreshPath("pre-rename"); + std::filesystem::remove_all(path); + OneShotFault faults; + auto store = Create(path, &faults); + faults.target = ManifestIoPoint::WriteTemp; + faults.remaining = 1; + const auto result = store->Transition(1, store->digest(), ManifestPhase::Active, Operation(2)); + Check(result.visibility == ManifestVisibility::NotVisible && + result.error == ManifestStoreError::WriteFailure, + "pre-rename failure visibility mismatch"); + Check(!store->writable() && store->snapshot().phase == ManifestPhase::Prepared, + "failed write did not latch prior state"); + const auto retry = store->Transition(1, store->digest(), ManifestPhase::Active, Operation(2)); + Check(retry.error == ManifestStoreError::WriterLatched, "failed writer was reused"); + store.reset(); + std::filesystem::remove_all(path); +} + +void TestPostRenameDirectorySyncIsUncertain() { + const auto path = FreshPath("uncertain"); + std::filesystem::remove_all(path); + OneShotFault faults; + auto store = Create(path, &faults); + faults.target = ManifestIoPoint::SyncDirectory; + // Creation's syncs are complete before this fault is armed. + faults.remaining = 1; + const auto result = store->Transition(1, store->digest(), ManifestPhase::Active, Operation(2)); + Check(result.visibility == ManifestVisibility::VisibleDurabilityUnknown && + result.error == ManifestStoreError::DurabilityUncertain, + "post-rename sync failure was not reported uncertain"); + Check(!store->writable() && store->snapshot().phase == ManifestPhase::Active, + "visible snapshot not retained/latch missing"); + store.reset(); + auto reopened = ManifestStore::OpenExisting(path); + Check(std::holds_alternative>(reopened), + "visible uncertain manifest could not be inspected"); + auto recovery = std::get>(std::move(reopened)); + Check(recovery->snapshot().phase == ManifestPhase::Active, + "post-rename manifest was not visible"); + recovery.reset(); + std::filesystem::remove_all(path); +} + +void TestGenerationBoundaries() { + Check(TryNextManifestGeneration(1) == 2, "generation did not advance"); + Check(TryNextManifestGeneration(UINT64_MAX - 1) == UINT64_MAX, + "last generation step rejected"); + Check(!TryNextManifestGeneration(UINT64_MAX), "generation wrapped"); + Check(!TryNextManifestGeneration(0), "zero generation accepted"); +} + +} // namespace + +int main() { + try { + TestDurableLifecycleAndRecovery(); + TestPreRenameFailureLatchesWriter(); + TestPostRenameDirectorySyncIsUncertain(); + TestGenerationBoundaries(); + std::cout << "manifest store tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "manifest store test failure: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/supervisor/runtime_owner_independent_test.cpp b/tests/supervisor/runtime_owner_independent_test.cpp new file mode 100644 index 0000000..da2d1c5 --- /dev/null +++ b/tests/supervisor/runtime_owner_independent_test.cpp @@ -0,0 +1,645 @@ +#include "supervisor/runtime_owner.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::supervisor; +namespace fs = std::filesystem; + +#define CHECK(expr) do { if (!(expr)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #expr); \ + std::abort(); \ +} } while (false) + +namespace { + +class TempRoot { + public: + TempRoot() { + std::string pattern = "/tmp/rg006-runtime-qa.XXXXXX"; + std::vector writable(pattern.begin(), pattern.end()); + writable.push_back('\0'); + char* made = ::mkdtemp(writable.data()); + CHECK(made != nullptr); + path_ = made; + } + ~TempRoot() { std::error_code ignored; fs::remove_all(path_, ignored); } + const fs::path& path() const { return path_; } + private: + fs::path path_; +}; + +RuntimeDomainId Domain(std::uint8_t value) { + RuntimeDomainId id{}; + id[0] = value; + return id; +} + +EpochId Epoch(std::uint8_t value) { + EpochId id{}; + id[0] = value; + return id; +} + +std::string ReadFile(const fs::path& path) { + std::ifstream in(path, std::ios::binary); + CHECK(in.good()); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); +} + +void WriteFile(const fs::path& path, std::string_view bytes) { + const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + CHECK(fd >= 0); + std::size_t offset = 0; + while (offset < bytes.size()) { + const ssize_t n = ::write(fd, bytes.data() + offset, bytes.size() - offset); + CHECK(n > 0); + offset += static_cast(n); + } + CHECK(::fsync(fd) == 0); + CHECK(::close(fd) == 0); +} + +class FailOnce final : public IRuntimeOwnerIo { + public: + explicit FailOnce(RuntimeOwnerIoPoint point) : point_(point) {} + bool FailAt(RuntimeOwnerIoPoint point) noexcept override { + if (point == point_ && !fired_) { fired_ = true; return true; } + return false; + } + bool fired() const { return fired_; } + private: + RuntimeOwnerIoPoint point_; + bool fired_{}; +}; + +class ArmableFailOnce final : public IRuntimeOwnerIo { + public: + explicit ArmableFailOnce(RuntimeOwnerIoPoint point) : point_(point) {} + void Arm() noexcept { armed_ = true; } + bool fired() const noexcept { return fired_; } + bool FailAt(RuntimeOwnerIoPoint point) noexcept override { + if (armed_ && point == point_ && !fired_) { fired_ = true; return true; } + return false; + } + private: + RuntimeOwnerIoPoint point_; + bool armed_{}; + bool fired_{}; +}; + +class FailNth final : public IRuntimeOwnerIo { + public: + FailNth(RuntimeOwnerIoPoint point, unsigned nth) : point_(point), nth_(nth) {} + bool FailAt(RuntimeOwnerIoPoint point) noexcept override { + if (point != point_) return false; + if (++seen_ == nth_) { fired_ = true; return true; } + return false; + } + bool fired() const noexcept { return fired_; } + private: + RuntimeOwnerIoPoint point_; + unsigned nth_; + unsigned seen_{}; + bool fired_{}; +}; + +class ExitAtNth final : public IRuntimeOwnerIo { + public: + ExitAtNth(RuntimeOwnerIoPoint point, unsigned nth, int status) + : point_(point), nth_(nth), status_(status) {} + bool FailAt(RuntimeOwnerIoPoint point) noexcept override { + if (point == point_ && ++seen_ == nth_) ::_exit(status_); + return false; + } + private: + RuntimeOwnerIoPoint point_; + unsigned nth_; + int status_; + unsigned seen_{}; +}; + +std::unique_ptr MustCreate(const fs::path& path, RuntimeDomainId domain = Domain(1), + IRuntimeOwnerIo* hooks = nullptr) { + auto result = RuntimeOwner::CreateNew(path.string(), domain, hooks); + CHECK(std::holds_alternative>(result)); + return std::move(std::get>(result)); +} + +void CheckCloexecFd(const DuplicateFdResult& result) { + CHECK(std::holds_alternative(result)); + const int fd = std::get(result); + CHECK(fd >= 0); + const int flags = ::fcntl(fd, F_GETFD); + CHECK(flags >= 0 && (flags & FD_CLOEXEC) != 0); + CHECK(::close(fd) == 0); +} + +void CheckOwnerError(const RuntimeOwnerCheck& result, RuntimeOwnerError expected) { + CHECK(std::get_if(&result) != nullptr); + CHECK(std::get(result) == expected); +} + +void TestFreshCreateClaimAndExistingRecovery() { + TempRoot tmp; + const auto root = tmp.path() / "runtime"; + auto owner = MustCreate(root); + CHECK(owner->mode() == RuntimeOwnerMode::Fresh); + CHECK(owner->domain_id() == Domain(1)); + CHECK(owner->root_path() == (fs::canonical(root.parent_path()) / root.filename()).string()); + CHECK(std::holds_alternative(owner->ValidateOwnership())); + CheckCloexecFd(owner->DuplicateRootFd()); + struct stat st{}; + CHECK(::stat(root.c_str(), &st) == 0 && (st.st_mode & 07777) == 0700); + CHECK(::stat((root / "owner.lock").c_str(), &st) == 0 && (st.st_mode & 07777) == 0600); + CHECK(::stat((root / "runtime-anchor.json").c_str(), &st) == 0 && (st.st_mode & 07777) == 0600); + + auto claim_result = owner->ClaimInitialEpoch(Epoch(7)); + CHECK(std::holds_alternative(claim_result)); + auto claim = std::move(std::get(claim_result)); + CHECK(claim.epoch_id() == Epoch(7)); + CHECK(claim.domain_id() == Domain(1)); + CHECK(claim.root_path() == owner->root_path()); + CHECK(std::holds_alternative(claim.ValidateOwnership())); + CheckCloexecFd(claim.DuplicateRootFd()); + const auto second_claim = owner->ClaimInitialEpoch(Epoch(8)); + CHECK(std::get_if(&second_claim) != nullptr); + CHECK(std::get(second_claim) == RuntimeOwnerError::InitialClaimAlreadyUsed); + CHECK(std::holds_alternative(owner->ValidateOwnership())); + + auto busy = RuntimeOwner::OpenExisting(root.string(), Domain(1)); + CHECK(std::get_if(&busy) != nullptr); + CHECK(std::get(busy) == RuntimeOwnerError::LockBusy); + auto duplicate = RuntimeOwner::CreateNew(root.string(), Domain(2)); + CHECK(std::get_if(&duplicate) != nullptr); + CHECK(std::get(duplicate) == RuntimeOwnerError::AlreadyExists); + + // A claimed epoch keeps the exclusive lock alive after its owner wrapper is dropped. + owner.reset(); + auto still_busy = RuntimeOwner::OpenExisting(root.string(), Domain(1)); + CHECK(std::get_if(&still_busy) != nullptr); + CHECK(std::get(still_busy) == RuntimeOwnerError::LockBusy); + // Claim remains alive in this scope; the lock cannot be released by resetting the owner. +} + +void TestOpenExistingRequiresValidAnchorAndNeverCreates() { + TempRoot tmp; + const auto missing = tmp.path() / "missing"; + auto absent = RuntimeOwner::OpenExisting(missing.string(), Domain(1)); + CHECK(std::get_if(&absent) != nullptr); + CHECK(!fs::exists(missing)); + + const auto root = tmp.path() / "runtime"; + { + auto owner = MustCreate(root); + CHECK(owner->ClaimInitialEpoch(Epoch(9)).index() == 0); + } + auto recovery = RuntimeOwner::OpenExisting(root.string(), Domain(1)); + CHECK(std::holds_alternative>(recovery)); + auto existing = std::move(std::get>(recovery)); + CHECK(existing->mode() == RuntimeOwnerMode::RecoveryRequired); + CHECK(std::holds_alternative(existing->ValidateOwnership())); + auto forbidden = existing->ClaimInitialEpoch(Epoch(10)); + CHECK(std::get_if(&forbidden) != nullptr); + CHECK(std::get(forbidden) == RuntimeOwnerError::RecoveryRequired); + existing.reset(); + + CHECK(::unlink((root / "runtime-anchor.json").c_str()) == 0); + auto missing_anchor = RuntimeOwner::OpenExisting(root.string(), Domain(1)); + CHECK(std::get_if(&missing_anchor) != nullptr); + CHECK(!std::holds_alternative>(missing_anchor)); + auto cannot_reinitialize = RuntimeOwner::CreateNew(root.string(), Domain(1)); + CHECK(std::get_if(&cannot_reinitialize) != nullptr); + CHECK(std::get(cannot_reinitialize) == RuntimeOwnerError::AlreadyExists); + CHECK(!fs::exists(root / "runtime-anchor.json")); +} + +void TestDomainAndPathBinding() { + TempRoot tmp; + const auto root = tmp.path() / "runtime"; + auto owner = MustCreate(root, Domain(3)); + const auto bytes = ReadFile(root / "runtime-anchor.json"); + owner.reset(); + auto wrong_domain = RuntimeOwner::OpenExisting(root.string(), Domain(4)); + CHECK(std::get_if(&wrong_domain) != nullptr); + CHECK(std::get(wrong_domain) == RuntimeOwnerError::DomainMismatch); + CHECK(ReadFile(root / "runtime-anchor.json") == bytes); + + auto relative = RuntimeOwner::CreateNew("relative/root", Domain(1)); + CHECK(std::get_if(&relative) != nullptr); + CHECK(std::get(relative) == RuntimeOwnerError::InvalidPath); + CHECK(!fs::exists("relative")); +} + +void TestRootLockSurvivesTokenAndSeparatesConfiguredRoots() { + TempRoot tmp; + const auto root_a = tmp.path() / "a"; + const auto root_b = tmp.path() / "b"; + auto a = MustCreate(root_a, Domain(5)); + auto claim_result = a->ClaimInitialEpoch(Epoch(11)); + CHECK(std::holds_alternative(claim_result)); + auto claim = std::move(std::get(claim_result)); + a.reset(); + auto b = MustCreate(root_b, Domain(5)); + CHECK(b->mode() == RuntimeOwnerMode::Fresh); + auto locked_a = RuntimeOwner::OpenExisting(root_a.string(), Domain(5)); + CHECK(std::get_if(&locked_a) != nullptr); + CHECK(std::get(locked_a) == RuntimeOwnerError::LockBusy); + // Distinct roots are intentionally independent; deployment reconciliation is external. +} + +void TestForkedOwnerCannotValidateOrClaim() { + TempRoot tmp; + const auto root = tmp.path() / "runtime"; + auto owner = MustCreate(root, Domain(8)); + int pipefd[2]{}; + CHECK(::pipe(pipefd) == 0); + const pid_t child = ::fork(); + CHECK(child >= 0); + if (child == 0) { + ::close(pipefd[0]); + const auto validation = owner->ValidateOwnership(); + const int valid_error = std::get_if(&validation) + ? static_cast(std::get(validation)) : -1; + auto claim = owner->ClaimInitialEpoch(Epoch(12)); + const int claim_error = std::get_if(&claim) + ? static_cast(std::get(claim)) : -1; + const int values[] = {valid_error, claim_error}; + if (::write(pipefd[1], values, sizeof(values)) != sizeof(values)) ::_exit(74); + ::_exit(0); + } + ::close(pipefd[1]); + int values[2] = {-1, -1}; + CHECK(::read(pipefd[0], values, sizeof(values)) == sizeof(values)); + CHECK(::close(pipefd[0]) == 0); + int status = 0; + CHECK(::waitpid(child, &status, 0) == child); + CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 0); + CHECK(values[0] == static_cast(RuntimeOwnerError::OwnerProcessChanged)); + CHECK(values[1] == static_cast(RuntimeOwnerError::OwnerProcessChanged)); + CHECK(std::holds_alternative(owner->ValidateOwnership())); +} + +void TestAnchorLockAndRootReplacementFailClosed() { + TempRoot tmp; + const auto root = tmp.path() / "root-anchor"; + auto owner = MustCreate(root, Domain(13)); + const auto anchor = ReadFile(root / "runtime-anchor.json"); + CHECK(::unlink((root / "runtime-anchor.json").c_str()) == 0); + WriteFile(root / "runtime-anchor.json", anchor); + const auto changed_anchor = owner->ValidateOwnership(); + CHECK(std::get_if(&changed_anchor) != nullptr); + CHECK(std::get(changed_anchor) == RuntimeOwnerError::AnchorIdentityChanged); + const auto displaced = tmp.path() / "original-anchor"; + CHECK(::rename((root / "runtime-anchor.json").c_str(), displaced.c_str()) == 0); + WriteFile(root / "runtime-anchor.json", anchor); + CheckOwnerError(owner->ValidateOwnership(), RuntimeOwnerError::AnchorIdentityChanged); + CHECK(::unlink((root / "runtime-anchor.json").c_str()) == 0); + CHECK(::rename(displaced.c_str(), (root / "runtime-anchor.json").c_str()) == 0); + const auto restored_anchor = owner->ValidateOwnership(); + CHECK(std::get_if(&restored_anchor) != nullptr); + CHECK(std::get(restored_anchor) == RuntimeOwnerError::AnchorIdentityChanged); + CHECK(owner->mode() == RuntimeOwnerMode::RecoveryRequired); + + TempRoot tmp2; + const auto lock_root = tmp2.path() / "root-lock"; + auto locked = MustCreate(lock_root, Domain(14)); + CHECK(::unlink((lock_root / "owner.lock").c_str()) == 0); + WriteFile(lock_root / "owner.lock", "new inode"); + const auto changed_lock = locked->ValidateOwnership(); + CHECK(std::get_if(&changed_lock) != nullptr); + CHECK(std::get(changed_lock) == RuntimeOwnerError::LockIdentityChanged); + CHECK(locked->mode() == RuntimeOwnerMode::RecoveryRequired); + + TempRoot tmp3; + const auto replaced_root = tmp3.path() / "root-path"; + auto rooted = MustCreate(replaced_root, Domain(15)); + const auto moved = tmp3.path() / "old-root"; + CHECK(::rename(replaced_root.c_str(), moved.c_str()) == 0); + CHECK(::mkdir(replaced_root.c_str(), 0700) == 0); + const auto changed_root = rooted->ValidateOwnership(); + CHECK(std::get_if(&changed_root) != nullptr); + CHECK(std::get(changed_root) == RuntimeOwnerError::RootIdentityChanged); + CHECK(::rmdir(replaced_root.c_str()) == 0); + CHECK(::rename(moved.c_str(), replaced_root.c_str()) == 0); + const auto restored_root = rooted->ValidateOwnership(); + CHECK(std::get_if(&restored_root) != nullptr); + CHECK(std::get(restored_root) == RuntimeOwnerError::RootIdentityChanged); + CHECK(rooted->mode() == RuntimeOwnerMode::RecoveryRequired); +} + +void TestAnchorSymlinkAndUnexpectedEntry() { + TempRoot tmp; + const auto root = tmp.path() / "anchor-link"; + { + auto owner = MustCreate(root, Domain(17)); + } + const auto outside = tmp.path() / "outside"; + WriteFile(outside, "not an anchor"); + CHECK(::unlink((root / "runtime-anchor.json").c_str()) == 0); + CHECK(::symlink(outside.c_str(), (root / "runtime-anchor.json").c_str()) == 0); + auto symlink_anchor = RuntimeOwner::OpenExisting(root.string(), Domain(17)); + CHECK(std::get_if(&symlink_anchor) != nullptr); + + TempRoot tmp2; + const auto extra_root = tmp2.path() / "extra"; + auto owner = MustCreate(extra_root, Domain(18)); + const EpochId zero_epoch{}; + const auto invalid_epoch = owner->ClaimInitialEpoch(zero_epoch); + CHECK(std::get_if(&invalid_epoch) != nullptr); + CHECK(std::get(invalid_epoch) == RuntimeOwnerError::InvalidEpochId); + CHECK(std::holds_alternative(owner->ValidateOwnership())); + WriteFile(extra_root / "unregistered", "unexpected"); + const auto unexpected = owner->ClaimInitialEpoch(Epoch(18)); + CHECK(std::get_if(&unexpected) != nullptr); + CHECK(std::get(unexpected) == RuntimeOwnerError::UnexpectedRootEntry); +} + +void TestOneOwnershipFailurePoisonsOwnerAndClaim() { + TempRoot tmp; + auto io = std::make_unique(RuntimeOwnerIoPoint::CheckRootIdentity); + auto owner = MustCreate(tmp.path() / "poison", Domain(19), io.get()); + auto result = owner->ClaimInitialEpoch(Epoch(19)); + CHECK(std::holds_alternative(result)); + auto claim = std::move(std::get(result)); + io->Arm(); + + const auto first = claim.ValidateOwnership(); + CHECK(std::get_if(&first) != nullptr); + CHECK(std::get(first) == RuntimeOwnerError::RootIdentityChanged); + CHECK(owner->mode() == RuntimeOwnerMode::RecoveryRequired); + const auto later = owner->ValidateOwnership(); + CHECK(std::get_if(&later) != nullptr); + CHECK(std::get(later) == RuntimeOwnerError::RootIdentityChanged); + const auto duplicate = owner->DuplicateRootFd(); + CHECK(std::get_if(&duplicate) != nullptr); + CHECK(std::get(duplicate) == RuntimeOwnerError::RootIdentityChanged); + const auto other_claim = owner->ClaimInitialEpoch(Epoch(20)); + CHECK(std::get_if(&other_claim) != nullptr); + CHECK(std::get(other_claim) == RuntimeOwnerError::RecoveryRequired); +} + +void TestSecondClaimAfterLegitimateChildDoesNotPoisonWinner() { + TempRoot tmp; + auto io = std::make_unique(RuntimeOwnerIoPoint::EnumerateRoot); + auto owner = MustCreate(tmp.path() / "runtime", Domain(20), io.get()); + auto first_result = owner->ClaimInitialEpoch(Epoch(20)); + CHECK(std::holds_alternative(first_result)); + auto token = std::move(std::get(first_result)); + const auto root_fd = token.DuplicateRootFd(); + CHECK(std::holds_alternative(root_fd)); + const int fd = std::get(root_fd); + CHECK(::mkdirat(fd, "epoch-0001", 0700) == 0); + CHECK(::close(fd) == 0); + + // A later claimant must check the already-consumed flag before inspecting a + // root whose authorized bootstrap has now added an epoch child entry. + io->Arm(); + const auto second = owner->ClaimInitialEpoch(Epoch(21)); + CHECK(std::get_if(&second) != nullptr); + CHECK(std::get(second) == RuntimeOwnerError::InitialClaimAlreadyUsed); + CHECK(!io->fired()); + CHECK(owner->mode() == RuntimeOwnerMode::Fresh); + CHECK(std::holds_alternative(owner->ValidateOwnership())); + CHECK(std::holds_alternative(token.ValidateOwnership())); +} + +void TestConcurrentClaimHasOneWinnerWithoutPoisoning() { + TempRoot tmp; + auto owner = MustCreate(tmp.path() / "runtime", Domain(24)); + std::barrier start(3); + std::atomic success{0}; + std::atomic already_used{0}; + std::atomic busy{0}; + std::atomic unexpected{0}; + const auto worker = [&](std::uint8_t epoch_byte) { + start.arrive_and_wait(); + auto result = owner->ClaimInitialEpoch(Epoch(epoch_byte)); + if (std::holds_alternative(result)) { + success.fetch_add(1, std::memory_order_relaxed); + } else if (std::get(result) == RuntimeOwnerError::InitialClaimAlreadyUsed) { + already_used.fetch_add(1, std::memory_order_relaxed); + } else if (std::get(result) == RuntimeOwnerError::Busy) { + busy.fetch_add(1, std::memory_order_relaxed); + } else { + unexpected.fetch_add(1, std::memory_order_relaxed); + } + }; + std::thread one(worker, 25); + std::thread two(worker, 26); + start.arrive_and_wait(); + one.join(); + two.join(); + CHECK(success.load(std::memory_order_relaxed) == 1); + CHECK(already_used.load(std::memory_order_relaxed) + busy.load(std::memory_order_relaxed) == 1); + CHECK(unexpected.load(std::memory_order_relaxed) == 0); + CHECK(owner->mode() == RuntimeOwnerMode::Fresh); + CHECK(std::holds_alternative(owner->ValidateOwnership())); +} + +void TestExternalDirectoryScanDoesNotAdvanceOwnerEnumeration() { + TempRoot tmp; + auto owner = MustCreate(tmp.path() / "runtime", Domain(27)); + auto duplicate = owner->DuplicateRootFd(); + CHECK(std::holds_alternative(duplicate)); + DIR* directory = ::fdopendir(std::get(duplicate)); + CHECK(directory != nullptr); + bool saw_anchor = false; + bool saw_lock = false; + while (dirent* entry = ::readdir(directory)) { + const std::string name(entry->d_name); + if (name == "runtime-anchor.json") saw_anchor = true; + if (name == "owner.lock") saw_lock = true; + } + CHECK(saw_anchor && saw_lock); + CHECK(::closedir(directory) == 0); + + const auto claim = owner->ClaimInitialEpoch(Epoch(27)); + CHECK(std::holds_alternative(claim)); + CHECK(std::holds_alternative(owner->ValidateOwnership())); +} + +void TestCreateFailureNeverBecomesFreshOrReinitializes() { + const std::array fail_points{ + RuntimeOwnerIoPoint::ResolveParent, + RuntimeOwnerIoPoint::MkdirRoot, + RuntimeOwnerIoPoint::SyncParent, + RuntimeOwnerIoPoint::OpenRoot, + RuntimeOwnerIoPoint::ValidateRoot, + RuntimeOwnerIoPoint::CreateLock, + RuntimeOwnerIoPoint::AcquireLock, + RuntimeOwnerIoPoint::SyncLock, + RuntimeOwnerIoPoint::SyncRoot, + RuntimeOwnerIoPoint::CreateAnchorTemp, + RuntimeOwnerIoPoint::WriteAnchor, + RuntimeOwnerIoPoint::SyncAnchor, + RuntimeOwnerIoPoint::RenameAnchor, + }; + for (const auto point : fail_points) { + TempRoot tmp; + const auto root = tmp.path() / "runtime"; + FailNth hooks(point, 1U); + auto created = RuntimeOwner::CreateNew(root.string(), Domain(21), &hooks); + CHECK(hooks.fired()); + CHECK(std::get_if(&created) != nullptr); + CHECK(!std::holds_alternative>(created)); + if (fs::exists(root)) { + auto reopened = RuntimeOwner::OpenExisting(root.string(), Domain(21)); + if (std::holds_alternative>(reopened)) { + auto recovery = std::move(std::get>(reopened)); + CHECK(recovery->mode() == RuntimeOwnerMode::RecoveryRequired); + const auto claim = recovery->ClaimInitialEpoch(Epoch(22)); + CHECK(std::get_if(&claim) != nullptr); + } + auto retry = RuntimeOwner::CreateNew(root.string(), Domain(21)); + CHECK(std::get_if(&retry) != nullptr); + CHECK(std::get(retry) == RuntimeOwnerError::AlreadyExists); + } + } + + // Isolate the after-rename but before root-fsync boundary: the anchor may be + // visible, but only recovery can open it and no initial claim is issued. + TempRoot tmp; + const auto root = tmp.path() / "uncertain"; + FailNth after_rename(RuntimeOwnerIoPoint::SyncRoot, 2); + auto uncertain = RuntimeOwner::CreateNew(root.string(), Domain(22), &after_rename); + CHECK(after_rename.fired()); + CHECK(std::get_if(&uncertain) != nullptr); + CHECK(std::get(uncertain) == RuntimeOwnerError::DurabilityUncertain); + auto recovery = RuntimeOwner::OpenExisting(root.string(), Domain(22)); + CHECK(std::holds_alternative>(recovery)); + auto recovered = std::move(std::get>(recovery)); + CHECK(recovered->mode() == RuntimeOwnerMode::RecoveryRequired); + auto no_claim = recovered->ClaimInitialEpoch(Epoch(23)); + CHECK(std::get_if(&no_claim) != nullptr); +} + +int OpenExistingErrorBounded(const std::string& path, RuntimeDomainId domain) { + int fds[2]{}; + CHECK(::pipe(fds) == 0); + const pid_t child = ::fork(); + CHECK(child >= 0); + if (child == 0) { + ::close(fds[0]); + auto opened = RuntimeOwner::OpenExisting(path, domain); + const int code = std::get_if(&opened) + ? static_cast(std::get(opened)) : -1; + if (::write(fds[1], &code, sizeof(code)) != sizeof(code)) ::_exit(74); + ::_exit(0); + } + ::close(fds[1]); + pollfd event{fds[0], POLLIN, 0}; + const int ready = ::poll(&event, 1, 3000); + if (ready != 1) { + (void)::kill(child, SIGKILL); + int ignored = 0; + (void)::waitpid(child, &ignored, 0); + ::close(fds[0]); + CHECK(false && "OpenExisting must reject FIFO entries without blocking"); + } + int code = -1; + CHECK(::read(fds[0], &code, sizeof(code)) == sizeof(code)); + CHECK(::close(fds[0]) == 0); + int status = 0; + CHECK(::waitpid(child, &status, 0) == child); + CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 0); + return code; +} + +void TestOpenExistingRejectsFifoLockAndAnchorWithoutBlocking() { + TempRoot tmp; + const auto root = tmp.path() / "fifo-anchor"; + { + auto owner = MustCreate(root, Domain(31)); + } + CHECK(::unlink((root / "runtime-anchor.json").c_str()) == 0); + CHECK(::mkfifo((root / "runtime-anchor.json").c_str(), 0600) == 0); + CHECK(OpenExistingErrorBounded(root.string(), Domain(31)) == + static_cast(RuntimeOwnerError::InvalidAnchor)); + + TempRoot tmp2; + const auto lock_root = tmp2.path() / "fifo-lock"; + { + auto owner = MustCreate(lock_root, Domain(32)); + } + CHECK(::unlink((lock_root / "owner.lock").c_str()) == 0); + CHECK(::mkfifo((lock_root / "owner.lock").c_str(), 0600) == 0); + CHECK(OpenExistingErrorBounded(lock_root.string(), Domain(32)) == + static_cast(RuntimeOwnerError::InvalidLock)); +} + +void TestProcessCrashBeforeAndAfterAnchorRename() { + for (const bool after_rename : {false, true}) { + TempRoot tmp; + const auto root = tmp.path() / "runtime"; + const auto target = after_rename ? RuntimeOwnerIoPoint::SyncRoot + : RuntimeOwnerIoPoint::RenameAnchor; + const unsigned nth = after_rename ? 2U : 1U; + const pid_t child = ::fork(); + CHECK(child >= 0); + if (child == 0) { + ExitAtNth crash(target, nth, 79); + (void)RuntimeOwner::CreateNew(root.string(), Domain(41), &crash); + ::_exit(0); + } + int status = 0; + CHECK(::waitpid(child, &status, 0) == child); + CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 79); + + auto opened = RuntimeOwner::OpenExisting(root.string(), Domain(41)); + if (after_rename) { + CHECK(std::holds_alternative>(opened)); + auto recovery = std::move(std::get>(opened)); + CHECK(recovery->mode() == RuntimeOwnerMode::RecoveryRequired); + CHECK(std::get(recovery->ClaimInitialEpoch(Epoch(42))) == + RuntimeOwnerError::RecoveryRequired); + } else { + CHECK(std::get_if(&opened) != nullptr); + CHECK(std::get(opened) == RuntimeOwnerError::AnchorMissing); + } + auto cannot_reinit = RuntimeOwner::CreateNew(root.string(), Domain(41)); + CHECK(std::get_if(&cannot_reinit) != nullptr); + CHECK(std::get(cannot_reinit) == RuntimeOwnerError::AlreadyExists); + } +} + +} // namespace + +int main() { + TestFreshCreateClaimAndExistingRecovery(); + TestOpenExistingRequiresValidAnchorAndNeverCreates(); + TestDomainAndPathBinding(); + TestRootLockSurvivesTokenAndSeparatesConfiguredRoots(); + TestForkedOwnerCannotValidateOrClaim(); + TestAnchorLockAndRootReplacementFailClosed(); + TestAnchorSymlinkAndUnexpectedEntry(); + TestOneOwnershipFailurePoisonsOwnerAndClaim(); + TestSecondClaimAfterLegitimateChildDoesNotPoisonWinner(); + TestConcurrentClaimHasOneWinnerWithoutPoisoning(); + TestExternalDirectoryScanDoesNotAdvanceOwnerEnumeration(); + TestCreateFailureNeverBecomesFreshOrReinitializes(); + TestOpenExistingRejectsFifoLockAndAnchorWithoutBlocking(); + TestProcessCrashBeforeAndAfterAnchorRename(); + std::puts("independent runtime owner checks passed"); +} diff --git a/tests/supervisor/runtime_owner_test.cpp b/tests/supervisor/runtime_owner_test.cpp new file mode 100644 index 0000000..3378896 --- /dev/null +++ b/tests/supervisor/runtime_owner_test.cpp @@ -0,0 +1,265 @@ +#include "supervisor/runtime_owner.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::supervisor; + +namespace { + +void Check(bool condition, const char* what) { + if (!condition) throw std::runtime_error(what); +} + +class OneShotFault final : public IRuntimeOwnerIo { + public: + RuntimeOwnerIoPoint target{RuntimeOwnerIoPoint::MkdirRoot}; + unsigned remaining{}; + bool FailAt(RuntimeOwnerIoPoint point) noexcept override { + if (remaining == 0 || point != target) return false; + if (--remaining == 0) return true; + return false; + } +}; + +RuntimeDomainId Domain() { RuntimeDomainId id{}; id[0] = 1; return id; } +EpochId Epoch() { EpochId id{}; id[0] = 9; return id; } + +std::string FreshPath(const char* suffix) { + const char* tmp = std::getenv("TMPDIR"); + const std::string root = tmp != nullptr && *tmp != '\0' ? tmp : "/tmp"; + return root + "/rateguard-runtime-owner-" + std::to_string(::getpid()) + "-" + suffix; +} + +std::unique_ptr Create(const std::string& path, + const RuntimeDomainId& domain = Domain(), + IRuntimeOwnerIo* io = nullptr) { + auto result = RuntimeOwner::CreateNew(path, domain, io); + if (auto* error = std::get_if(&result)) + std::cerr << "CreateNew error=" << static_cast(*error) << '\n'; + Check(std::holds_alternative>(result), "CreateNew failed"); + return std::get>(std::move(result)); +} + +void TestFreshClaimAndRecoveryOnlyOpen() { + const auto path = FreshPath("fresh"); + std::filesystem::remove_all(path); + auto owner = Create(path); + Check(owner->mode() == RuntimeOwnerMode::Fresh, "new root not Fresh"); + Check(std::holds_alternative(owner->ValidateOwnership()), + "fresh owner validation failed"); + struct stat st {}; + Check(::stat(path.c_str(), &st) == 0 && (st.st_mode & 07777) == 0700, + "root mode is not 0700"); + Check(::stat((path + "/owner.lock").c_str(), &st) == 0 && (st.st_mode & 07777) == 0600, + "lock mode is not 0600"); + Check(::stat((path + "/runtime-anchor.json").c_str(), &st) == 0 && + (st.st_mode & 07777) == 0600, "anchor mode is not 0600"); + + { + auto claim_result = owner->ClaimInitialEpoch(Epoch()); + Check(std::holds_alternative(claim_result), "fresh claim rejected"); + auto claim = std::get(std::move(claim_result)); + Check(claim.epoch_id() == Epoch() && claim.domain_id() == Domain() && + claim.root_path() == owner->root_path(), "claim binding mismatch"); + Check(std::holds_alternative(claim.ValidateOwnership()), + "claim validation failed"); + auto duplicate_fd = claim.DuplicateRootFd(); + Check(std::holds_alternative(duplicate_fd), "claim failed to duplicate root fd"); + ::close(std::get(duplicate_fd)); + Check(std::filesystem::create_directory(path + "/epoch-intents"), + "create bootstrap intent directory"); + auto second_claim = owner->ClaimInitialEpoch(Epoch()); + Check(std::get_if(&second_claim) != nullptr && + std::get(second_claim) == RuntimeOwnerError::InitialClaimAlreadyUsed, + "second initial claim succeeded"); + Check(std::holds_alternative(claim.ValidateOwnership()), + "second claim invalidated the live bootstrap token"); + auto locked_open = RuntimeOwner::OpenExisting(path, Domain()); + Check(std::get_if(&locked_open) != nullptr && + std::get(locked_open) == RuntimeOwnerError::LockBusy, + "second process owner lock was not rejected"); + owner.reset(); + // The move-only bootstrap claim retains the flock after RuntimeOwner dies. + locked_open = RuntimeOwner::OpenExisting(path, Domain()); + Check(std::get(locked_open) == RuntimeOwnerError::LockBusy, + "claim failed to retain ownership lock"); + } + auto new_owner_result = RuntimeOwner::OpenExisting(path, Domain()); + Check(std::holds_alternative>(new_owner_result), + "OpenExisting did not succeed after claim release"); + auto recovery_owner = std::get>(std::move(new_owner_result)); + Check(recovery_owner->mode() == RuntimeOwnerMode::RecoveryRequired, + "existing root was not RecoveryRequired"); + Check(std::holds_alternative(recovery_owner->ClaimInitialEpoch(Epoch())), + "recovery root issued initial claim"); + recovery_owner.reset(); + std::filesystem::remove_all(path); +} + +void TestDomainAndMissingAnchorFailClosed() { + const auto path = FreshPath("domain"); + std::filesystem::remove_all(path); + auto owner = Create(path); + owner.reset(); + auto wrong_domain = RuntimeOwner::OpenExisting(path, RuntimeDomainId{}); + Check(std::holds_alternative(wrong_domain), "zero domain accepted"); + auto other = Domain(); other[1] = 2; + wrong_domain = RuntimeOwner::OpenExisting(path, other); + Check(std::get_if(&wrong_domain) != nullptr && + std::get(wrong_domain) == RuntimeOwnerError::DomainMismatch, + "wrong domain accepted"); + std::filesystem::remove(path + "/runtime-anchor.json"); + auto missing = RuntimeOwner::OpenExisting(path, Domain()); + Check(std::get_if(&missing) != nullptr && + std::get(missing) == RuntimeOwnerError::AnchorMissing, + "missing anchor was recreated or accepted"); + std::filesystem::remove_all(path); +} + +void TestAnchorFifoIsRejectedWithoutBlocking() { + const auto path = FreshPath("anchor-fifo"); + std::filesystem::remove_all(path); + auto owner = Create(path); + owner.reset(); + Check(std::filesystem::remove(path + "/runtime-anchor.json"), "remove anchor for fifo test"); + Check(::mkfifo((path + "/runtime-anchor.json").c_str(), 0600) == 0, + "create anchor fifo"); + auto result = RuntimeOwner::OpenExisting(path, Domain()); + Check(std::get_if(&result) != nullptr && + std::get(result) == RuntimeOwnerError::InvalidAnchor, + "FIFO anchor was not rejected"); + std::filesystem::remove_all(path); +} + +void TestAnchorTamperLatchesFreshOwner() { + const auto path = FreshPath("tamper"); + std::filesystem::remove_all(path); + auto owner = Create(path); + const auto backup = path + "/anchor.save"; + std::filesystem::rename(path + "/runtime-anchor.json", backup); + { + FILE* fp = std::fopen((path + "/runtime-anchor.json").c_str(), "wb"); + Check(fp != nullptr, "create tamper anchor"); + const char data[] = "{}"; + Check(std::fwrite(data, 1, sizeof(data) - 1, fp) == sizeof(data) - 1, + "write tamper anchor"); + Check(std::fclose(fp) == 0, "close tamper anchor"); + Check(::chmod((path + "/runtime-anchor.json").c_str(), 0600) == 0, + "chmod tamper anchor"); + } + auto failed = owner->ValidateOwnership(); + Check(std::get_if(&failed) != nullptr, + "tampered anchor passed validation"); + std::filesystem::remove(path + "/runtime-anchor.json"); + std::filesystem::rename(backup, path + "/runtime-anchor.json"); + Check(owner->mode() == RuntimeOwnerMode::RecoveryRequired, + "owner regained Fresh mode after anchor restore"); + Check(std::holds_alternative(owner->ClaimInitialEpoch(Epoch())), + "latched owner issued initial claim"); + owner.reset(); + std::filesystem::remove_all(path); +} + +void TestUnexpectedRootEntryBlocksClaim() { + const auto path = FreshPath("extra-entry"); + std::filesystem::remove_all(path); + auto owner = Create(path); + { + FILE* fp = std::fopen((path + "/unexpected").c_str(), "wb"); + Check(fp != nullptr, "create extra file"); + Check(std::fclose(fp) == 0, "close extra file"); + } + auto claim = owner->ClaimInitialEpoch(Epoch()); + Check(std::get_if(&claim) != nullptr && + std::get(claim) == RuntimeOwnerError::UnexpectedRootEntry, + "unexpected root entry did not block claim"); + Check(owner->mode() == RuntimeOwnerMode::RecoveryRequired, + "unexpected entry did not latch owner"); + owner.reset(); + std::filesystem::remove_all(path); +} + +void TestFailureBoundaries() { + const auto parent_sync_path = FreshPath("parent-sync"); + std::filesystem::remove_all(parent_sync_path); + OneShotFault fault; + fault.target = RuntimeOwnerIoPoint::SyncParent; + fault.remaining = 1; + auto result = RuntimeOwner::CreateNew(parent_sync_path, Domain(), &fault); + Check(std::get_if(&result) != nullptr && + std::get(result) == RuntimeOwnerError::DurabilityUncertain, + "parent sync failure not uncertain"); + auto retry = RuntimeOwner::CreateNew(parent_sync_path, Domain()); + Check(std::get_if(&retry) != nullptr && + std::get(retry) == RuntimeOwnerError::AlreadyExists, + "partial root was reset after parent sync uncertainty"); + std::filesystem::remove_all(parent_sync_path); + + const auto anchor_sync_path = FreshPath("anchor-sync"); + std::filesystem::remove_all(anchor_sync_path); + fault.target = RuntimeOwnerIoPoint::SyncRoot; + fault.remaining = 2; // First is pre-anchor root sync; second is after anchor rename. + result = RuntimeOwner::CreateNew(anchor_sync_path, Domain(), &fault); + Check(std::get_if(&result) != nullptr && + std::get(result) == RuntimeOwnerError::DurabilityUncertain, + "post-anchor root sync failure not uncertain"); + auto recovery = RuntimeOwner::OpenExisting(anchor_sync_path, Domain()); + Check(std::holds_alternative>(recovery), + "visible anchor after uncertain sync unavailable for recovery"); + Check(std::get>(recovery)->mode() == + RuntimeOwnerMode::RecoveryRequired, + "uncertain created root not recovery-only"); + recovery = RuntimeOwnerError::IoFailure; + std::filesystem::remove_all(anchor_sync_path); +} + +void TestForkedHandleIsRejected() { + const auto path = FreshPath("fork"); + std::filesystem::remove_all(path); + auto owner = Create(path); + const pid_t child = ::fork(); + Check(child >= 0, "fork failed"); + if (child == 0) { + const auto result = owner->ValidateOwnership(); + _exit(std::get_if(&result) != nullptr && + std::get(result) == RuntimeOwnerError::OwnerProcessChanged + ? 0 : 1); + } + int status = 0; + Check(::waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0, + "fork-inherited owner was accepted"); + Check(owner->mode() == RuntimeOwnerMode::Fresh, + "child invalidation incorrectly changed parent owner"); + owner.reset(); + std::filesystem::remove_all(path); +} + +} // namespace + +int main() { + try { + TestFreshClaimAndRecoveryOnlyOpen(); + TestDomainAndMissingAnchorFailClosed(); + TestAnchorFifoIsRejectedWithoutBlocking(); + TestAnchorTamperLatchesFreshOwner(); + TestUnexpectedRootEntryBlocksClaim(); + TestFailureBoundaries(); + TestForkedHandleIsRejected(); + std::cout << "runtime owner tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "runtime owner test failure: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/supervisor/unix_http_fault_independent_test.cpp b/tests/supervisor/unix_http_fault_independent_test.cpp new file mode 100644 index 0000000..b3bfd56 --- /dev/null +++ b/tests/supervisor/unix_http_fault_independent_test.cpp @@ -0,0 +1,550 @@ +#if defined(__linux__) +#include "supervisor/unix_http_transport.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace std::chrono_literals; +using rateguard::platform::ClockIdentity; +using rateguard::platform::ClockResult; +using rateguard::platform::IClock; +using rateguard::platform::MonoNanos; +using namespace rateguard::supervisor; + +enum class SendFault { None, EpipeBeforeBytes, OneByteThenEpipe, Fragmented }; +enum class PollFaultStage { None, BeforeAnyByte, AfterAnyByte }; + +class FaultClock final : public IClock { + public: + static constexpr std::uint64_t kBase = 1'000'000'000ULL; + ClockResult Now() override { + return MonoNanos{kBase + elapsed_.load(std::memory_order_relaxed)}; + } + ClockResult Provenance() override { return ClockIdentity{}; } + bool Healthy() const override { return true; } + void Advance(std::uint64_t nanos) { + elapsed_.fetch_add(nanos, std::memory_order_relaxed); + } + private: + std::atomic_uint64_t elapsed_{0}; +}; + +struct FaultPlan { + FaultClock* clock{}; + SendFault send_fault{SendFault::None}; + bool connect_eagain{}; + PollFaultStage poll_stage{PollFaultStage::None}; + int poll_interrupts{}; + std::uint64_t advance_per_interrupt_ns{}; + bool sent_any{}; + int send_calls{}; + int connect_calls{}; + int recorded_poll_count{}; + std::array recorded_poll_ms{}; +}; + +thread_local FaultPlan* active_fault = nullptr; + +void RecordPoll(FaultPlan* plan, int timeout_ms) noexcept { + if (plan == nullptr || plan->recorded_poll_count >= + static_cast(plan->recorded_poll_ms.size())) + return; + plan->recorded_poll_ms[static_cast(plan->recorded_poll_count++)] = + timeout_ms; +} + +bool ShouldInjectPoll(FaultPlan* plan) noexcept { + if (plan == nullptr || plan->poll_interrupts <= 0) return false; + if (plan->poll_stage == PollFaultStage::BeforeAnyByte && plan->sent_any) + return false; + if (plan->poll_stage == PollFaultStage::AfterAnyByte && !plan->sent_any) + return false; + return plan->poll_stage != PollFaultStage::None; +} + +} // namespace + +extern "C" int __real_connect(int, const sockaddr*, socklen_t); +extern "C" ssize_t __real_send(int, const void*, size_t, int); +extern "C" int __real_poll(pollfd*, nfds_t, int); +extern "C" int __real___poll_chk(pollfd*, nfds_t, int, size_t); + +namespace { +int InjectedPoll(pollfd* descriptors, nfds_t count, int timeout_ms) { + auto* plan = active_fault; + if (plan != nullptr) { + const bool stage_matches = + (plan->poll_stage == PollFaultStage::BeforeAnyByte && !plan->sent_any) || + (plan->poll_stage == PollFaultStage::AfterAnyByte && plan->sent_any); + if (stage_matches) RecordPoll(plan, timeout_ms); + if (ShouldInjectPoll(plan)) { + --plan->poll_interrupts; + plan->clock->Advance(plan->advance_per_interrupt_ns); + errno = EINTR; + return -1; + } + } + return __real_poll(descriptors, count, timeout_ms); +} +} // namespace + +extern "C" int __wrap_connect(int fd, const sockaddr* address, + socklen_t address_length) { + auto* plan = active_fault; + if (plan != nullptr) { + ++plan->connect_calls; + if (plan->connect_eagain) { + errno = EAGAIN; + return -1; + } + } + const int result = __real_connect(fd, address, address_length); + if (result == 0 || errno != EINPROGRESS) return result; + // Complete a real local connection using the unwrapped poll so injected + // poll faults target the HTTP exchange waits, not setup timing. + pollfd descriptor{fd, POLLOUT, 0}; + const int ready = __real_poll(&descriptor, 1, 1'000); + if (ready <= 0) { + if (ready == 0) errno = ETIMEDOUT; + return -1; + } + int socket_error = 0; + socklen_t error_length = sizeof(socket_error); + if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &error_length) != 0) + return -1; + if (socket_error != 0) { + errno = socket_error; + return -1; + } + return 0; +} + +extern "C" ssize_t __wrap_send(int fd, const void* buffer, size_t length, + int flags) { + auto* plan = active_fault; + if (plan == nullptr) return __real_send(fd, buffer, length, flags); + const int call = plan->send_calls++; + if (plan->send_fault == SendFault::EpipeBeforeBytes) { + errno = EPIPE; + return -1; + } + if (plan->send_fault == SendFault::OneByteThenEpipe) { + if (call == 0) { + const auto count = __real_send(fd, buffer, std::min(length, 1), + flags); + if (count > 0) plan->sent_any = true; + return count; + } + errno = EPIPE; + return -1; + } + if (plan->send_fault == SendFault::Fragmented) { + if (call == 0) { + errno = EINTR; + return -1; + } + if (call == 1) { + errno = EAGAIN; + return -1; + } + const auto count = __real_send(fd, buffer, + std::min(length, 7), flags); + if (count > 0) plan->sent_any = true; + return count; + } + const auto count = __real_send(fd, buffer, length, flags); + if (count > 0) plan->sent_any = true; + return count; +} + +extern "C" int __wrap_poll(pollfd* descriptors, nfds_t count, int timeout_ms) { + return InjectedPoll(descriptors, count, timeout_ms); +} + +// Ubuntu's fortified headers may lower poll() to __poll_chk(). Link the test +// executable with --wrap=__poll_chk as well as --wrap=poll so sanitizer builds +// exercise the same deterministic deadline fault path. +extern "C" int __wrap___poll_chk(pollfd* descriptors, nfds_t count, + int timeout_ms, size_t descriptors_bytes) { + if (descriptors_bytes != static_cast(-1) && + count > descriptors_bytes / sizeof(*descriptors)) { + return __real___poll_chk(descriptors, count, timeout_ms, descriptors_bytes); + } + return InjectedPoll(descriptors, count, timeout_ms); +} + +namespace { +int failures = 0; +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::cerr << __FILE__ << ':' << __LINE__ << ": CHECK failed: " #expr \ + << '\n'; \ + ++failures; \ + } \ + } while (false) + +struct TempDir { + std::string path; + TempDir() { + std::string pattern = "/tmp/rateguard-http-fault-XXXXXX"; + std::vector bytes(pattern.begin(), pattern.end()); + bytes.push_back('\0'); + if (char* result = ::mkdtemp(bytes.data()); result != nullptr) path = result; + } + ~TempDir() { + if (!path.empty()) std::filesystem::remove_all(path); + } +}; + +class BoundedPeer { + public: + enum class Behavior { Reply, Hold }; + BoundedPeer(std::string path, Behavior behavior, + std::string response = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") + : path_(std::move(path)), behavior_(behavior), response_(std::move(response)) { + listener_ = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (listener_ < 0) return; + sockaddr_un address{}; + address.sun_family = AF_UNIX; + if (path_.size() >= sizeof(address.sun_path)) return; + std::memcpy(address.sun_path, path_.c_str(), path_.size() + 1); + const auto length = static_cast( + offsetof(sockaddr_un, sun_path) + path_.size() + 1); + if (::bind(listener_, reinterpret_cast(&address), length) != 0 || + ::listen(listener_, 4) != 0) { + (void)::close(listener_); + listener_ = -1; + return; + } + worker_ = std::thread([this] { Serve(); }); + } + ~BoundedPeer() { + { + std::lock_guard lock(mutex_); + stop_ = true; + release_ = true; + } + condition_.notify_all(); + if (worker_.joinable()) worker_.join(); + if (listener_ >= 0) (void)::close(listener_); + (void)::unlink(path_.c_str()); + } + BoundedPeer(const BoundedPeer&) = delete; + BoundedPeer& operator=(const BoundedPeer&) = delete; + [[nodiscard]] bool valid() const { return listener_ >= 0; } + [[nodiscard]] int accepted() const { return accepted_.load(); } + [[nodiscard]] bool WaitAccepted(std::chrono::milliseconds timeout = 2s) { + std::unique_lock lock(mutex_); + return condition_.wait_for(lock, timeout, + [&] { return accepted_.load() > 0 || finished_; }) && + accepted_.load() > 0; + } + [[nodiscard]] std::string received() const { + std::lock_guard lock(mutex_); + return received_; + } + [[nodiscard]] bool WaitReceivedSize(std::size_t size, + std::chrono::milliseconds timeout = 2s) { + std::unique_lock lock(mutex_); + return condition_.wait_for(lock, timeout, + [&] { return received_.size() >= size || finished_; }) && + received_.size() >= size; + } + [[nodiscard]] bool WaitFinished(std::chrono::milliseconds timeout = 5s) { + std::unique_lock lock(mutex_); + return condition_.wait_for(lock, timeout, [&] { return finished_; }); + } + void Release() { + { + std::lock_guard lock(mutex_); + release_ = true; + } + condition_.notify_all(); + } + + private: + void Serve() { + const auto accept_until = std::chrono::steady_clock::now() + 4s; + int connection = -1; + while (std::chrono::steady_clock::now() < accept_until) { + { + std::lock_guard lock(mutex_); + if (stop_) break; + } + pollfd descriptor{listener_, POLLIN, 0}; + const int ready = __real_poll(&descriptor, 1, 50); + if (ready < 0 && errno == EINTR) continue; + if (ready < 0) break; + if (ready == 0) continue; + connection = ::accept4(listener_, nullptr, nullptr, + SOCK_CLOEXEC | SOCK_NONBLOCK); + if (connection >= 0) break; + if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) break; + } + if (connection < 0) { + std::lock_guard lock(mutex_); + finished_ = true; + condition_.notify_all(); + return; + } + accepted_.store(1); + condition_.notify_all(); + + std::string request; + char buffer[256]; + const auto read_until = std::chrono::steady_clock::now() + 2s; + while (request.find("\r\n\r\n") == std::string::npos && + request.size() <= kUnixHttpMaxRequestBytes && + std::chrono::steady_clock::now() < read_until) { + pollfd descriptor{connection, POLLIN, 0}; + const int ready = __real_poll(&descriptor, 1, 50); + if (ready < 0 && errno == EINTR) continue; + if (ready <= 0) continue; + const auto amount = ::recv(connection, buffer, sizeof(buffer), 0); + if (amount < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) + continue; + if (amount <= 0) break; + request.append(buffer, static_cast(amount)); + { + std::lock_guard lock(mutex_); + received_ = request; + } + condition_.notify_all(); + } + { + std::lock_guard lock(mutex_); + received_ = request; + condition_.notify_all(); + } + if (behavior_ == Behavior::Hold) { + std::unique_lock lock(mutex_); + (void)condition_.wait_for(lock, 3s, [&] { return release_ || stop_; }); + } else { + std::size_t sent = 0; + while (sent < response_.size()) { + const auto amount = __real_send(connection, response_.data() + sent, + response_.size() - sent, MSG_NOSIGNAL); + if (amount <= 0) break; + sent += static_cast(amount); + } + } + (void)::shutdown(connection, SHUT_RDWR); + (void)::close(connection); + { + std::lock_guard lock(mutex_); + finished_ = true; + } + condition_.notify_all(); + } + + std::string path_; + Behavior behavior_; + std::string response_; + int listener_{-1}; + std::thread worker_; + std::atomic_int accepted_{0}; + mutable std::mutex mutex_; + std::condition_variable condition_; + bool stop_{false}; + bool release_{false}; + bool finished_{false}; + std::string received_; +}; + +struct Fixture { + TempDir directory; + FaultClock clock; + std::string socket_path; + UnixHttpTransportCreateResult created = + UnixHttpFailure{UnixHttpFailureReason::NotConfigured, false}; + std::unique_ptr transport; + Fixture() { + socket_path = directory.path + "/daemon.sock"; + } + bool Create() { + auto result = CreateUnixHttpTransport( + UnixHttpTransportConfig{socket_path, + static_cast(::getuid()), + static_cast(::getuid())}, + clock); + if (!std::holds_alternative>(result)) + return false; + transport = std::move(std::get>(result)); + return true; + } +}; + +void TestEpipeBeforeAndAfterFirstBytePreservesUncertainty() { + for (const auto& [fault, expected_sent, expected_bytes] : { + std::tuple{SendFault::EpipeBeforeBytes, false, std::size_t{0}}, + std::tuple{SendFault::OneByteThenEpipe, true, std::size_t{1}}}) { + Fixture fixture; + BoundedPeer peer(fixture.socket_path, BoundedPeer::Behavior::Hold); + CHECK(peer.valid()); + if (!peer.valid() || !fixture.Create()) continue; + FaultPlan plan; + plan.send_fault = fault; + active_fault = &plan; + std::atomic_bool cancelled{false}; + const auto result = fixture.transport->RoundTrip( + UnixHttpMethod::Get, "/v1.57/version", + {FaultClock::kBase + 2'000'000'000ULL}, cancelled); + active_fault = nullptr; + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::SocketFailure); + CHECK(failure.request_possibly_sent == expected_sent); + } + CHECK(peer.WaitAccepted()); + peer.Release(); + CHECK(peer.WaitFinished()); + const auto request = peer.received(); + CHECK(request.size() == expected_bytes); + if (expected_bytes == 1) CHECK(request == "G"); + CHECK(plan.connect_calls == 1); + active_fault = nullptr; + } +} + +void TestConnectEagainFailsWithoutRetryOrDispatch() { + Fixture fixture; + BoundedPeer peer(fixture.socket_path, BoundedPeer::Behavior::Hold); + CHECK(peer.valid()); + if (!peer.valid() || !fixture.Create()) return; + FaultPlan plan; + plan.connect_eagain = true; + active_fault = &plan; + std::atomic_bool cancelled{false}; + const auto result = fixture.transport->RoundTrip( + UnixHttpMethod::Get, "/v1.57/version", + {FaultClock::kBase + 2'000'000'000ULL}, cancelled); + active_fault = nullptr; + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::SocketFailure); + CHECK(!failure.request_possibly_sent); + } + CHECK(plan.connect_calls == 1); + CHECK(peer.accepted() == 0); +} + +void TestFragmentedSendAndFiniteEintrEagainStillSendExactRequest() { + Fixture fixture; + BoundedPeer peer(fixture.socket_path, BoundedPeer::Behavior::Reply); + CHECK(peer.valid()); + if (!peer.valid() || !fixture.Create()) return; + FaultPlan plan; + plan.send_fault = SendFault::Fragmented; + active_fault = &plan; + std::atomic_bool cancelled{false}; + const auto result = fixture.transport->RoundTrip( + UnixHttpMethod::Post, "/v1.57/containers/" + std::string(64, 'a') + + "/stop?signal=SIGTERM&t=1", + {FaultClock::kBase + 3'000'000'000ULL}, cancelled); + active_fault = nullptr; + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) + CHECK(std::get(result).status == 200); + CHECK(peer.WaitAccepted()); + const auto expected = + "POST /v1.57/containers/" + std::string(64, 'a') + + "/stop?signal=SIGTERM&t=1 HTTP/1.1\r\nHost: docker\r\n" + "Connection: close\r\nContent-Length: 0\r\n\r\n"; + CHECK(peer.received() == expected); + CHECK(plan.send_calls > 3); + CHECK(plan.connect_calls == 1); +} + +void TestPollEintrConsumesOriginalDeadlineBeforeAndAfterSend() { + for (const auto& stage : {PollFaultStage::BeforeAnyByte, + PollFaultStage::AfterAnyByte}) { + Fixture fixture; + BoundedPeer peer(fixture.socket_path, BoundedPeer::Behavior::Hold); + CHECK(peer.valid()); + if (!peer.valid() || !fixture.Create()) continue; + FaultPlan plan; + plan.clock = &fixture.clock; + plan.poll_stage = stage; + plan.poll_interrupts = 3; + plan.advance_per_interrupt_ns = 30'000'000ULL; + active_fault = &plan; + std::atomic_bool cancelled{false}; + const auto result = fixture.transport->RoundTrip( + UnixHttpMethod::Get, "/v1.57/version", + {FaultClock::kBase + 80'000'000ULL}, cancelled); + active_fault = nullptr; + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::DeadlineExpired); + CHECK(failure.request_possibly_sent == + (stage == PollFaultStage::AfterAnyByte)); + } + CHECK(plan.recorded_poll_count >= 3); + if (plan.recorded_poll_count >= 3) { + CHECK(plan.recorded_poll_ms[0] == 80); + CHECK(plan.recorded_poll_ms[1] == 50); + CHECK(plan.recorded_poll_ms[2] == 20); + } + if (stage == PollFaultStage::AfterAnyByte) { + CHECK(peer.WaitAccepted()); + CHECK(peer.WaitReceivedSize(16)); + peer.Release(); + CHECK(peer.WaitFinished()); + CHECK(peer.received().starts_with("GET /v1.57/version HTTP/1.1\r\n")); + } else { + CHECK(peer.accepted() <= 1); + peer.Release(); + CHECK(peer.WaitFinished()); + CHECK(peer.received().empty()); + } + } +} + +} // namespace + +int main() { + TestEpipeBeforeAndAfterFirstBytePreservesUncertainty(); + TestConnectEagainFailsWithoutRetryOrDispatch(); + TestFragmentedSendAndFiniteEintrEagainStillSendExactRequest(); + TestPollEintrConsumesOriginalDeadlineBeforeAndAfterSend(); + if (failures != 0) { + std::cerr << failures << " deterministic HTTP fault assertion(s) failed\n"; + return 1; + } + std::cout << "Deterministic Unix HTTP fault checks passed\n"; + return 0; +} +#else +int main() { return 77; } +#endif diff --git a/tests/supervisor/unix_http_transport_independent_test.cpp b/tests/supervisor/unix_http_transport_independent_test.cpp new file mode 100644 index 0000000..8d12e3e --- /dev/null +++ b/tests/supervisor/unix_http_transport_independent_test.cpp @@ -0,0 +1,677 @@ +#if defined(__linux__) +#include "supervisor/unix_http_transport.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +int failures = 0; + +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::cerr << __FILE__ << ':' << __LINE__ << ": CHECK failed: " #expr \ + << '\n'; \ + ++failures; \ + } \ + } while (false) + +using namespace std::chrono_literals; +using rateguard::platform::ClockFailure; +using rateguard::platform::ClockFailureReason; +using rateguard::platform::ClockIdentity; +using rateguard::platform::ClockResult; +using rateguard::platform::IClock; +using rateguard::platform::MonoNanos; +using namespace rateguard::supervisor; + +class TestClock final : public IClock { + public: + ClockResult Now() override { + timespec ts{}; + if (::clock_gettime(CLOCK_MONOTONIC, &ts) != 0 || ts.tv_sec < 0 || + ts.tv_nsec < 0 || ts.tv_nsec >= 1'000'000'000L) { + return Failure(); + } + const auto sec = static_cast(ts.tv_sec); + const auto nsec = static_cast(ts.tv_nsec); + if (sec > (UINT64_MAX - nsec) / 1'000'000'000ULL) return Failure(); + return MonoNanos{sec * 1'000'000'000ULL + nsec}; + } + ClockResult Provenance() override { return Failure(); } + bool Healthy() const override { return true; } + + private: + static ClockFailure Failure() { + using namespace rateguard::v1::contract; + return {{ErrorCategory::Internal, ErrorCode::Internal, + RetryDisposition::Never, Commitment::NotCommitted}, + ClockFailureReason::ClockSyscall}; + } +}; + +class ThrowingClock final : public IClock { + public: + explicit ThrowingClock(int throw_on_now, int throw_on_healthy) + : throw_on_now_(throw_on_now), throw_on_healthy_(throw_on_healthy) {} + ClockResult Now() override { + ++now_calls_; + if (now_calls_ == throw_on_now_) throw std::runtime_error("clock test fault"); + timespec ts{}; + if (::clock_gettime(CLOCK_MONOTONIC, &ts) != 0 || ts.tv_sec < 0 || + ts.tv_nsec < 0 || ts.tv_nsec >= 1'000'000'000L) { + return TestClockFailure(); + } + const auto sec = static_cast(ts.tv_sec); + const auto nsec = static_cast(ts.tv_nsec); + if (sec > (UINT64_MAX - nsec) / 1'000'000'000ULL) return TestClockFailure(); + return MonoNanos{sec * 1'000'000'000ULL + nsec}; + } + ClockResult Provenance() override { return TestClockFailure(); } + bool Healthy() const override { + ++healthy_calls_; + if (healthy_calls_ == throw_on_healthy_) + throw std::runtime_error("health test fault"); + return true; + } + + private: + static ClockFailure TestClockFailure() { + using namespace rateguard::v1::contract; + return {{ErrorCategory::Internal, ErrorCode::Internal, + RetryDisposition::Never, Commitment::NotCommitted}, + ClockFailureReason::ClockSyscall}; + } + int throw_on_now_; + int throw_on_healthy_; + int now_calls_{0}; + mutable int healthy_calls_{0}; +}; + +struct TempDir { + std::string path; + TempDir() { + std::string pattern = "/tmp/rateguard-http-independent-XXXXXX"; + std::vector bytes(pattern.begin(), pattern.end()); + bytes.push_back('\0'); + if (char* result = ::mkdtemp(bytes.data()); result != nullptr) path = result; + } + ~TempDir() { + if (!path.empty()) std::filesystem::remove_all(path); + } +}; + +class UnixPeer { + public: + UnixPeer(const std::string& path, std::string response, + std::chrono::milliseconds delay = 0ms, + std::atomic_bool* cancel_after_request = nullptr) + : path_(path), response_(std::move(response)), delay_(delay), + cancel_after_request_(cancel_after_request) { + listener_ = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (listener_ < 0) return; + sockaddr_un address{}; + address.sun_family = AF_UNIX; + if (path_.size() >= sizeof(address.sun_path)) return; + std::memcpy(address.sun_path, path_.c_str(), path_.size() + 1); + const auto length = static_cast( + offsetof(sockaddr_un, sun_path) + path_.size() + 1); + if (::bind(listener_, reinterpret_cast(&address), length) != 0 || + ::listen(listener_, 4) != 0) { + ::close(listener_); + listener_ = -1; + return; + } + worker_ = std::thread([this] { Serve(); }); + } + ~UnixPeer() { + stop_.store(true, std::memory_order_relaxed); + if (worker_.joinable()) worker_.join(); + if (listener_ >= 0) { + (void)::close(listener_); + listener_ = -1; + } + (void)::unlink(path_.c_str()); + } + UnixPeer(const UnixPeer&) = delete; + UnixPeer& operator=(const UnixPeer&) = delete; + [[nodiscard]] bool valid() const { return listener_ >= 0; } + [[nodiscard]] int accepted() const { return accepted_.load(); } + [[nodiscard]] std::string request() const { + std::lock_guard lock(mutex_); + return request_; + } + [[nodiscard]] bool WaitAccepted(std::chrono::milliseconds timeout = 2s) { + std::unique_lock lock(mutex_); + return condition_.wait_for(lock, timeout, [&] { return accepted_.load() > 0; }); + } + + private: + void Serve() { + const auto accept_deadline = std::chrono::steady_clock::now() + 3s; + int connection = -1; + while (!stop_.load(std::memory_order_relaxed) && + std::chrono::steady_clock::now() < accept_deadline) { + pollfd descriptor{listener_, POLLIN, 0}; + const int ready = ::poll(&descriptor, 1, 50); + if (ready < 0 && errno == EINTR) continue; + if (ready < 0) return; + if (ready == 0) continue; + connection = ::accept4(listener_, nullptr, nullptr, + SOCK_CLOEXEC | SOCK_NONBLOCK); + if (connection >= 0) break; + if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) return; + } + if (connection < 0) return; + accepted_.store(1); + condition_.notify_all(); + std::string request; + char buffer[512]; + const auto read_deadline = std::chrono::steady_clock::now() + 3s; + while (request.find("\r\n\r\n") == std::string::npos && + request.size() < kUnixHttpMaxRequestBytes + 1 && + !stop_.load(std::memory_order_relaxed) && + std::chrono::steady_clock::now() < read_deadline) { + pollfd descriptor{connection, POLLIN, 0}; + const int ready = ::poll(&descriptor, 1, 50); + if (ready < 0 && errno == EINTR) continue; + if (ready < 0 || ready == 0) continue; + const auto count = ::recv(connection, buffer, sizeof(buffer), 0); + if (count < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) + continue; + if (count <= 0) break; + request.append(buffer, static_cast(count)); + } + { + std::lock_guard lock(mutex_); + request_ = std::move(request); + } + condition_.notify_all(); + if (cancel_after_request_ != nullptr) + cancel_after_request_->store(true, std::memory_order_relaxed); + if (delay_ > 0ms && delay_ <= 3s) std::this_thread::sleep_for(delay_); + std::size_t sent = 0; + while (sent < response_.size()) { + const auto count = ::send(connection, response_.data() + sent, + response_.size() - sent, MSG_NOSIGNAL); + if (count <= 0) break; + sent += static_cast(count); + } + (void)::shutdown(connection, SHUT_RDWR); + (void)::close(connection); + } + + std::string path_; + std::string response_; + std::chrono::milliseconds delay_; + std::atomic_bool* cancel_after_request_; + int listener_{-1}; + std::thread worker_; + std::atomic_int accepted_{0}; + std::atomic_bool stop_{false}; + mutable std::mutex mutex_; + std::condition_variable condition_; + std::string request_; +}; + +class FourCallPeer { + public: + explicit FourCallPeer(const std::string& path) : path_(path) { + listener_ = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (listener_ < 0) return; + sockaddr_un address{}; + address.sun_family = AF_UNIX; + std::memcpy(address.sun_path, path_.c_str(), path_.size() + 1); + const auto length = static_cast( + offsetof(sockaddr_un, sun_path) + path_.size() + 1); + if (::bind(listener_, reinterpret_cast(&address), length) != 0 || + ::listen(listener_, 8) != 0) { + (void)::close(listener_); + listener_ = -1; + return; + } + worker_ = std::thread([this] { Serve(); }); + } + ~FourCallPeer() { + { + std::lock_guard lock(mutex_); + stop_ = true; + release_ = true; + } + condition_.notify_all(); + if (worker_.joinable()) worker_.join(); + if (listener_ >= 0) (void)::close(listener_); + (void)::unlink(path_.c_str()); + } + FourCallPeer(const FourCallPeer&) = delete; + FourCallPeer& operator=(const FourCallPeer&) = delete; + [[nodiscard]] bool valid() const { return listener_ >= 0; } + [[nodiscard]] bool WaitReady(std::chrono::milliseconds timeout = 3s) { + std::unique_lock lock(mutex_); + return condition_.wait_for(lock, timeout, [&] { return ready_ || finished_; }) && ready_; + } + [[nodiscard]] int accepted() const { + std::lock_guard lock(mutex_); + return accepted_; + } + void Release() { + { + std::lock_guard lock(mutex_); + release_ = true; + } + condition_.notify_all(); + } + + private: + bool ReadRequest(int fd) { + std::string request; + char buffer[512]; + const auto until = std::chrono::steady_clock::now() + 2s; + while (request.find("\r\n\r\n") == std::string::npos && + request.size() < kUnixHttpMaxRequestBytes + 1 && + std::chrono::steady_clock::now() < until) { + pollfd descriptor{fd, POLLIN, 0}; + const int ready = ::poll(&descriptor, 1, 50); + if (ready < 0 && errno == EINTR) continue; + if (ready <= 0) continue; + const auto count = ::recv(fd, buffer, sizeof(buffer), 0); + if (count < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) + continue; + if (count <= 0) break; + request.append(buffer, static_cast(count)); + } + return request.find("\r\n\r\n") != std::string::npos; + } + + void Serve() { + const auto accept_until = std::chrono::steady_clock::now() + 3s; + std::vector connections; + while (connections.size() < kUnixHttpMaxConcurrentCalls && + std::chrono::steady_clock::now() < accept_until) { + { + std::lock_guard lock(mutex_); + if (stop_) break; + } + pollfd descriptor{listener_, POLLIN, 0}; + const int ready = ::poll(&descriptor, 1, 50); + if (ready < 0 && errno == EINTR) continue; + if (ready < 0) break; + if (ready == 0) continue; + const int fd = ::accept4(listener_, nullptr, nullptr, + SOCK_CLOEXEC | SOCK_NONBLOCK); + if (fd < 0) { + if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) continue; + break; + } + connections.push_back(fd); + if (!ReadRequest(fd)) break; + { + std::lock_guard lock(mutex_); + accepted_ = static_cast(connections.size()); + } + condition_.notify_all(); + } + { + std::lock_guard lock(mutex_); + ready_ = connections.size() == kUnixHttpMaxConcurrentCalls; + finished_ = true; + } + condition_.notify_all(); + { + std::unique_lock lock(mutex_); + (void)condition_.wait_for(lock, 3s, [&] { return release_ || stop_; }); + } + constexpr std::string_view response = + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; + for (const int fd : connections) { + std::size_t sent = 0; + while (sent < response.size()) { + const auto count = ::send(fd, response.data() + sent, + response.size() - sent, MSG_NOSIGNAL); + if (count <= 0) break; + sent += static_cast(count); + } + (void)::shutdown(fd, SHUT_RDWR); + (void)::close(fd); + } + } + + std::string path_; + int listener_{-1}; + std::thread worker_; + mutable std::mutex mutex_; + std::condition_variable condition_; + int accepted_{0}; + bool ready_{false}; + bool finished_{false}; + bool release_{false}; + bool stop_{false}; +}; + +MonoNanos Now(TestClock& clock) { + const auto result = clock.Now(); + return std::get(result); +} + +MonoNanos RealMonotonicNow() { + timespec ts{}; + if (::clock_gettime(CLOCK_MONOTONIC, &ts) != 0 || ts.tv_sec < 0 || + ts.tv_nsec < 0 || ts.tv_nsec >= 1'000'000'000L) { + return MonoNanos{0}; + } + return MonoNanos{static_cast(ts.tv_sec) * 1'000'000'000ULL + + static_cast(ts.tv_nsec)}; +} + +template +UnixHttpTransportCreateResult CreateTransport(const std::string& path, + ClockT& clock, + std::uint32_t peer_uid) { + return CreateUnixHttpTransport( + UnixHttpTransportConfig{path, peer_uid, + static_cast(::getuid())}, + clock); +} + +void TestSingleExchangeExactPostAndNoRedirectFollowing() { + TempDir dir; + CHECK(!dir.path.empty()); + if (dir.path.empty()) return; + const auto path = dir.path + "/daemon.sock"; + UnixPeer peer(path, "HTTP/1.1 302 Found\r\nContent-Length: 0\r\n\r\n"); + CHECK(peer.valid()); + if (!peer.valid()) return; + TestClock clock; + auto created = CreateTransport(path, clock, static_cast(::getuid())); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + std::atomic_bool cancelled{false}; + const auto deadline = Now(clock).value + 2'000'000'000ULL; + const auto result = transport.RoundTrip( + UnixHttpMethod::Post, + "/v1.57/containers/" + std::string(64, 'a') + + "/stop?signal=SIGTERM&t=1", + {deadline}, cancelled); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) + CHECK(std::get(result).status == 302); + CHECK(peer.WaitAccepted()); + CHECK(peer.accepted() == 1); + CHECK(peer.request() == + "POST /v1.57/containers/" + std::string(64, 'a') + + "/stop?signal=SIGTERM&t=1 HTTP/1.1\r\nHost: docker\r\n" + "Connection: close\r\nContent-Length: 0\r\n\r\n"); +} + +void TestPreDispatchCancellationAndPeerMismatch() { + TempDir dir; + const auto path = dir.path + "/daemon.sock"; + UnixPeer peer(path, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + CHECK(peer.valid()); + if (!peer.valid()) return; + TestClock clock; + auto created = CreateTransport(path, clock, static_cast(::getuid())); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + std::atomic_bool cancelled{true}; + auto result = transport.RoundTrip(UnixHttpMethod::Get, "/v1.57/version", + {Now(clock).value + 2'000'000'000ULL}, cancelled); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::Cancelled); + CHECK(!failure.request_possibly_sent); + } + CHECK(peer.accepted() == 0); + + cancelled.store(false, std::memory_order_relaxed); + const auto wrong_uid = static_cast(::getuid() == 0 ? 1 : 0); + auto wrong_peer = CreateTransport(path, clock, wrong_uid); + CHECK(std::holds_alternative>(wrong_peer)); + if (!std::holds_alternative>(wrong_peer)) return; + auto& wrong_transport = *std::get>(wrong_peer); + result = wrong_transport.RoundTrip( + UnixHttpMethod::Get, "/v1.57/version", + {Now(clock).value + 2'000'000'000ULL}, cancelled); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::PeerCredentialMismatch); + CHECK(!failure.request_possibly_sent); + } + CHECK(peer.WaitAccepted()); + CHECK(peer.accepted() == 1); +} + +void TestSocketPathReplacementFailsBeforeConnect() { + TempDir dir; + const auto path = dir.path + "/daemon.sock"; + const auto bind_listener = [&path]() { + const int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (fd < 0) return -1; + sockaddr_un address{}; + address.sun_family = AF_UNIX; + std::memcpy(address.sun_path, path.c_str(), path.size() + 1); + const auto length = static_cast( + offsetof(sockaddr_un, sun_path) + path.size() + 1); + if (::bind(fd, reinterpret_cast(&address), length) != 0 || + ::listen(fd, 1) != 0) { + (void)::close(fd); + return -1; + } + return fd; + }; + const int old_listener = bind_listener(); + CHECK(old_listener >= 0); + if (old_listener < 0) return; + TestClock clock; + auto created = CreateTransport(path, clock, static_cast(::getuid())); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) { + (void)::close(old_listener); + (void)::unlink(path.c_str()); + return; + } + auto& transport = *std::get>(created); + + // Remove the original listening socket and bind a replacement at the same + // path. The transport must compare its pinned device/inode before connect. + CHECK(::unlink(path.c_str()) == 0); + const int replacement_listener = bind_listener(); + CHECK(replacement_listener >= 0); + // Keep the old socket inode alive until the replacement is bound so the + // filesystem cannot immediately recycle its inode number. + (void)::close(old_listener); + if (replacement_listener < 0) return; + std::atomic_bool cancelled{false}; + const auto result = transport.RoundTrip( + UnixHttpMethod::Get, "/v1.57/version", + {Now(clock).value + 2'000'000'000ULL}, cancelled); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::NotConfigured); + CHECK(!failure.request_possibly_sent); + } + (void)::close(replacement_listener); + (void)::unlink(path.c_str()); +} + +void TestDeadlineAfterRequestIsUncertain() { + TempDir dir; + const auto path = dir.path + "/daemon.sock"; + UnixPeer peer(path, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", 250ms); + CHECK(peer.valid()); + if (!peer.valid()) return; + TestClock clock; + auto created = CreateTransport(path, clock, static_cast(::getuid())); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + std::atomic_bool cancelled{false}; + const auto result = transport.RoundTrip( + UnixHttpMethod::Get, "/v1.57/version", + {Now(clock).value + 50'000'000ULL}, cancelled); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::DeadlineExpired); + CHECK(failure.request_possibly_sent); + } + CHECK(peer.WaitAccepted()); + CHECK(peer.accepted() == 1); +} + +void TestCancellationAfterFullRequestIsUncertain() { + TempDir dir; + const auto path = dir.path + "/daemon.sock"; + std::atomic_bool cancelled{false}; + UnixPeer peer(path, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", 250ms, + &cancelled); + CHECK(peer.valid()); + if (!peer.valid()) return; + TestClock clock; + auto created = CreateTransport(path, clock, static_cast(::getuid())); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + const auto result = transport.RoundTrip( + UnixHttpMethod::Post, "/v1.57/containers/id/stop?signal=SIGTERM&t=1", + {Now(clock).value + 2'000'000'000ULL}, cancelled); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::Cancelled); + CHECK(failure.request_possibly_sent); + } + CHECK(peer.WaitAccepted()); + CHECK(peer.accepted() == 1); + CHECK(peer.request().starts_with( + "POST /v1.57/containers/id/stop?signal=SIGTERM&t=1 HTTP/1.1\r\n")); +} + +void TestConcurrentLimitRejectsFifthCallWithoutQueueing() { + TempDir dir; + const auto path = dir.path + "/daemon.sock"; + FourCallPeer peer(path); + CHECK(peer.valid()); + if (!peer.valid()) return; + TestClock clock; + auto created = CreateTransport(path, clock, static_cast(::getuid())); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + std::atomic_bool cancelled{false}; + std::array, kUnixHttpMaxConcurrentCalls> results; + std::vector clients; + clients.reserve(kUnixHttpMaxConcurrentCalls); + for (std::size_t index = 0; index < kUnixHttpMaxConcurrentCalls; ++index) { + clients.emplace_back([&, index] { + const auto deadline = Now(clock).value + 5'000'000'000ULL; + results[index] = transport.RoundTrip(UnixHttpMethod::Get, + "/v1.57/version", {deadline}, cancelled); + }); + } + const bool four_ready = peer.WaitReady(); + CHECK(four_ready); + CHECK(peer.accepted() == static_cast(kUnixHttpMaxConcurrentCalls)); + const auto fifth_deadline = Now(clock).value + 2'000'000'000ULL; + const auto fifth = transport.RoundTrip(UnixHttpMethod::Get, "/v1.57/version", + {fifth_deadline}, cancelled); + CHECK(std::holds_alternative(fifth)); + if (std::holds_alternative(fifth)) { + const auto failure = std::get(fifth); + CHECK(failure.reason == UnixHttpFailureReason::Overloaded); + CHECK(!failure.request_possibly_sent); + } + CHECK(peer.accepted() == static_cast(kUnixHttpMaxConcurrentCalls)); + peer.Release(); + for (auto& client : clients) + if (client.joinable()) client.join(); + for (const auto& result : results) { + CHECK(result.has_value()); + if (result.has_value()) { + CHECK(std::holds_alternative(*result)); + if (std::holds_alternative(*result)) + CHECK(std::get(*result).status == 200); + } + } +} + +void TestThrowingClockCannotEscapeNoexceptRoundTrip() { + for (const auto& [throw_on_now, throw_on_healthy] : + {std::pair{2, 0}, std::pair{0, 4}}) { + TempDir dir; + const auto path = dir.path + "/daemon.sock"; + UnixPeer peer(path, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + CHECK(peer.valid()); + if (!peer.valid()) continue; + ThrowingClock clock(throw_on_now, throw_on_healthy); + auto created = CreateTransport(path, clock, + static_cast(::getuid())); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) + continue; + auto& transport = *std::get>(created); + std::atomic_bool cancelled{false}; + // Keep the deadline comfortably in the future without sampling the + // deliberately throwing clock. + const auto result = transport.RoundTrip(UnixHttpMethod::Get, "/version", + {RealMonotonicNow().value + + 2'000'000'000ULL}, cancelled); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::ClockFailure); + CHECK(!failure.request_possibly_sent); + } + CHECK(peer.accepted() == 0); + } +} + +} // namespace + +int main() { + TestSingleExchangeExactPostAndNoRedirectFollowing(); + TestPreDispatchCancellationAndPeerMismatch(); + TestSocketPathReplacementFailsBeforeConnect(); + TestDeadlineAfterRequestIsUncertain(); + TestCancellationAfterFullRequestIsUncertain(); + TestConcurrentLimitRejectsFifthCallWithoutQueueing(); + TestThrowingClockCannotEscapeNoexceptRoundTrip(); + if (failures != 0) { + std::cerr << failures << " independent Linux transport assertion(s) failed\n"; + return 1; + } + std::cout << "Independent Linux Unix HTTP checks passed\n"; + return 0; +} +#else +int main() { return 77; } +#endif diff --git a/tests/supervisor/unix_http_transport_linux_test.cpp b/tests/supervisor/unix_http_transport_linux_test.cpp new file mode 100644 index 0000000..52b8d96 --- /dev/null +++ b/tests/supervisor/unix_http_transport_linux_test.cpp @@ -0,0 +1,363 @@ +#if defined(__linux__) +#include "supervisor/unix_http_transport.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +int failures = 0; +#define CHECK(expr) do { if (!(expr)) { std::cerr << __FILE__ << ':' << __LINE__ << ": CHECK failed: " #expr "\n"; ++failures; } } while (false) + +class LinuxTestClock final : public rateguard::platform::IClock { + public: + rateguard::platform::ClockResult Now() override { + timespec ts{}; + if (::clock_gettime(CLOCK_MONOTONIC, &ts) != 0) + return Error(rateguard::platform::ClockFailureReason::ClockSyscall); + if (ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= 1'000'000'000L) + return Error(rateguard::platform::ClockFailureReason::InvalidTimespec); + return rateguard::platform::MonoNanos{ + static_cast(ts.tv_sec) * 1'000'000'000ULL + + static_cast(ts.tv_nsec)}; + } + rateguard::platform::ClockResult Provenance() override { + return Error(rateguard::platform::ClockFailureReason::LatchedFailure); + } + bool Healthy() const override { return true; } + private: + static rateguard::platform::ClockFailure Error( + rateguard::platform::ClockFailureReason reason) { + using namespace rateguard::v1::contract; + return {{ErrorCategory::Internal, ErrorCode::Internal, RetryDisposition::Never, + Commitment::NotCommitted}, reason}; + } +}; + +class ThrowingTestClock final : public rateguard::platform::IClock { + public: + rateguard::platform::ClockResult Now() override { + throw std::runtime_error("injected clock exception"); + } + rateguard::platform::ClockResult Provenance() override { + throw std::runtime_error("injected clock exception"); + } + bool Healthy() const override { throw std::runtime_error("injected clock exception"); } +}; + +struct TempDir { + std::string path; + TempDir() { + std::string pattern = "/tmp/rateguard-unix-http-XXXXXX"; + std::vector data(pattern.begin(), pattern.end()); + data.push_back('\0'); + char* created = ::mkdtemp(data.data()); + if (created != nullptr) path = created; + } + ~TempDir() { if (!path.empty()) std::filesystem::remove_all(path); } +}; + +class LocalPeer { + public: + enum class Mode { Reply, Delay, CancelAfterRequest, Hold }; + LocalPeer(const std::string& path, Mode mode, + std::string reply = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok", + std::atomic_bool* cancel = nullptr) + : path_(path), mode_(mode), reply_(std::move(reply)), cancel_(cancel) { + listener_ = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (listener_ < 0) return; + sockaddr_un addr{}; + addr.sun_family = AF_UNIX; + std::memcpy(addr.sun_path, path_.c_str(), path_.size() + 1); + const auto len = static_cast(offsetof(sockaddr_un, sun_path) + path_.size() + 1); + if (::bind(listener_, reinterpret_cast(&addr), len) != 0 || + ::listen(listener_, 8) != 0) { + ::close(listener_); + listener_ = -1; + return; + } + running_ = std::thread([this] { Serve(); }); + } + ~LocalPeer() { + stop_.store(true, std::memory_order_relaxed); + Release(); + if (running_.joinable()) running_.join(); + if (listener_ >= 0) ::close(listener_); + } + bool valid() const { return listener_ >= 0; } + int accepted() const { return accepted_.load(); } + std::string request() const { + std::lock_guard lock(mutex_); + return request_; + } + void Release() { + { + std::lock_guard lock(mutex_); + released_ = true; + } + cv_.notify_all(); + } + bool WaitAccepted(int count, std::chrono::milliseconds timeout = std::chrono::seconds(3)) { + std::unique_lock lock(mutex_); + return cv_.wait_for(lock, timeout, [&] { return accepted_.load() >= count; }); + } + private: + void Serve() { + for (;;) { + pollfd listener_poll{listener_, POLLIN, 0}; + const int ready = ::poll(&listener_poll, 1, 100); + if (stop_.load(std::memory_order_relaxed)) break; + if (ready == 0 || (ready < 0 && errno == EINTR)) continue; + if (ready < 0) break; + const int fd = ::accept4(listener_, nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK); + if (fd < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue; + break; + } + ++accepted_; + { + std::lock_guard lock(mutex_); + cv_.notify_all(); + } + std::string request; + char buffer[1024]; + const auto read_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3); + while (request.find("\r\n\r\n") == std::string::npos && request.size() < 8192 && + !stop_.load(std::memory_order_relaxed) && + std::chrono::steady_clock::now() < read_deadline) { + pollfd read_poll{fd, POLLIN, 0}; + const int readable = ::poll(&read_poll, 1, 100); + if (readable < 0 && errno == EINTR) continue; + if (readable < 0) break; + if (readable == 0) continue; + const auto n = ::recv(fd, buffer, sizeof(buffer), 0); + if (n < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) continue; + if (n <= 0) break; + request.append(buffer, static_cast(n)); + } + { + std::lock_guard lock(mutex_); + request_ = request; + cv_.notify_all(); + } + if (mode_ == Mode::CancelAfterRequest && cancel_ != nullptr) + cancel_->store(true, std::memory_order_relaxed); + if (mode_ == Mode::Delay) std::this_thread::sleep_for(std::chrono::milliseconds(300)); + if (mode_ == Mode::Hold) { + std::unique_lock lock(mutex_); + (void)cv_.wait_for(lock, std::chrono::seconds(3), [&] { return released_; }); + } + if (mode_ == Mode::Reply) { + (void)::send(fd, reply_.data(), reply_.size(), MSG_NOSIGNAL); + } + (void)::shutdown(fd, SHUT_RDWR); + ::close(fd); + if (mode_ != Mode::Hold) break; + } + } + + std::string path_; + Mode mode_; + std::string reply_; + std::atomic_bool* cancel_; + int listener_{-1}; + std::thread running_; + std::atomic_bool stop_{false}; + std::atomic_int accepted_{0}; + mutable std::mutex mutex_; + std::condition_variable cv_; + std::string request_; + bool released_{false}; +}; + +rateguard::platform::MonoNanos Now(LinuxTestClock& clock) { + return std::get(clock.Now()); +} + +rateguard::supervisor::UnixHttpTransportCreateResult MakeTransport( + const std::string& path, LinuxTestClock& clock, uid_t uid = ::getuid()) { + rateguard::supervisor::UnixHttpTransportConfig config; + config.socket_path = path; + config.expected_peer_uid = static_cast(uid); + config.expected_socket_owner_uid = static_cast(::getuid()); + return rateguard::supervisor::CreateUnixHttpTransport(config, clock); +} + +void TestSuccessfulRoundTripNoRetryAndExactRequest() { + using namespace rateguard::supervisor; + TempDir dir; + CHECK(!dir.path.empty()); + if (dir.path.empty()) return; + const auto path = dir.path + "/docker.sock"; + LocalPeer peer(path, LocalPeer::Mode::Reply); + CHECK(peer.valid()); + if (!peer.valid()) return; + LinuxTestClock clock; + auto created = MakeTransport(path, clock); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + std::atomic_bool cancel{false}; + const auto deadline = Now(clock); + const auto result = transport.RoundTrip(UnixHttpMethod::Get, "/v1.45/version", + {deadline.value + 2'000'000'000ULL}, cancel); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& response = std::get(result); + CHECK(response.status == 200); + CHECK(std::string(response.body.begin(), response.body.end()) == "ok"); + } + CHECK(peer.accepted() == 1); + CHECK(peer.request() == "GET /v1.45/version HTTP/1.1\r\nHost: docker\r\n" + "Connection: close\r\nContent-Length: 0\r\n\r\n"); +} + +void TestFailureBeforeAndAfterDispatch() { + using namespace rateguard::supervisor; + TempDir dir; + const auto path = dir.path + "/docker.sock"; + LocalPeer peer(path, LocalPeer::Mode::Delay); + CHECK(peer.valid()); + if (!peer.valid()) return; + LinuxTestClock clock; + auto created = MakeTransport(path, clock); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + std::atomic_bool cancel{false}; + + auto result = transport.RoundTrip(UnixHttpMethod::Get, "/version", {1}, cancel); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::InvalidDeadline); + CHECK(!failure.request_possibly_sent); + } + CHECK(peer.accepted() == 0); + + const auto now = Now(clock); + result = transport.RoundTrip(UnixHttpMethod::Post, "/v1.45/containers/x/stop?t=1&signal=SIGTERM", + {now.value + 100'000'000ULL}, cancel); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::DeadlineExpired); + CHECK(failure.request_possibly_sent); + } + CHECK(peer.accepted() == 1); +} + +void TestCancellationAfterDispatch() { + using namespace rateguard::supervisor; + TempDir dir; + const auto path = dir.path + "/docker.sock"; + std::atomic_bool cancel{false}; + LocalPeer peer(path, LocalPeer::Mode::CancelAfterRequest, {}, &cancel); + CHECK(peer.valid()); + if (!peer.valid()) return; + LinuxTestClock clock; + auto created = MakeTransport(path, clock); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + const auto now = Now(clock); + const auto result = transport.RoundTrip(UnixHttpMethod::Get, "/version", + {now.value + 2'000'000'000ULL}, cancel); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::Cancelled); + CHECK(failure.request_possibly_sent); + } +} + +void TestThrowingClockMapsToFailureWithoutDispatch() { + using namespace rateguard::supervisor; + TempDir dir; + const auto path = dir.path + "/docker.sock"; + LocalPeer peer(path, LocalPeer::Mode::Reply); + CHECK(peer.valid()); + if (!peer.valid()) return; + ThrowingTestClock clock; + UnixHttpTransportConfig config; + config.socket_path = path; + config.expected_peer_uid = static_cast(::getuid()); + config.expected_socket_owner_uid = static_cast(::getuid()); + auto created = CreateUnixHttpTransport(config, clock); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + std::atomic_bool cancel{false}; + const auto result = transport.RoundTrip(UnixHttpMethod::Get, "/version", {100}, cancel); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::ClockFailure); + CHECK(!failure.request_possibly_sent); + } + CHECK(peer.accepted() == 0); +} + +void TestPeerUidMismatchBeforeDispatch() { + using namespace rateguard::supervisor; + TempDir dir; + const auto path = dir.path + "/docker.sock"; + LocalPeer peer(path, LocalPeer::Mode::Reply); + CHECK(peer.valid()); + if (!peer.valid()) return; + LinuxTestClock clock; + const auto wrong_uid = static_cast(::getuid() == 0 ? 1 : 0); + auto created = MakeTransport(path, clock, wrong_uid); + CHECK(std::holds_alternative>(created)); + if (!std::holds_alternative>(created)) return; + auto& transport = *std::get>(created); + std::atomic_bool cancel{false}; + const auto now = Now(clock); + const auto result = transport.RoundTrip(UnixHttpMethod::Get, "/version", + {now.value + 2'000'000'000ULL}, cancel); + CHECK(std::holds_alternative(result)); + if (std::holds_alternative(result)) { + const auto& failure = std::get(result); + CHECK(failure.reason == UnixHttpFailureReason::PeerCredentialMismatch); + CHECK(!failure.request_possibly_sent); + } +} + +} // namespace + +int main() { + TestSuccessfulRoundTripNoRetryAndExactRequest(); + TestFailureBeforeAndAfterDispatch(); + TestCancellationAfterDispatch(); + TestThrowingClockMapsToFailureWithoutDispatch(); + TestPeerUidMismatchBeforeDispatch(); + if (failures != 0) { + std::cerr << failures << " Linux transport assertion(s) failed\n"; + return 1; + } + std::cout << "Linux Unix HTTP transport tests passed\n"; + return 0; +} +#else +int main() { return 77; } +#endif diff --git a/tools/capture_build_manifest.py b/tools/capture_build_manifest.py new file mode 100644 index 0000000..64f497a --- /dev/null +++ b/tools/capture_build_manifest.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Capture observed build inputs without asserting the candidate lock is validated.""" +from __future__ import annotations + +import argparse +import datetime as dt +import json +import os +import platform +import shutil +import shlex +import subprocess +import sys +from pathlib import Path +from typing import Any + + +def command_output(args: list[str], cwd: Path | None = None) -> str | None: + if not args or shutil.which(args[0]) is None: + return None + try: + proc = subprocess.run(args, cwd=cwd, text=True, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, check=False, timeout=15) + except (OSError, subprocess.TimeoutExpired): + return None + value = proc.stdout.strip() + return value if proc.returncode == 0 and value else None + + +def git_head(path: Path | None) -> str | None: + if path is None or not path.exists(): + return None + return command_output(["git", "-C", str(path), "rev-parse", "HEAD"]) + + +def read_os_release() -> dict[str, str]: + values: dict[str, str] = {} + path = Path("/etc/os-release") + if not path.exists(): + return values + for line in path.read_text(encoding="utf-8").splitlines(): + if "=" in line and not line.startswith("#"): + key, value = line.split("=", 1) + values[key] = value.strip().strip('"') + return values + + +def load_lock(path: Path) -> dict[str, Any]: + if not path.exists(): + return {"lock_status": "missing"} + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + return {"lock_status": "invalid", "error": str(exc)} + + + +def build_configuration(source: Path, build: Path) -> dict[str, Any]: + """Observe the compiler standard used by every project C++ translation unit.""" + flags_seen: set[str] = set() + count = 0 + all_cpp20 = True + try: + entries = json.loads((build / "compile_commands.json").read_text(encoding="utf-8")) + if not isinstance(entries, list): + raise ValueError("compile_commands root is not a list") + for entry in entries: + path = Path(entry["file"]) + if not path.is_absolute(): + path = Path(entry["directory"]) / path + path = path.resolve() + try: + relative = path.relative_to(source) + except ValueError: + continue + if "_deps" in relative.parts or path.suffix not in (".cpp", ".cc", ".cxx", ".C"): + continue + args = entry.get("arguments") + if args is None: + args = shlex.split(entry["command"]) + flags = [arg for arg in args if arg.startswith("-std=")] + flags_seen.update(flags) + all_cpp20 = all_cpp20 and flags == ["-std=c++20"] + count += 1 + except (OSError, ValueError, KeyError, TypeError) as exc: + return {"cxx_standard": None, "project_compile_commands_count": 0, + "error": str(exc)} + return {"cxx_standard": "C++20" if count and all_cpp20 else None, + "project_compile_commands_count": count, + "project_cxx_standard_flags": sorted(flags_seen)} + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--source-root", required=True, type=Path) + parser.add_argument("--build-dir", required=True, type=Path) + parser.add_argument("--grpc-source", type=Path, default=None) + parser.add_argument("--protoc", type=Path, default=None) + parser.add_argument("--grpc-plugin", type=Path, default=None) + parser.add_argument("--codegen-tools", type=Path, default=None) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--build-result", choices=("not-yet-run", "passed", "failed"), + default="not-yet-run") + args = parser.parse_args() + source = args.source_root.resolve() + build = args.build_dir.resolve() + grpc_source = args.grpc_source.resolve() if args.grpc_source else None + cmake_cache = build / "CMakeCache.txt" + cache = cmake_cache.read_text(encoding="utf-8", errors="replace") if cmake_cache.exists() else "" + compiler_path = None + for line in cache.splitlines(): + if line.startswith("CMAKE_CXX_COMPILER:FILEPATH="): + compiler_path = line.split("=", 1)[1] + break + compiler = [compiler_path or os.environ.get("CXX") or "c++", "--version"] + lock = load_lock(source / "build-lock.json") + codegen_tools: dict[str, str] = {} + if args.codegen_tools and args.codegen_tools.exists(): + try: + codegen_tools = json.loads(args.codegen_tools.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + codegen_tools = {} + protoc_path = args.protoc or (Path(codegen_tools["protoc"]) if codegen_tools.get("protoc") else None) + plugin_path = args.grpc_plugin or (Path(codegen_tools["grpc_cpp_plugin"]) if codegen_tools.get("grpc_cpp_plugin") else None) + third_party = (grpc_source / "third_party") if grpc_source else None + dependency_commits = { + "grpc": git_head(grpc_source), + "protobuf_submodule": git_head(third_party / "protobuf" if third_party else None), + "abseil_submodule": git_head(third_party / "abseil-cpp" if third_party else None), + "re2_submodule": git_head(third_party / "re2" if third_party else None), + "cares_submodule": git_head(third_party / "cares" / "cares" if third_party else None), + } + manifest = { + "manifest_schema_version": 1, + "captured_at_utc": dt.datetime.now(dt.timezone.utc).isoformat(), + "claim_status": "observed_environment_only", + "build_result": args.build_result, + "lock_status": lock.get("lock_status", "missing"), + "source": { + "git_commit": git_head(source), + "github_sha": os.environ.get("GITHUB_SHA"), + "github_ref": os.environ.get("GITHUB_REF"), + "github_head_ref": os.environ.get("GITHUB_HEAD_REF"), + "workflow": os.environ.get("GITHUB_WORKFLOW"), + "run_id": os.environ.get("GITHUB_RUN_ID"), + }, + "runner": { + "label_requested": "ubuntu-24.04", + "run_os": os.environ.get("RUNNER_OS"), + "run_arch": os.environ.get("RUNNER_ARCH"), + "image_os": os.environ.get("ImageOS"), + "image_version": os.environ.get("ImageVersion"), + "kernel": platform.release(), + "machine": platform.machine(), + "os_release": read_os_release(), + "image_digest": None, + "image_digest_note": "GitHub-hosted runner image digest is not asserted; use ImageOS/ImageVersion and observed package versions.", + }, + "tools": { + "python": sys.version.splitlines()[0], + "cmake": command_output(["cmake", "--version"]), + "ninja": command_output(["ninja", "--version"]), + "cxx_compiler": command_output(compiler), + "protoc_path": str(protoc_path) if protoc_path else None, + "protoc": command_output([str(protoc_path), "--version"]) if protoc_path else command_output(["protoc", "--version"]), + "grpc_cpp_plugin_path": str(plugin_path) if plugin_path else None, + "grpc_cpp_plugin": command_output([str(plugin_path), "--version"]) if plugin_path else shutil.which("grpc_cpp_plugin"), + "git": command_output(["git", "--version"]), + }, + "system_packages": { + "libssl_dev": command_output(["dpkg-query", "-W", "-f=${Version}", "libssl-dev"]), + "zlib1g_dev": command_output(["dpkg-query", "-W", "-f=${Version}", "zlib1g-dev"]), + "nlohmann_json_dev": command_output(["dpkg-query", "-W", "-f=${Version}", "nlohmann-json3-dev"]), + "libgrpc_dev": command_output(["dpkg-query", "-W", "-f=${Version}", "libgrpc-dev"]), + "libgrpcpp_dev": command_output(["dpkg-query", "-W", "-f=${Version}", "libgrpc++-dev"]), + "libprotobuf_dev": command_output(["dpkg-query", "-W", "-f=${Version}", "libprotobuf-dev"]), + "protobuf_compiler": command_output(["dpkg-query", "-W", "-f=${Version}", "protobuf-compiler"]), + "protobuf_compiler_grpc": command_output(["dpkg-query", "-W", "-f=${Version}", "protobuf-compiler-grpc"]), + }, + "dependency_mode": "system_packages" if not grpc_source else "grpc_source", + "dependency_commits": dependency_commits, + "candidate_lock": lock, + "build_configuration": build_configuration(source, build), + "limitations": [ + "This manifest records one observed run; it does not by itself prove bit-for-bit reproducibility.", + "Do not promote lock_status until CI succeeds and requested refs are compared with captured immutable commits.", + "A missing commit/tool/package value is recorded as null, not inferred.", + ], + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(f"Wrote observed build manifest: {args.output}") + print(f"Build result: {args.build_result}; lock status: {manifest['lock_status']}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/history/history_reader.h b/tools/history/history_reader.h new file mode 100644 index 0000000..e4ca074 --- /dev/null +++ b/tools/history/history_reader.h @@ -0,0 +1,107 @@ +#pragma once + +#include "src/events/history_validator.h" + +#include +#include +#include +#include + +namespace rateguard::events::history { + +enum class ReadError { BadPlan, BadHeader, BadEncoding, IncompleteEvidence, ReadFailure }; +using ReadResult = std::variant; + +namespace input { +template +bool Number(std::istream& in, T& value) { + std::array bytes{}; + if (!in.read(reinterpret_cast(bytes.data()), bytes.size())) return false; + value = 0; + for (const auto byte : bytes) + value = static_cast((static_cast(value) << 8) | byte); + return true; +} + +template +bool Enum(std::istream& in, E& value) { + std::uint8_t octet; + if (!Number(in, octet)) return false; + value = static_cast(octet); + return true; +} + +inline bool Flag(std::istream& in, bool& value) { + std::uint8_t octet; + if (!Number(in, octet) || octet > 1) return false; + value = octet != 0; + return true; +} + +template +bool Bytes(std::istream& in, std::array& field) { + return static_cast(in.read(reinterpret_cast(field.data()), N)); +} +} // namespace input + +// Offline reader for a complete binary file. The caller supplies a trusted run +// plan. File-supplied sizes never control allocations. +inline ReadResult ReadStrictHistory(std::istream& in, const RunPlan& plan) noexcept { + try { + if (plan.budget_bytes < 97 || plan.budget_bytes > kMaxRunBudgetBytes || + plan.producers.size() > (plan.budget_bytes - 97) / 90) return ReadError::BadPlan; + auto roster = plan.producers; + std::sort(roster.begin(), roster.end(), [](const auto& a, const auto& b) { + return a.owner < b.owner || (a.owner == b.owner && a.producer_index < b.producer_index); + }); + std::uint64_t extent; + if (!validation::detail::ValidExpectedPlan(roster, plan.budget_bytes, extent)) + return ReadError::BadPlan; + + EventSnapshotV1 s; + std::array magic{}; + std::uint32_t count; + if (!in.read(magic.data(), magic.size()) || std::string_view(magic.data(), 8) != "RGHIST01" || + !input::Number(in, s.schema_version) || s.schema_version != 1 || + !input::Bytes(in, s.epoch_id) || s.epoch_id != plan.epoch_id || + !input::Bytes(in, s.policy_digest) || s.policy_digest != plan.policy_digest || + !input::Number(in, count) || count != roster.size() || + !input::Number(in, s.planned_bytes) || s.planned_bytes != extent || + !input::Number(in, s.budget_bytes) || s.budget_bytes != plan.budget_bytes) + return ReadError::BadHeader; + + s.producers.reserve(roster.size()); + for (const auto& expected : roster) { + auto& p = s.producers.emplace_back(); + if (!input::Enum(in, p.owner) || p.owner != expected.owner || + !input::Number(in, p.producer_index) || p.producer_index != expected.producer_index || + !input::Number(in, p.capacity) || p.capacity != expected.event_capacity) + return ReadError::BadEncoding; + p.slots.resize(expected.event_capacity); + for (auto& slot : p.slots) { + auto& e = slot.event; + if (!input::Enum(in, slot.status) || !input::Number(in, slot.producer_sequence) || + !input::Enum(in, e.stage) || !input::Enum(in, e.outcome) || + !input::Bytes(in, e.attempt_id) || !input::Number(in, e.timestamp_ns) || + !input::Number(in, e.cost_units) || !input::Number(in, slot.checksum64)) + return ReadError::BadEncoding; + } + if (!input::Flag(in, p.sealed) || !input::Flag(in, p.incomplete) || + !input::Number(in, p.reserved_count) || !input::Number(in, p.published_count) || + !input::Number(in, p.seal_checksum64)) return ReadError::BadEncoding; + } + std::uint64_t terminal_extent; + if (!input::Flag(in, s.complete) || !input::Number(in, terminal_extent) || + terminal_extent != extent || !input::Number(in, s.checksum64)) + return ReadError::BadEncoding; + if (in.peek() != std::istream::traits_type::eof() || in.bad() || !in.eof()) + return ReadError::BadEncoding; + if (!validation::ValidateHistorySnapshot(s, plan).complete()) + return ReadError::IncompleteEvidence; + return s; + } catch (...) { + return ReadError::ReadFailure; + } +} + +} // namespace rateguard::events::history diff --git a/tools/history/inspect_main.cpp b/tools/history/inspect_main.cpp new file mode 100644 index 0000000..a5e13dd --- /dev/null +++ b/tools/history/inspect_main.cpp @@ -0,0 +1,343 @@ +// Offline structural inspector for RGHIST01 binary history files. +// +// CLI-specific trusted plan JSON (all keys required, no other keys): +// { +// "schema_version": 1, +// "epoch_id": "<32 lowercase hex chars>", +// "policy_digest": "<64 lowercase hex chars>", +// "budget_bytes": "", +// "producers": [ +// {"producer_owner": 1, "producer_index": 0, "event_capacity": "1"} +// ] +// } +// `producer_owner` is numeric 1..5; `producer_index` is uint32 JSON integer. All u64 +// values are canonical decimal strings to avoid JSON float rounding. The CLI +// accepts at most 1 MiB of plan JSON; the producer count is additionally +// bounded by the plan's fixed-width history budget. This is an offline tool +// input limit, not a product/runtime limit. A structurally complete history +// is not a quota-safety verdict: output always reports UNKNOWN for safety. + +#include "tools/history/history_reader.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using Json = nlohmann::json; +using namespace rateguard::events; + +constexpr std::size_t kMaxPlanJsonBytes = 1U * 1024U * 1024U; +constexpr std::size_t kMaxJsonDepth = 8; +constexpr std::uint64_t kMaxRunBytes = kMaxRunBudgetBytes; + +struct CliFailure final { + std::string code; + int exit_code; +}; + +[[noreturn]] void Fail(std::string_view code, int exit_code = 2) { + throw CliFailure{std::string(code), exit_code}; +} + +Json ErrorJson(std::string_view code) { + return Json{{"result_schema_version", 1}, {"status", "error"}, + {"error", code}, {"safety_verdict", "UNKNOWN"}}; +} + +void EmitError(std::string_view code) noexcept { + try { + std::cout << ErrorJson(code).dump() << '\n'; + } catch (...) { + // The normal path uses only a fixed, small JSON object. This fallback + // avoids writing exception detail or input data to diagnostics. + std::cout << "{\"result_schema_version\":1,\"status\":\"error\"," + "\"error\":\"output_failure\",\"safety_verdict\":\"UNKNOWN\"}\n"; + } +} + +class DuplicateKeyAndFloatGuard final : public nlohmann::json_sax { + public: + using string_t = Json::string_t; + using binary_t = Json::binary_t; + using number_integer_t = Json::number_integer_t; + using number_unsigned_t = Json::number_unsigned_t; + using number_float_t = Json::number_float_t; + + bool null() override { return true; } + bool boolean(bool) override { return true; } + bool number_integer(number_integer_t) override { return true; } + bool number_unsigned(number_unsigned_t) override { return true; } + bool number_float(number_float_t, const string_t&) override { + return Reject("json_float"); + } + bool string(string_t&) override { return true; } + bool binary(binary_t&) override { return Reject("json_binary"); } + bool start_object(std::size_t) override { + if (frames_.size() >= kMaxJsonDepth) return Reject("json_depth_limit"); + frames_.push_back(Frame{true, {}}); + return true; + } + bool key(string_t& value) override { + if (frames_.empty() || !frames_.back().is_object) return Reject("json_invalid_key"); + if (!frames_.back().keys.insert(value).second) return Reject("json_duplicate_key"); + return true; + } + bool end_object() override { + if (frames_.empty() || !frames_.back().is_object) return Reject("json_invalid_object"); + frames_.pop_back(); + return true; + } + bool start_array(std::size_t) override { + if (frames_.size() >= kMaxJsonDepth) return Reject("json_depth_limit"); + frames_.push_back(Frame{false, {}}); + return true; + } + bool end_array() override { + if (frames_.empty() || frames_.back().is_object) return Reject("json_invalid_array"); + frames_.pop_back(); + return true; + } + bool parse_error(std::size_t, const std::string&, + const nlohmann::detail::exception&) override { + if (error_.empty()) error_ = "json_syntax"; + return false; + } + [[nodiscard]] std::string_view error() const noexcept { return error_; } + + private: + struct Frame final { + bool is_object; + std::set> keys; + }; + bool Reject(std::string_view code) { + if (error_.empty()) error_ = code; + return false; + } + std::vector frames_; + std::string_view error_; +}; + +std::string ReadBoundedPlanFile(const std::filesystem::path& path) { + std::error_code ec; + const auto status = std::filesystem::status(path, ec); + if (ec || !std::filesystem::is_regular_file(status)) Fail("plan_file_unavailable"); + const auto bytes = std::filesystem::file_size(path, ec); + if (ec) Fail("plan_file_unavailable"); + if (bytes > kMaxPlanJsonBytes) Fail("plan_too_large"); + + std::ifstream input(path, std::ios::binary); + if (!input) Fail("plan_file_unavailable"); + std::string text(static_cast(bytes), '\0'); + if (bytes != 0) { + input.read(text.data(), static_cast(bytes)); + if (input.gcount() != static_cast(bytes)) Fail("plan_read_failure"); + } + char extra{}; + if (input.get(extra)) Fail("plan_changed_during_read"); + if (input.bad()) Fail("plan_read_failure"); + return text; +} + +void CheckKeys(const Json& object, std::initializer_list required) { + if (!object.is_object()) Fail("plan_schema_invalid"); + for (const auto& item : object.items()) { + if (std::find(required.begin(), required.end(), std::string_view(item.key())) == required.end()) + Fail("plan_unknown_key"); + } + for (const auto key : required) { + if (!object.contains(std::string(key))) Fail("plan_missing_key"); + } +} + +std::uint32_t JsonU32(const Json& value) { + if (value.is_number_unsigned()) { + const auto number = value.get(); + if (number <= std::numeric_limits::max()) + return static_cast(number); + } else if (value.is_number_integer()) { + const auto number = value.get(); + if (number >= 0 && static_cast(number) <= + std::numeric_limits::max()) + return static_cast(number); + } + Fail("plan_integer_invalid"); +} + +std::uint64_t DecimalU64(const Json& value, bool positive) { + if (!value.is_string()) Fail("plan_u64_must_be_decimal_string"); + const auto text = value.get(); + if (text.empty() || (text.size() > 1 && text.front() == '0')) + Fail("plan_decimal_noncanonical"); + for (const unsigned char c : text) { + if (c < '0' || c > '9') Fail("plan_decimal_noncanonical"); + } + std::uint64_t parsed_value = 0; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), parsed_value, 10); + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) + Fail("plan_u64_out_of_range"); + if (positive && parsed_value == 0) Fail("plan_value_must_be_positive"); + return parsed_value; +} + +template +std::array LowerHex(const Json& value) { + if (!value.is_string()) Fail("plan_hex_must_be_string"); + const auto hex = value.get(); + if (hex.size() != N * 2) Fail("plan_hex_width_invalid"); + auto nibble = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return -1; + }; + std::array result{}; + for (std::size_t i = 0; i < N; ++i) { + const auto high = nibble(hex[2 * i]); + const auto low = nibble(hex[2 * i + 1]); + if (high < 0 || low < 0) Fail("plan_hex_not_lowercase"); + result[i] = static_cast((high << 4) | low); + } + return result; +} + +std::uint64_t PlanExtent(const std::vector& producers) { + constexpr std::uint64_t kHeader = 80; + constexpr std::uint64_t kTerminal = 17; + constexpr std::uint64_t kProducerEnvelope = 13; + constexpr std::uint64_t kSlot = 51; + constexpr std::uint64_t kProducerSeal = 26; + std::uint64_t total = kHeader + kTerminal; + for (const auto& producer : producers) { + const auto maximum = std::numeric_limits::max(); + if (total > maximum - kProducerEnvelope - kProducerSeal) + Fail("plan_extent_overflow"); + const auto remaining = maximum - total - kProducerEnvelope - kProducerSeal; + if (producer.event_capacity > remaining / kSlot) Fail("plan_extent_overflow"); + total += kProducerEnvelope + producer.event_capacity * kSlot + kProducerSeal; + } + return total; +} + +RunPlan ParsePlan(std::string_view source) { + DuplicateKeyAndFloatGuard guard; + if (!Json::sax_parse(source.begin(), source.end(), &guard)) + Fail(guard.error().empty() ? std::string_view("plan_json_invalid") : guard.error()); + const auto json = Json::parse(source); + CheckKeys(json, {"schema_version", "epoch_id", "policy_digest", "budget_bytes", "producers"}); + if (JsonU32(json.at("schema_version")) != 1) Fail("plan_schema_version_unsupported"); + + RunPlan plan; + plan.epoch_id = LowerHex<16>(json.at("epoch_id")); + plan.policy_digest = LowerHex<32>(json.at("policy_digest")); + plan.budget_bytes = DecimalU64(json.at("budget_bytes"), true); + if (plan.budget_bytes > kMaxRunBytes) Fail("plan_budget_exceeds_cap"); + + const auto& producers = json.at("producers"); + if (!producers.is_array() || producers.empty()) Fail("plan_producers_invalid"); + if (plan.budget_bytes < 97 || producers.size() > (plan.budget_bytes - 97) / 90) + Fail("plan_producer_count_exceeds_budget"); + + std::set> seen; + plan.producers.reserve(producers.size()); + for (const auto& item : producers) { + CheckKeys(item, {"producer_owner", "producer_index", "event_capacity"}); + const auto owner_value = JsonU32(item.at("producer_owner")); + if (owner_value < 1 || owner_value > 5) Fail("plan_owner_invalid"); + const auto index = JsonU32(item.at("producer_index")); + const auto capacity = DecimalU64(item.at("event_capacity"), true); + if (capacity > static_cast(std::numeric_limits::max())) + Fail("plan_capacity_out_of_range"); + const auto owner = static_cast(owner_value); + if (!seen.emplace(owner, index).second) Fail("plan_duplicate_producer"); + plan.producers.push_back(ProducerSpec{static_cast(owner), index, capacity}); + } + + const auto expected_bytes = PlanExtent(plan.producers); + if (expected_bytes >= kMaxRunBytes) Fail("plan_extent_exceeds_cap"); + if (expected_bytes > plan.budget_bytes) Fail("plan_budget_below_extent"); + return plan; +} + +std::uint64_t FileSize(const std::filesystem::path& path, std::string_view error) { + std::error_code ec; + if (!std::filesystem::is_regular_file(std::filesystem::status(path, ec)) || ec) + Fail(error); + const auto bytes = std::filesystem::file_size(path, ec); + if (ec) Fail(error); + return bytes; +} + +std::string_view ReadErrorName(history::ReadError error) noexcept { + switch (error) { + case history::ReadError::BadPlan: return "history_bad_plan"; + case history::ReadError::BadHeader: return "history_bad_header"; + case history::ReadError::BadEncoding: return "history_bad_encoding"; + case history::ReadError::IncompleteEvidence: return "history_incomplete"; + case history::ReadError::ReadFailure: return "history_read_failure"; + } + return "history_read_failure"; +} + +int Run(const std::filesystem::path& plan_path, + const std::filesystem::path& history_path) { + const auto plan_text = ReadBoundedPlanFile(plan_path); + const auto plan = ParsePlan(plan_text); + const auto expected_bytes = PlanExtent(plan.producers); + const auto history_bytes = FileSize(history_path, "history_file_unavailable"); + if (history_bytes != expected_bytes) Fail("history_size_mismatch"); + + std::ifstream history_input(history_path, std::ios::binary); + if (!history_input) Fail("history_file_unavailable"); + auto parsed = history::ReadStrictHistory(history_input, plan); + if (const auto* error = std::get_if(&parsed)) + Fail(ReadErrorName(*error)); + const auto& snapshot = std::get(parsed); + const auto report = validation::ValidateHistorySnapshot(snapshot, plan); + if (!report.complete()) Fail("history_incomplete"); + + const Json result{ + {"result_schema_version", 1}, + {"history_schema_version", snapshot.schema_version}, + {"status", "structurally_complete"}, + {"safety_verdict", "UNKNOWN"}, + {"event_count", std::to_string(report.published_events)}, + {"history_bytes", std::to_string(report.snapshot_bytes)}, + {"budget_bytes", std::to_string(snapshot.budget_bytes)}, + }; + std::cout << result.dump() << '\n'; + return std::cout ? 0 : 2; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 3) { + EmitError("usage"); + return 64; + } + try { + return Run(argv[1], argv[2]); + } catch (const CliFailure& failure) { + EmitError(failure.code); + return failure.exit_code; + } catch (...) { + EmitError("internal_error"); + return 2; + } +} diff --git a/tools/history/retention.py b/tools/history/retention.py new file mode 100644 index 0000000..0d6c58f --- /dev/null +++ b/tools/history/retention.py @@ -0,0 +1,41 @@ +"""D7 housekeeping for a dedicated local synthetic-history export directory.""" +from __future__ import annotations + +import argparse +import os +import re +import stat +import time +from pathlib import Path + +RETENTION_SECONDS = 7 * 24 * 60 * 60 +# Exporters choose the creation second once and keep it when a file is copied. +LOCAL_HISTORY = re.compile(r"rg-history-v1-([0-9]{1,12})-[0-9a-f]{32}\.bin(?:\.partial)?", re.ASCII) + + +def expire_local_exports(directory: Path, now_seconds: int) -> int: + """Remove expired managed files. Caller owns and serializes this directory.""" + if now_seconds < 0: + raise ValueError("negative UTC time") + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + fd = os.open(directory, flags) + removed = 0 + try: + with os.scandir(fd) as entries: + for entry in entries: + match = LOCAL_HISTORY.fullmatch(entry.name) + if match is None or now_seconds - int(match[1]) < RETENTION_SECONDS: + continue + if stat.S_ISREG(entry.stat(follow_symlinks=False).st_mode): + os.unlink(entry.name, dir_fd=fd) + removed += 1 + finally: + os.close(fd) + return removed + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path, help="private local history directory") + args = parser.parse_args() + print(expire_local_exports(args.directory, int(time.time()))) diff --git a/tools/history/strict_reconciliation.h b/tools/history/strict_reconciliation.h new file mode 100644 index 0000000..54e9c6b --- /dev/null +++ b/tools/history/strict_reconciliation.h @@ -0,0 +1,328 @@ +#pragma once + +// Independent Release A stage reconciliation helper. It summarizes complete +// histories; it never decides quota safety or emits a PASS verdict. +#include "src/events/history_validator.h" + +#include +#include +#include +#include +#include +#include + +namespace rateguard::events::reconciliation { + +using namespace rateguard::events; + +struct AttemptDeadline final { + AttemptId attempt_id{}; + std::uint64_t deadline_ns{0}; +}; + +enum class EvidenceState : std::uint8_t { Complete = 1, Incomplete = 2, Invalid = 3 }; +enum class AttemptState : std::uint8_t { + TimelyAllow = 1, + TimelyLimited, + LateAllow, + LateLimited, + TerminalError, + CommittedUnanswered, + NoDecisionOrResponse, + Unresolved, + DuplicateStage, + OrphanStage, +}; + +enum class Violation : std::uint8_t { + None = 0, + DuplicateDeadline, + DeadlineWithoutOffer, + DuplicateStage, + OrphanStage, + AllowWithoutCommittedAllow, + DecisionResponseMismatch, + TimestampOrderViolation, + ForwardWithoutAllow, + CompletionWithoutForward, +}; + +struct AttemptResult final { + AttemptId attempt_id{}; + AttemptState state{AttemptState::Unresolved}; + bool has_deadline{false}; + bool has_strict_decision{false}; + bool committed{false}; + bool has_adapter_receipt{false}; + std::uint64_t duplicate_stage_count{0}; + bool timestamp_order_valid{true}; +}; + +struct ReconciliationReport final { + EvidenceState evidence{EvidenceState::Invalid}; + bool safety_pass_allowed{false}; + std::uint64_t offered_records{0}; + std::uint64_t offered_attempts{0}; + std::uint64_t strict_allow_commits{0}; + std::uint64_t strict_limited_decisions{0}; + std::uint64_t decision_unanswered{0}; + std::uint64_t limited_decision_unanswered{0}; + std::uint64_t adapter_receipts{0}; + std::uint64_t response_sends{0}; + std::uint64_t response_sent_unreceived{0}; + std::uint64_t timely_allow{0}; + std::uint64_t timely_limited{0}; + std::uint64_t late_allow{0}; + std::uint64_t late_limited{0}; + std::uint64_t terminal_errors{0}; + std::uint64_t committed_unanswered{0}; + std::uint64_t unresolved_attempts{0}; + std::uint64_t duplicate_stage_violations{0}; + std::uint64_t orphan_stage_attempts{0}; + std::uint64_t uncommitted_allow_responses{0}; + std::uint64_t decision_response_mismatches{0}; + std::uint64_t unmatched_deadlines{0}; + std::vector attempts; + std::vector violations; +}; + +namespace detail { +struct StageEvent final { + AttemptId id{}; + Stage stage{}; + Outcome outcome{}; + std::uint64_t timestamp_ns{}; +}; +struct DeadlineRow final { AttemptId id{}; std::uint64_t deadline{}; }; +struct AttemptRow final { + AttemptId id{}; + std::array stage{}; + std::array counts{}; + bool offered{false}; +}; +inline bool IdLess(const AttemptId& a, const AttemptId& b) noexcept { return a < b; } +inline bool Add(std::uint64_t& value, std::uint64_t amount) noexcept { + if (amount > std::numeric_limits::max() - value) return false; + value += amount; + return true; +} +inline std::size_t StageIndex(Stage stage) noexcept { return static_cast(stage); } +inline const DeadlineRow* FindDeadline(const std::vector& rows, + const AttemptId& id) noexcept { + auto it = std::lower_bound(rows.begin(), rows.end(), id, + [](const DeadlineRow& row, const AttemptId& key) { return row.id < key; }); + return it != rows.end() && it->id == id ? &*it : nullptr; +} +} // namespace detail + +// `deadlines` must come from the caller's offered-attempt schedule, keyed by +// the exact 16-byte AttemptId. No attempt ID is parsed or used to infer time. +inline ReconciliationReport ReconcileStrictHistory( + const EventSnapshotV1& snapshot, const RunPlan& expected_plan, + std::span deadlines) noexcept { + using namespace detail; + ReconciliationReport report; + const auto structural = validation::ValidateHistorySnapshot(snapshot, expected_plan); + if (structural.verdict == validation::Verdict::Invalid) { + report.evidence = EvidenceState::Invalid; + return report; + } + if (structural.verdict != validation::Verdict::Complete) { + report.evidence = EvidenceState::Incomplete; + return report; + } + try { + report.evidence = EvidenceState::Complete; + std::vector events; + if (structural.published_events > std::numeric_limits::max()) { + report.evidence = EvidenceState::Invalid; + return report; + } + events.reserve(static_cast(structural.published_events)); + for (const auto& producer : snapshot.producers) { + for (const auto& slot : producer.slots) { + if (slot.status != SlotStatus::Published) continue; + events.push_back({slot.event.attempt_id, slot.event.stage, slot.event.outcome, + slot.event.timestamp_ns}); + } + } + std::vector deadline_rows; + deadline_rows.reserve(deadlines.size()); + for (const auto& d : deadlines) { + if (d.deadline_ns == 0) { + report.evidence = EvidenceState::Invalid; + return report; + } + deadline_rows.push_back({d.attempt_id, d.deadline_ns}); + } + std::sort(deadline_rows.begin(), deadline_rows.end(), + [](const auto& a, const auto& b) { return a.id < b.id; }); + for (std::size_t i = 1; i < deadline_rows.size(); ++i) { + if (deadline_rows[i - 1].id == deadline_rows[i].id) { + report.evidence = EvidenceState::Invalid; + report.violations.push_back(Violation::DuplicateDeadline); + return report; + } + } + std::sort(events.begin(), events.end(), [](const auto& a, const auto& b) { + return a.id < b.id || (a.id == b.id && a.stage < b.stage); + }); + for (std::size_t begin = 0; begin < events.size();) { + std::size_t end = begin + 1; + while (end < events.size() && events[end].id == events[begin].id) ++end; + AttemptRow row; + row.id = events[begin].id; + for (std::size_t i = begin; i < end; ++i) { + const auto stage = StageIndex(events[i].stage); + if (stage < 1 || stage > 6) { + report.evidence = EvidenceState::Invalid; + return report; + } + ++row.counts[stage]; + if (!row.stage[stage]) row.stage[stage] = &events[i]; + if (events[i].stage == Stage::Offered) row.offered = true; + } + if (row.offered) { + if (!Add(report.offered_attempts, 1)) { report.evidence = EvidenceState::Invalid; return report; } + if (!Add(report.offered_records, row.counts[StageIndex(Stage::Offered)])) { report.evidence = EvidenceState::Invalid; return report; } + } else { + if (!Add(report.orphan_stage_attempts, 1)) { report.evidence = EvidenceState::Invalid; return report; } + report.violations.push_back(Violation::OrphanStage); + } + const auto* deadline = row.offered ? FindDeadline(deadline_rows, row.id) : nullptr; + const bool duplicate = [&] { + for (std::size_t stage = 1; stage <= 6; ++stage) + if (row.counts[stage] > 1) return true; + return false; + }(); + std::uint64_t duplicate_count = 0; + for (std::size_t stage = 1; stage <= 6; ++stage) + if (row.counts[stage] > 1) { + duplicate_count += row.counts[stage] - 1; + if (!Add(report.duplicate_stage_violations, row.counts[stage] - 1)) { + report.evidence = EvidenceState::Invalid; return report; + } + report.violations.push_back(Violation::DuplicateStage); + } + if (row.offered && !deadline) ++report.unmatched_deadlines; + const auto decision_stage = StageIndex(Stage::StrictDecision); + const auto received_stage = StageIndex(Stage::Received); + const auto responded_stage = StageIndex(Stage::Responded); + const auto* decision = row.counts[decision_stage] == 1 ? row.stage[decision_stage] : nullptr; + const auto* received = row.counts[received_stage] == 1 ? row.stage[received_stage] : nullptr; + const auto* responded = row.counts[responded_stage] == 1 ? row.stage[responded_stage] : nullptr; + const bool committed_allow = decision && decision->outcome == Outcome::Allow; + const bool decided_limited = decision && decision->outcome == Outcome::Limited; + if (decision && (committed_allow || decided_limited)) { + if (committed_allow) ++report.strict_allow_commits; + else ++report.strict_limited_decisions; + } + if (received && !Add(report.adapter_receipts, row.counts[StageIndex(Stage::Received)])) { report.evidence = EvidenceState::Invalid; return report; } + if (responded && !Add(report.response_sends, row.counts[StageIndex(Stage::Responded)])) { report.evidence = EvidenceState::Invalid; return report; } + if (row.counts[responded_stage] == 1 && row.counts[received_stage] == 0) + ++report.response_sent_unreceived; + if (responded && received && + (responded->outcome == Outcome::Allow || responded->outcome == Outcome::Limited) && + (received->outcome == Outcome::Allow || received->outcome == Outcome::Limited) && + responded->outcome != received->outcome) { + ++report.decision_response_mismatches; + report.violations.push_back(Violation::DecisionResponseMismatch); + } + bool timestamps_ordered = true; + const Stage ordered_stages[] = {Stage::Offered, Stage::StrictDecision, Stage::Responded, + Stage::Received, Stage::Forwarded, Stage::Completed}; + const StageEvent* prior = nullptr; + for (Stage stage : ordered_stages) { + const auto* current = row.stage[StageIndex(stage)]; + if (!current) continue; + if (prior && current->timestamp_ns < prior->timestamp_ns) timestamps_ordered = false; + prior = current; + } + if (!timestamps_ordered) report.violations.push_back(Violation::TimestampOrderViolation); + const auto forward_stage = StageIndex(Stage::Forwarded); + const auto completed_stage = StageIndex(Stage::Completed); + const auto* forwarded = row.counts[forward_stage] == 1 ? row.stage[forward_stage] : nullptr; + const auto* completed = row.counts[completed_stage] == 1 ? row.stage[completed_stage] : nullptr; + const bool forwarding_permitted = committed_allow && received && deadline && received->outcome == Outcome::Allow && + received->timestamp_ns < deadline->deadline; + if (forwarded && !forwarding_permitted) + report.violations.push_back(Violation::ForwardWithoutAllow); + if (completed && !forwarded) report.violations.push_back(Violation::CompletionWithoutForward); + AttemptResult result; + result.attempt_id = row.id; + result.has_deadline = deadline != nullptr; + result.has_strict_decision = decision != nullptr; + result.committed = committed_allow; + result.has_adapter_receipt = received != nullptr; + result.duplicate_stage_count = duplicate_count; + result.timestamp_order_valid = timestamps_ordered; + if (!row.offered) { + result.state = AttemptState::OrphanStage; + } else if (duplicate) { + result.state = AttemptState::DuplicateStage; + ++report.unresolved_attempts; + } else if (received && !deadline) { + result.state = AttemptState::Unresolved; + ++report.unresolved_attempts; + } else if (received) { + const bool timely = received->timestamp_ns < deadline->deadline; + if (received->outcome == Outcome::Allow) { + if (committed_allow) { + result.state = timely ? AttemptState::TimelyAllow : AttemptState::LateAllow; + if (timely) ++report.timely_allow; else ++report.late_allow; + } else { + result.state = AttemptState::Unresolved; + ++report.unresolved_attempts; + ++report.uncommitted_allow_responses; + report.violations.push_back(Violation::AllowWithoutCommittedAllow); + } + } else if (received->outcome == Outcome::Limited) { + if (decided_limited) { + result.state = timely ? AttemptState::TimelyLimited : AttemptState::LateLimited; + if (timely) ++report.timely_limited; else ++report.late_limited; + } else { + result.state = AttemptState::Unresolved; + ++report.unresolved_attempts; + if (decision && (committed_allow || decided_limited)) { + ++report.decision_response_mismatches; + report.violations.push_back(Violation::DecisionResponseMismatch); + } + } + } else { + result.state = AttemptState::TerminalError; + ++report.terminal_errors; + } + } else if (committed_allow || decided_limited) { + result.state = AttemptState::CommittedUnanswered; + ++report.decision_unanswered; + if (!deadline) ++report.unresolved_attempts; + if (committed_allow) ++report.committed_unanswered; + else ++report.limited_decision_unanswered; + } else { + result.state = AttemptState::NoDecisionOrResponse; + ++report.unresolved_attempts; + } + report.attempts.push_back(result); + begin = end; + } + for (const auto& d : deadline_rows) { + const auto found = std::lower_bound(events.begin(), events.end(), d.id, + [](const StageEvent& e, const AttemptId& id) { return e.id < id; }); + bool has_offer = false; + for (auto it = found; it != events.end() && it->id == d.id; ++it) + if (it->stage == Stage::Offered) { has_offer = true; break; } + if (!has_offer) { + ++report.unmatched_deadlines; + report.violations.push_back(Violation::DeadlineWithoutOffer); + } + } + return report; + } catch (...) { + report.evidence = EvidenceState::Incomplete; + report.safety_pass_allowed = false; + report.attempts.clear(); + return report; + } +} + +} // namespace rateguard::events::reconciliation diff --git a/tools/policy_v1_oracle.py b/tools/policy_v1_oracle.py new file mode 100644 index 0000000..a932a6a --- /dev/null +++ b/tools/policy_v1_oracle.py @@ -0,0 +1,225 @@ +"""Independent policy-v1 canonical encoder. + +This is an oracle derived from docs/contracts/policy-v1.md, not a wrapper around +or shared implementation with the C++ codec. It handles the frozen valid JSON +fixture so its bytes and digest can be compared directly with production output. +""" +from __future__ import annotations + +import hashlib +import json +import re +import struct +from pathlib import Path +from typing import Any + +U32_MAX = (1 << 32) - 1 +U64_MAX = (1 << 64) - 1 +ID_RE = re.compile(r"[A-Za-z0-9_.-]{1,128}\Z") +DECIMAL_RE = re.compile(r"(?:0|[1-9][0-9]*)\Z") +HEX16_RE = re.compile(r"[0-9a-f]{32}\Z") +HEX32_RE = re.compile(r"[0-9a-f]{64}\Z") +ROLE_VALUE = {"adapter": 1, "replica": 2, "authority": 3} + + +def u8(value: int) -> bytes: + if not 0 <= value <= 0xff: + raise ValueError("u8 out of range") + return struct.pack(">B", value) + + +def u32(value: int) -> bytes: + if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= U32_MAX: + raise ValueError("u32 out of range") + return struct.pack(">I", value) + + +def decimal_u64(value: Any) -> int: + if not isinstance(value, str) or not DECIMAL_RE.fullmatch(value): + raise ValueError("uint64 must be canonical decimal text") + result = int(value) + if result > U64_MAX: + raise ValueError("uint64 out of range") + return result + + +def u64_decimal(value: Any) -> bytes: + return struct.pack(">Q", decimal_u64(value)) + + +def ascii_string(value: Any) -> bytes: + if not isinstance(value, str): + raise ValueError("expected string") + encoded = value.encode("ascii") + if len(encoded) > U32_MAX: + raise ValueError("string too long") + return u32(len(encoded)) + encoded + + +def fixed_hex(value: Any, regex: re.Pattern[str]) -> bytes: + if not isinstance(value, str) or not regex.fullmatch(value): + raise ValueError("invalid lower-case fixed-width hex") + return bytes.fromhex(value) + + +def identifier(value: Any) -> str: + if not isinstance(value, str) or not ID_RE.fullmatch(value): + raise ValueError(f"invalid identifier: {value!r}") + return value + + +def bounded_policy_units(value: Any) -> bytes: + numeric = decimal_u64(value) + if not 1 <= numeric <= 1_000_000_000: + raise ValueError("policy units outside 1..1e9") + return struct.pack(">Q", numeric) + + +def encode_policy(policy: dict[str, Any]) -> bytes: + """Encode a valid schema-v1 policy in canonical byte order.""" + schema_version = policy["schema_version"] + if isinstance(schema_version, bool) or schema_version != 1: + raise ValueError("unsupported schema version") + mode = policy["mode"] + if mode not in ("strict", "credit"): + raise ValueError("unsupported mode") + + epoch = fixed_hex(policy["epoch_id"], HEX16_RE) + authority_incarnation = fixed_hex(policy["authority_incarnation"], HEX16_RE) + trust_root = fixed_hex(policy["trust_root_sha256"], HEX32_RE) + + slots = sorted(policy["replica_slots"], key=lambda slot: slot["slot_id"]) + slot_rows: list[bytes] = [] + slot_ids: set[int] = set() + slot_incarnations: dict[int, str] = {} + for slot in slots: + slot_id = slot["slot_id"] + if isinstance(slot_id, bool) or not isinstance(slot_id, int) or not 0 <= slot_id <= U32_MAX: + raise ValueError("slot_id is not uint32") + if slot_id in slot_ids: + raise ValueError("duplicate slot") + incarnation = fixed_hex(slot["incarnation_id"], HEX16_RE) + slot_ids.add(slot_id) + slot_incarnations[slot_id] = slot["incarnation_id"] + slot_rows.append(u32(slot_id) + incarnation) + + tenants = sorted(policy["tenants"], key=lambda tenant: identifier(tenant["tenant_id"]).encode("ascii")) + if not 1 <= len(tenants) <= 10_000: + raise ValueError("tenant count outside limit") + tenant_indices: dict[str, int] = {} + operation_indices: dict[tuple[str, str], int] = {} + tenant_rows: list[bytes] = [] + for tenant_index, tenant in enumerate(tenants): + tenant_id = identifier(tenant["tenant_id"]) + if tenant_id in tenant_indices: + raise ValueError("duplicate tenant") + tenant_indices[tenant_id] = tenant_index + capacity = decimal_u64(tenant["capacity_units"]) + rate = decimal_u64(tenant["rate_units_per_second"]) + if not 1 <= capacity <= 1_000_000_000 or not 1 <= rate <= 1_000_000_000: + raise ValueError("tenant capacity/rate out of bounds") + operations = sorted(tenant["operations"], + key=lambda operation: identifier(operation["operation_id"]).encode("ascii")) + if not 1 <= len(operations) <= 64: + raise ValueError("operation count outside limit") + operation_rows: list[bytes] = [] + max_cost = 0 + for operation_index, operation in enumerate(operations): + operation_id = identifier(operation["operation_id"]) + key = (tenant_id, operation_id) + if key in operation_indices: + raise ValueError("duplicate operation") + operation_indices[key] = operation_index + cost = decimal_u64(operation["cost_units"]) + if not 1 <= cost <= capacity: + raise ValueError("operation cost out of bounds") + max_cost = max(max_cost, cost) + operation_rows.append(ascii_string(operation_id) + struct.pack(">Q", cost)) + + has_q = mode == "credit" + if has_q != ("credit_batch_units" in tenant): + raise ValueError("credit_batch_units presence disagrees with mode") + if has_q: + q = decimal_u64(tenant["credit_batch_units"]) + if not max_cost <= q <= capacity: + raise ValueError("credit batch outside max operation cost..capacity") + encoded_tenant = (ascii_string(tenant_id) + + struct.pack(">Q", capacity) + + struct.pack(">Q", rate) + + u8(1 if has_q else 0)) + if has_q: + encoded_tenant += struct.pack(">Q", q) + tenant_rows.append(encoded_tenant + u32(len(operation_rows)) + b"".join(operation_rows)) + + principals = sorted(policy["principals"], key=lambda principal: principal["uri"].encode("ascii")) + uris: set[str] = set() + authorities = 0 + adapters = 0 + replica_slots: set[int] = set() + principal_rows: list[bytes] = [] + for principal in principals: + uri = principal["uri"] + uri_bytes = uri.encode("ascii") + if uri in uris: + raise ValueError("duplicate principal URI") + uris.add(uri) + role_name = principal["role"] + if role_name not in ROLE_VALUE: + raise ValueError("unknown principal role") + role = ROLE_VALUE[role_name] + expected_slot = None + if role_name == "adapter": + adapters += 1 + if not uri.startswith("spiffe://rateguard.local/adapter/"): + raise ValueError("adapter URI mismatch") + identifier(uri.rsplit("/", 1)[-1]) + elif role_name == "authority": + authorities += 1 + expected_uri = ("spiffe://rateguard.local/authority/" + + policy["authority_incarnation"]) + if uri != expected_uri or principal.get("permissions", []): + raise ValueError("authority URI/permissions mismatch") + else: + expected_slot = principal.get("slot_id") + if expected_slot not in slot_ids or expected_slot in replica_slots: + raise ValueError("replica slot absent or duplicate") + replica_slots.add(expected_slot) + incarnation = slot_incarnations[expected_slot] + expected_uri = (f"spiffe://rateguard.local/replica/{expected_slot}/{incarnation}") + if uri != expected_uri: + raise ValueError("replica URI and slot incarnation disagree") + + permissions = [] + for permission in principal.get("permissions", []): + key = (identifier(permission["tenant_id"]), + identifier(permission["operation_id"])) + if key not in operation_indices: + raise ValueError("permission references unknown tenant/operation") + permissions.append((key, tenant_indices[key[0]], operation_indices[key])) + permissions.sort(key=lambda item: (item[0][0].encode("ascii"), item[0][1].encode("ascii"))) + if len({item[0] for item in permissions}) != len(permissions): + raise ValueError("duplicate permission") + row = ascii_string(uri) + u32(role) + if role_name == "replica": + row += u32(expected_slot) + row += u32(len(permissions)) + row += b"".join(u32(tenant_i) + u32(operation_i) + for _, tenant_i, operation_i in permissions) + principal_rows.append(row) + + if adapters < 1 or authorities != 1 or replica_slots != slot_ids: + raise ValueError("principal inventory incomplete or invalid") + + return (u32(1) + u32(1 if mode == "strict" else 2) + + epoch + authority_incarnation + trust_root + + u32(len(slot_rows)) + b"".join(slot_rows) + + u32(len(tenant_rows)) + b"".join(tenant_rows) + + u32(len(principal_rows)) + b"".join(principal_rows)) + + +def load_fixture(path: Path) -> dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) + + +def digest(policy: dict[str, Any]) -> str: + return hashlib.sha256(encode_policy(policy)).hexdigest() diff --git a/tools/probes/docker_time_preflight.py b/tools/probes/docker_time_preflight.py new file mode 100644 index 0000000..c54af8e --- /dev/null +++ b/tools/probes/docker_time_preflight.py @@ -0,0 +1,438 @@ +#!/usr/bin/env python3 +"""Observe Linux UTC/time-namespace behavior in a tightly constrained Docker run. + +This is a capability observation only. It does not establish epoch supervision, +common deployment configuration, or a production quota guarantee. +""" +from __future__ import annotations + +import argparse +import datetime as _datetime +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import threading +import uuid +from pathlib import Path +from typing import Any, Sequence + +MAX_STDOUT = 8192 +MAX_STDERR = 2048 +COMMAND_TIMEOUT_SECONDS = 45 +IMAGE_PULL_TIMEOUT_SECONDS = 120 + + +class HarnessError(Exception): + pass + + +def _drain(stream: Any, limit: int, result: dict[str, Any], key: str) -> None: + kept = bytearray() + truncated = False + while True: + chunk = stream.read(1024) + if not chunk: + break + room = limit - len(kept) + if room > 0: + kept.extend(chunk[:room]) + if len(chunk) > room: + truncated = True + result[key] = bytes(kept).decode("utf-8", errors="replace") + result[key + "_truncated"] = truncated + + +def run_capture(argv: Sequence[str], timeout: int = COMMAND_TIMEOUT_SECONDS) -> dict[str, Any]: + """Run argv with capped, drained stdout/stderr and an explicit timeout.""" + try: + proc = subprocess.Popen( + list(argv), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, close_fds=True, start_new_session=True, + ) + except FileNotFoundError: + return {"started": False, "return_code": None, "timed_out": False, + "stdout": "", "stderr": "", "error": "executable_not_found"} + except OSError as exc: + return {"started": False, "return_code": None, "timed_out": False, + "stdout": "", "stderr": "", "error": f"spawn_error:{exc.errno}"} + + buffers: dict[str, Any] = {} + out_thread = threading.Thread(target=_drain, args=(proc.stdout, MAX_STDOUT, buffers, "stdout")) + err_thread = threading.Thread(target=_drain, args=(proc.stderr, MAX_STDERR, buffers, "stderr")) + out_thread.start() + err_thread.start() + timed_out = False + try: + return_code = proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + timed_out = True + try: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + proc.kill() + return_code = proc.wait() + out_thread.join() + err_thread.join() + return {"started": True, "return_code": return_code, "timed_out": timed_out, + "stdout": buffers.get("stdout", ""), + "stdout_truncated": buffers.get("stdout_truncated", False), + "stderr": buffers.get("stderr", ""), + "stderr_truncated": buffers.get("stderr_truncated", False), + "error": "timeout" if timed_out else None} + + +def _parse_json_stdout(result: dict[str, Any]) -> dict[str, Any] | None: + if result.get("stdout_truncated"): + return None + try: + value = json.loads(result.get("stdout", "")) + except (json.JSONDecodeError, TypeError): + return None + return value if isinstance(value, dict) else None + + +def _parse_clock_sample(result: dict[str, Any]) -> dict[str, Any] | None: + if result.get("return_code") != 0 or result.get("stdout_truncated"): + return None + rows = result.get("stdout", "").splitlines() + if len(rows) != 1: + return None + fields = rows[0].split("|") + # Eight pipe-delimited identity fields followed by one monotonic timestamp. + if len(fields) != 9 or not fields[0] or any(not field for field in fields): + return None + if not re.fullmatch(r"[0-9a-f]{32}", fields[0]): + return None + if any(not re.fullmatch(r"-?(?:0|[1-9][0-9]*)", value) for value in fields[1:]): + return None + if any(value == "-0" for value in fields[1:]): + return None + try: + values = [int(value, 10) for value in fields[1:]] + except ValueError: + return None + if values[0] < 0 or values[1] <= 0 or values[1] > (1 << 64) - 1: + return None + if values[0] > (1 << 64) - 1: + return None + if not (-(1 << 63) <= values[2] < (1 << 63)): + return None + if not (-(1 << 63) <= values[4] < (1 << 63)): + return None + if values[3] < 0 or values[5] < 0: + return None + if values[3] > 999_999_999 or values[5] > 999_999_999: + return None + if values[6] != 1: + return None + if values[7] < 0 or values[7] > (1 << 64) - 1: + return None + return {"identity_fields": fields[:8], "monotonic_ns": values[7]} + + +def _valid_probe_path(raw: str, label: str) -> str: + path = Path(raw) + if not path.is_absolute(): + raise HarnessError(f"{label} path must be absolute") + if path.is_symlink() or not path.is_file() or not os.access(path, os.X_OK): + raise HarnessError(f"{label} path must be a regular executable, not a symlink") + canonical = str(path.resolve(strict=True)) + if "," in canonical: + raise HarnessError(f"{label} path cannot contain a comma for Docker mount syntax") + return canonical + + +def _docker_base_args(image_ref: str, uid: int, gid: int, + wall_path: str, clock_path: str, + container_name: str) -> list[str]: + return [ + "docker", "run", "--rm", "--pull=never", + "--cap-drop=ALL", "--security-opt=no-new-privileges", + "--read-only", "--network=none", "--user", f"{uid}:{gid}", + "--pids-limit=64", "--memory=256m", "--cpus=1", + "--name", container_name, + "--mount", f"type=bind,source={wall_path},target=/probes/wall,readonly", + "--mount", f"type=bind,source={clock_path},target=/probes/clock,readonly", + image_ref, + ] + + +def _docker_run_probe(image_ref: str, uid: int, gid: int, + wall_path: str, clock_path: str, probe: str) -> dict[str, Any]: + container_name = f"rateguard-preflight-{os.getpid()}-{uuid.uuid4().hex[:12]}" + base = _docker_base_args(image_ref, uid, gid, wall_path, clock_path, + container_name) + if probe == "wall": + result = run_capture(base + ["/probes/wall"]) + else: + result = run_capture(base + ["/probes/clock", "--child"]) + if result.get("timed_out"): + cleanup = run_capture(["docker", "rm", "--force", container_name], timeout=15) + result["cleanup_return_code"] = cleanup.get("return_code") + return result + + +def _image_metadata(docker_bin: str, image: str) -> tuple[dict[str, Any], str | None]: + inspect = run_capture([docker_bin, "image", "inspect", "--format", + "{{json .RepoDigests}}|{{.Id}}", image]) + if inspect.get("return_code") == 0 and not inspect.get("stdout_truncated"): + parsed = _decode_image_metadata(inspect.get("stdout", "")) + match = _matching_digest(image, parsed[0]) if parsed else None + if parsed and match: + return ({"inspect_return_code": inspect.get("return_code"), + "repo_digests": parsed[0], "image_id": parsed[1]}, match) + + pull = run_capture([docker_bin, "pull", "--quiet", image], timeout=IMAGE_PULL_TIMEOUT_SECONDS) + inspect_after = run_capture([docker_bin, "image", "inspect", "--format", + "{{json .RepoDigests}}|{{.Id}}", image]) + parsed = _decode_image_metadata(inspect_after.get("stdout", "")) + metadata = {"inspect_before": _command_status(inspect), + "pull": _command_status(pull), + "inspect_after": _command_status(inspect_after), + "repo_digests": parsed[0] if parsed else [], + "image_id": parsed[1] if parsed else None} + digest_ref = _matching_digest(image, parsed[0]) if parsed else None + return metadata, digest_ref + + +def _command_status(result: dict[str, Any]) -> dict[str, Any]: + return {"started": result.get("started"), + "return_code": result.get("return_code"), + "timed_out": result.get("timed_out"), + "error": result.get("error")} + + +def _matching_digest(image: str, digests: list[str]) -> str | None: + if any(not re.fullmatch(r"[^@\s]+@sha256:[0-9a-f]{64}", entry) + for entry in digests): + return None + repository = image.split("@", 1)[0] + colon = repository.rfind(":") + slash = repository.rfind("/") + if colon > slash: + repository = repository[:colon] + aliases = {repository} + if repository.startswith("docker.io/library/"): + aliases.add(repository[len("docker.io/library/"):]) + elif repository.startswith("docker.io/"): + aliases.add("docker.io/library/" + repository[len("docker.io/"):]) + elif "/" not in repository: + aliases.add("docker.io/library/" + repository) + prefixes = tuple(alias + "@sha256:" for alias in aliases) + return next((entry for entry in digests + if entry.startswith(prefixes)), None) + + +def _decode_image_metadata(text: str) -> tuple[list[str], str] | None: + line = text.strip() + if "|" not in line: + return None + digests_text, image_id = line.split("|", 1) + try: + digests = json.loads(digests_text) + except json.JSONDecodeError: + return None + if digests is None: + digests = [] + if not isinstance(digests, list) or not all( + isinstance(item, str) and + re.fullmatch(r"[^@\s]+@sha256:[0-9a-f]{64}", item) + for item in digests): + return None + if not re.fullmatch(r"sha256:[0-9a-f]{64}", image_id): + return None + return digests, image_id + + +def _wall_summary(result: dict[str, Any]) -> dict[str, Any]: + probe = _parse_json_stdout(result) + if probe is None: + return {"return_code": result.get("return_code"), "valid_json": False, + "probe": None, "error": result.get("error") or "invalid_json_output"} + return {"return_code": result.get("return_code"), "valid_json": True, + "probe": probe, "error": result.get("error")} + + +def _clock_summary(result: dict[str, Any]) -> dict[str, Any]: + parsed = _parse_clock_sample(result) + return {"return_code": result.get("return_code"), "sample": parsed, + "error": result.get("error") or (None if parsed else "invalid_clock_output")} + + +def _trusted_wall(summary: dict[str, Any]) -> bool: + p = summary.get("probe") + if not (summary.get("valid_json") and summary.get("return_code") == 0 and + isinstance(p, dict) and p.get("platform") == "linux" and + p.get("trusted") is True and p.get("failure_reason") is None): + return False + sync_state = p.get("sync_state") + flags = p.get("status_flags") + seconds = p.get("unix_seconds") + nanoseconds = p.get("nanoseconds") + return (type(sync_state) is int and 0 <= sync_state <= 4 and + type(flags) is int and flags >= 0 and (flags & 0x1040) == 0 and + type(seconds) is int and 0 <= seconds <= (1 << 63) - 1 and + type(nanoseconds) is int and 0 <= nanoseconds < 1_000_000_000) + + +def _readiness(host_wall_before: dict[str, Any], host_wall_after: dict[str, Any], + container_wall: dict[str, Any], host_clock_before: dict[str, Any], + container_clock: dict[str, Any], host_clock_after: dict[str, Any], + docker_run_errors: list[str]) -> tuple[str, dict[str, Any]]: + if docker_run_errors: + return "NOT_RUN", {"reason": docker_run_errors[0]} + if not (_trusted_wall(host_wall_before) and _trusted_wall(host_wall_after) and + _trusted_wall(container_wall)): + return "NOT_READY", {"reason": "host_or_container_utc_untrusted"} + clocks = [host_clock_before.get("sample"), container_clock.get("sample"), + host_clock_after.get("sample")] + if any(sample is None for sample in clocks): + return "NOT_READY", {"reason": "clock_namespace_probe_failed"} + before, inside, after = clocks + identity_match = (before["identity_fields"] == inside["identity_fields"] == + after["identity_fields"]) + time_ordered = before["monotonic_ns"] <= inside["monotonic_ns"] <= after["monotonic_ns"] + comparison = {"identity_fields_match": identity_match, + "monotonic_samples_ordered": time_ordered, + "host_before_ns": before["monotonic_ns"], + "container_ns": inside["monotonic_ns"], + "host_after_ns": after["monotonic_ns"]} + if not identity_match: + return "NOT_READY", {"reason": "time_namespace_identity_mismatch", + "comparison": comparison} + if not time_ordered: + return "NOT_READY", {"reason": "monotonic_sample_order_mismatch", + "comparison": comparison} + return "OBSERVATIONS_MATCHED", {"reason": None, "comparison": comparison} + + +def _docker_executable() -> str | None: + return shutil.which("docker") + + +def collect(args: argparse.Namespace) -> dict[str, Any]: + wall_path = _valid_probe_path(args.wall_probe, "wall probe") + clock_path = _valid_probe_path(args.clock_probe, "clock probe") + if wall_path == clock_path: + raise HarnessError("wall and clock probes must be different executables") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/:@-]{0,255}", args.image): + raise HarnessError("image must be a bounded Docker image reference") + + artifact: dict[str, Any] = { + "schema_version": 1, + "observed_at_utc": _datetime.datetime.now(_datetime.timezone.utc).isoformat(), + "scope": "capability observation only, not full deployment/epoch supervision", + "requested_image_tag": args.image, + "docker": {"available": False, "version": None, "repo_digest": None, + "image_id": None, "error": None}, + "host": {"wall_before": None, "wall_after": None, + "clock_before": None, "clock_after": None}, + "container": {"wall": None, "clock": None}, + "readiness": {"state": "NOT_RUN", "reason": "docker_not_checked", + "comparison": None}, + "limitations": [ + "A matched observation does not prove shared Docker deployment topology, epoch fencing, supervisor behavior, or a quota guarantee.", + "The image tag is mutable; the observed RepoDigest and image ID are recorded for this run.", + "No Docker permissions or capabilities are broadened to force a ready observation.", + ], + } + + docker_bin = _docker_executable() + docker_run_errors: list[str] = [] + image_ref: str | None = None + if docker_bin is None: + artifact["docker"]["error"] = "docker_executable_not_found" + else: + version = run_capture([docker_bin, "version", "--format", + "{{.Client.Version}}|{{.Server.Version}}"]) + artifact["docker"]["version_result"] = { + "return_code": version.get("return_code"), + "stdout": version.get("stdout", "").strip()[:256], + "error": version.get("error"), + } + if version.get("return_code") != 0 or version.get("timed_out"): + artifact["docker"]["error"] = "docker_daemon_unavailable" + else: + artifact["docker"]["available"] = True + artifact["docker"]["version"] = version.get("stdout", "").strip()[:256] + meta, image_ref = _image_metadata(docker_bin, args.image) + artifact["docker"]["image_metadata_result"] = meta + artifact["docker"]["repo_digest"] = image_ref + artifact["docker"]["image_id"] = meta.get("image_id") + if image_ref is None: + artifact["docker"]["error"] = "image_pull_or_digest_unavailable" + + # Host-only observations are still useful if Docker is absent or unsupported. + artifact["host"]["wall_before"] = _wall_summary( + run_capture([wall_path])) + artifact["host"]["clock_before"] = _clock_summary( + run_capture([clock_path, "--child"])) + + if docker_bin and artifact["docker"]["available"] and image_ref: + uid, gid = os.getuid(), os.getgid() + wall_container_raw = _docker_run_probe(image_ref, uid, gid, + wall_path, clock_path, "wall") + clock_container_raw = _docker_run_probe(image_ref, uid, gid, + wall_path, clock_path, "clock") + artifact["container"]["wall"] = _wall_summary(wall_container_raw) + artifact["container"]["clock"] = _clock_summary(clock_container_raw) + for label, raw in (("wall", wall_container_raw), ("clock", clock_container_raw)): + if (not raw.get("started") or raw.get("timed_out") or + raw.get("return_code") in (125, 126, 127)): + docker_run_errors.append(f"container_{label}_probe_not_run_or_failed") + else: + docker_run_errors.append(artifact["docker"].get("error") or "docker_not_available") + + artifact["host"]["wall_after"] = _wall_summary(run_capture([wall_path])) + artifact["host"]["clock_after"] = _clock_summary( + run_capture([clock_path, "--child"])) + + state, details = _readiness( + artifact["host"]["wall_before"], artifact["host"]["wall_after"], + artifact["container"]["wall"] or {}, artifact["host"]["clock_before"], + artifact["container"]["clock"] or {}, artifact["host"]["clock_after"], + docker_run_errors, + ) + artifact["readiness"] = {"state": state, "reason": details.get("reason"), + "comparison": details.get("comparison")} + return artifact + + +def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--wall-probe", required=True, + help="absolute path to the built trusted_wall_clock_probe executable") + parser.add_argument("--clock-probe", required=True, + help="absolute path to the built rateguard_clock_linux_smoke executable") + parser.add_argument("--image", default="ubuntu:24.04", + help="Docker image tag to observe (default: ubuntu:24.04)") + return parser.parse_args(argv) + + +def main(argv: Sequence[str] | None = None) -> int: + try: + artifact = collect(parse_args(argv)) + except HarnessError as exc: + print(json.dumps({"error": str(exc), "readiness": "NOT_RUN"}, + separators=(",", ":"))) + return 1 + except Exception as exc: # bounded class name only; never dump environment data + print(json.dumps({"error": f"harness_error:{type(exc).__name__}", + "readiness": "NOT_RUN"}, separators=(",", ":"))) + return 1 + encoded = json.dumps(artifact, separators=(",", ":"), sort_keys=True) + if len(encoded.encode("utf-8")) > 64 * 1024: + print(json.dumps({"error": "artifact_size_limit_exceeded", + "readiness": "NOT_RUN"}, separators=(",", ":"))) + return 1 + print(encoded) + # Exit zero means diagnostics were collected; readiness is an artifact field. + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/probes/trusted_wall_clock_probe.cpp b/tools/probes/trusted_wall_clock_probe.cpp new file mode 100644 index 0000000..404f182 --- /dev/null +++ b/tools/probes/trusted_wall_clock_probe.cpp @@ -0,0 +1,97 @@ +#include "security/trusted_wall_clock.h" + +#include +#include +#include +#include +#include + +using namespace rateguard::security; + +namespace { +struct Capture { + std::optional synchronization; + std::optional realtime; +}; + +class CapturingPlatform final : public ITrustedWallClockPlatform { + public: + explicit CapturingPlatform(std::shared_ptr capture) + : capture_(std::move(capture)) {} + + TrustedWallClockResult ReadSynchronization() override { + auto result = native_.ReadSynchronization(); + if (const auto* status = std::get_if(&result)) + capture_->synchronization = *status; + return result; + } + + TrustedWallClockResult ReadRealtime() override { + auto result = native_.ReadRealtime(); + if (const auto* sample = std::get_if(&result)) + capture_->realtime = *sample; + return result; + } + + private: + std::shared_ptr capture_; + NativeTrustedWallClockPlatform native_; +}; + +void EmitJson(const Capture& capture, bool trusted, + const TrustedWallClockFailureReason* reason) { +#if defined(__linux__) + constexpr std::string_view platform = "linux"; +#else + constexpr std::string_view platform = "unsupported"; +#endif + std::cout << "{\"platform\":\"" << platform << "\",\"sync_state\":"; + if (capture.synchronization) + std::cout << capture.synchronization->state; + else + std::cout << "null"; + std::cout << ",\"status_flags\":"; + if (capture.synchronization) + std::cout << capture.synchronization->flags; + else + std::cout << "null"; + std::cout << ",\"trusted\":" << (trusted ? "true" : "false") + << ",\"failure_reason\":"; + if (reason) + std::cout << '"' << FailureReasonName(*reason) << '"'; + else + std::cout << "null"; + if (trusted && capture.realtime) { + std::cout << ",\"unix_seconds\":" << capture.realtime->seconds + << ",\"nanoseconds\":" << capture.realtime->nanoseconds; + } + std::cout << "}\n"; +} +} // namespace + +int main() { + try { + auto capture = std::make_shared(); + std::unique_ptr platform = + std::make_unique(capture); + auto clock_result = TrustedWallClock::Create(std::move(platform)); + if (auto* clock = std::get_if>(&clock_result)) { + const bool trusted = (*clock)->Healthy() && capture->synchronization && + capture->realtime; + if (trusted) { + EmitJson(*capture, true, nullptr); + return 0; + } + const auto reason = TrustedWallClockFailureReason::LatchedFailure; + EmitJson(*capture, false, &reason); + return 2; + } + const auto& failure = std::get(clock_result); + EmitJson(*capture, false, &failure.reason); + return 2; + } catch (...) { + const auto reason = TrustedWallClockFailureReason::PlatformUnavailable; + EmitJson(Capture{}, false, &reason); + return 1; + } +} diff --git a/tools/tests/b2_mutation_test.py b/tools/tests/b2_mutation_test.py new file mode 100644 index 0000000..b764e7d --- /dev/null +++ b/tools/tests/b2_mutation_test.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Check actual RPC behavior and isolated mutants without exposing child output.""" +import argparse +import os +import re +import resource +import signal +import subprocess +import tempfile + +LIMIT = 64 * 1024 +ARMOR = re.compile(rb'-----BEGIN [A-Z0-9 ]{1,80}-----') +RPC_OK = b'PASS peer_authorization_real_tls_rpc' +AUTH_OK = b'peer authenticator checks passed' +PAIR_FAIL = b'FAIL known_unauthorized_pair_maps_permission_denied_before_state_spy' +PIN_FAIL = b'FAIL: same URI with different leaf DER fails pin check' + +def cap_files(): + resource.setrlimit(resource.RLIMIT_FSIZE, (LIMIT, LIMIT)) + +def run(binary, fixture): + with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err: + child = subprocess.Popen([binary, fixture], stdout=out, stderr=err, + start_new_session=True, preexec_fn=cap_files) + try: + code = child.wait(timeout=120) + except subprocess.TimeoutExpired: + try: + os.killpg(child.pid, signal.SIGKILL) + except ProcessLookupError: + pass + child.wait() + raise RuntimeError('test timeout; output withheld') from None + out.seek(0) + err.seek(0) + stdout, stderr = out.read(LIMIT + 1), err.read(LIMIT + 1) + if len(stdout) + len(stderr) >= LIMIT: + raise RuntimeError('test output cap reached; output withheld') + if ARMOR.search(stdout + stderr): + raise RuntimeError('PEM armor in test output; output withheld') + return code, stdout.strip(), stderr + +def positive(binary, fixture, expected): + code, stdout, _ = run(binary, fixture) + if code != 0 or stdout != expected: + raise RuntimeError('normal positive-control suite failed; output withheld') + +def negative(binary, fixture, expected): + code, stdout, stderr = run(binary, fixture) + failures = [line.strip() for line in stderr.splitlines() if line.startswith(b'FAIL')] + if code != 1 or stdout or failures != [expected]: + raise RuntimeError('unsafe variant escaped exact expected check; output withheld') + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--fixture', required=True) + parser.add_argument('--normal-rpc', required=True) + parser.add_argument('--pair-mutant-rpc') + parser.add_argument('--normal-auth') + parser.add_argument('--pin-mutant-auth') + args = parser.parse_args() + mutant_args = (args.pair_mutant_rpc, args.normal_auth, args.pin_mutant_auth) + if any(mutant_args) and not all(mutant_args): + parser.error('all mutant controls must be supplied together') + positive(args.normal_rpc, args.fixture, RPC_OK) + if not all(mutant_args): + print('PASS actual TLS peer authorization RPC checks') + return + negative(args.pair_mutant_rpc, args.fixture, PAIR_FAIL) + positive(args.normal_auth, args.fixture, AUTH_OK) + negative(args.pin_mutant_auth, args.fixture, PIN_FAIL) + print('PASS independent permission and leaf-pin defect controls') + +if __name__ == '__main__': + try: + main() + except (OSError, RuntimeError, subprocess.SubprocessError): + raise SystemExit('B2 child check failed; bounded output withheld') from None diff --git a/tools/tests/bucket_math_oracle.py b/tools/tests/bucket_math_oracle.py new file mode 100644 index 0000000..8880765 --- /dev/null +++ b/tools/tests/bucket_math_oracle.py @@ -0,0 +1,235 @@ +"""Independent arbitrary-precision oracle for the RG002 bucket transition API. + +Run locally with: + python3 -m unittest /tmp/rateguard-rg002-qa/tools/tests/bucket_math_oracle.py + +The oracle never imports or calls the C++ implementation; a tiny line protocol +adapter is compiled separately and compared against this model. +""" +from __future__ import annotations + +import os +import random +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +S = 1_000_000_000 +MAX_UNITS = 1_000_000_000 +U64_MAX = (1 << 64) - 1 +INPUT_ERROR = "ERR 0 0 0 0" # Input / InvalidArgument / Never / NotCommitted +INTERNAL_ERROR = "ERR 6 7 0 0" # Internal / Internal / Never / NotCommitted +QA_ROOT = Path(__file__).resolve().parents[2] +REPO_ROOT = Path(os.environ.get("RATEGUARD_REPO_ROOT", QA_ROOT)) +DRIVER_SOURCE = QA_ROOT / "tests" / "bucket_math_driver.cpp" +SOURCE_ROOT = REPO_ROOT +HEADER = REPO_ROOT / "src" / "authority" / "bucket_math.h" + + +def oracle_refill(capacity: int, rate: int, balance: int, last: int, now: int) -> str: + if not (1 <= capacity <= MAX_UNITS and 1 <= rate <= MAX_UNITS): + return INPUT_ERROR + capacity_subunits = capacity * S + if balance > capacity_subunits or now < last: + return INTERNAL_ERROR + elapsed = now - last + # Python integers are arbitrary precision: this intentionally differs from + # the checked-u128 implementation under test. + next_balance = min(capacity_subunits, balance + rate * elapsed) + return f"OK {next_balance} {now}" + + +def oracle_retry(deficit: int, rate: int) -> str: + if not (1 <= rate <= MAX_UNITS): + return INPUT_ERROR + return f"OK {(deficit + rate - 1) // rate}" + + +def oracle_decide(capacity: int, rate: int, balance: int, last: int, + cost: int, now: int) -> str: + if not (1 <= capacity <= MAX_UNITS and 1 <= rate <= MAX_UNITS): + return INPUT_ERROR + if not (1 <= cost <= capacity): + return INPUT_ERROR + refilled = oracle_refill(capacity, rate, balance, last, now) + if refilled.startswith("ERR "): + return refilled + _, available_text, timestamp_text = refilled.split() + available = int(available_text) + timestamp = int(timestamp_text) + cost_subunits = cost * S + if available >= cost_subunits: + return f"OK ALLOW {available - cost_subunits} {timestamp} -" + deficit = cost_subunits - available + delay = (deficit + rate - 1) // rate + return f"OK LIMITED {available} {timestamp} {delay}" + + +def oracle_command(line: str) -> str: + fields = line.split() + op = fields[0] + values = [int(value) for value in fields[1:]] + if op == "R" and len(values) == 5: + return oracle_refill(*values) + if op == "D" and len(values) == 6: + return oracle_decide(*values) + if op == "T" and len(values) == 2: + return oracle_retry(*values) + raise ValueError(f"bad command: {line!r}") + + +def compile_driver(output: Path, header_override: Path | None = None) -> None: + compiler = os.environ.get("CXX") or shutil.which("c++") + if not compiler: + raise RuntimeError("no C++20 compiler found") + include_dirs = [] + if header_override is not None: + include_dirs.append(header_override.parent.parent) + include_dirs.extend([SOURCE_ROOT / "src", SOURCE_ROOT / "include"]) + command = [compiler, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-pedantic"] + for directory in include_dirs: + command += ["-I", str(directory)] + command += [str(DRIVER_SOURCE), "-o", str(output)] + subprocess.run(command, check=True, capture_output=True, text=True, timeout=60) + + +def run_driver(executable: Path, lines: list[str]) -> list[str]: + result = subprocess.run([str(executable)], input="\n".join(lines) + "\n", + capture_output=True, text=True, check=True, timeout=30) + return result.stdout.splitlines() + + +def check_cases(executable: Path, lines: list[str]) -> None: + expected = [oracle_command(line) for line in lines] + actual = run_driver(executable, lines) + if actual != expected: + mismatches = [(line, want, got) for line, want, got in zip(lines, expected, actual) + if want != got] + raise AssertionError(f"{len(mismatches)} oracle mismatches; first: {mismatches[:3]}") + if len(actual) != len(expected): + raise AssertionError(f"driver emitted {len(actual)} lines for {len(expected)} inputs") + + +def golden_vectors() -> list[str]: + return [ + # Fractional unit refill: 1 ns at 3 units/s is 3 subunits exactly. + "R 4 3 0 100 101", + # Saturation, exact boundary admission, and one-subunit short. + f"R 3 2 {2*S} 10 1000000010", + f"D 1 1 {S-1} 0 1 1", + f"D 1 1 {S-2} 0 1 1", + # LIMITED with ceil(deficit/rate); known limited leaves debit unchanged. + "D 10 3 0 0 1 0", + # Weighted cost and full-capacity debit. + f"D 5 7 {5*S} 20 5 20", + # Maximum policy values and full uint64 elapsed time: safe saturation. + f"R {MAX_UNITS} {MAX_UNITS} 0 0 {U64_MAX}", + f"R {MAX_UNITS} {MAX_UNITS} {MAX_UNITS*S} 0 {U64_MAX}", + # Maximum legal balance/cost stay within uint64 storage after debit. + f"D {MAX_UNITS} 1 {MAX_UNITS*S} 0 {MAX_UNITS} 0", + # Retry division exact, rounded up, and at uint64 maximum. + "T 12 3", "T 13 3", f"T {U64_MAX} 1", + ] + + +def invalid_vectors() -> list[str]: + return [ + "R 0 1 0 0 0", f"R {MAX_UNITS+1} 1 0 0 0", + "R 1 0 0 0 0", f"R 1 {MAX_UNITS+1} 0 0 0", + f"D 1 1 {S} 0 0 0", f"D 1 1 {S} 0 2 0", + f"D {MAX_UNITS+1} 1 0 0 1 0", f"D 1 0 0 0 1 0", + f"D 1 1 {S+1} 0 1 0", # corrupt state + f"R 1 1 0 2 1", # clock moved backwards + "T 1 0", f"T 1 {MAX_UNITS+1}", + ] + + +def randomized_traces(seed: int = 0xD12A9, bucket_count: int = 24, + operations_per_bucket: int = 125) -> list[str]: + rng = random.Random(seed) + lines: list[str] = [] + for bucket_index in range(bucket_count): + capacity = rng.choice([1, 2, 3, 10, 999_999_999, MAX_UNITS, + rng.randint(1, MAX_UNITS)]) + rate = rng.choice([1, 2, 3, 7, MAX_UNITS, rng.randint(1, MAX_UNITS)]) + balance = rng.randint(0, capacity * S) + last = 0 + for operation_index in range(operations_per_bucket): + # Mostly short intervals, with occasional large intervals that + # trigger saturation. Timestamps remain monotone per bucket. + elapsed = rng.choice([0, 1, 2, 999_999_999, + rng.randint(0, 10**12)]) + now = last + elapsed + cost = rng.randint(1, capacity) + lines.append(f"D {capacity} {rate} {balance} {last} {cost} {now}") + expected = oracle_decide(capacity, rate, balance, last, cost, now) + parts = expected.split() + if parts[0] != "OK" or parts[1] not in ("ALLOW", "LIMITED"): + raise AssertionError(f"oracle emitted unexpected result: {expected}") + balance, last = int(parts[2]), int(parts[3]) + if operation_index % 5 == 0: + delta = rng.choice([0, 1, 1000, rng.randint(0, 10**9)]) + now = last + delta + lines.append(f"R {capacity} {rate} {balance} {last} {now}") + state = oracle_refill(capacity, rate, balance, last, now).split() + balance, last = int(state[1]), int(state[2]) + return lines + + +class BucketMathOracleTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + if not HEADER.is_file(): + raise FileNotFoundError(f"RG002 production header is required: {HEADER}") + if not DRIVER_SOURCE.is_file(): + raise FileNotFoundError(f"independent driver is required: {DRIVER_SOURCE}") + cls.temp = tempfile.TemporaryDirectory(prefix="rg002-oracle-") + cls.temp_path = Path(cls.temp.name) + cls.driver = cls.temp_path / "bucket_math_driver" + compile_driver(cls.driver) + + @classmethod + def tearDownClass(cls) -> None: + if hasattr(cls, "temp"): + cls.temp.cleanup() + + def test_golden_and_numeric_boundaries(self) -> None: + check_cases(self.driver, golden_vectors()) + + def test_invalid_and_corrupt_inputs_return_expected_errors(self) -> None: + check_cases(self.driver, invalid_vectors()) + + def test_seeded_arbitrary_precision_state_traces(self) -> None: + check_cases(self.driver, randomized_traces()) + + def _mutant_driver(self, name: str, old: str, new: str) -> Path: + source = HEADER.read_text(encoding="utf-8") + if old not in source: + self.fail(f"mutation anchor not found for {name}") + mutation_root = self.temp_path / f"mutant-{name}" + header = mutation_root / "authority" / "bucket_math.h" + header.parent.mkdir(parents=True, exist_ok=True) + header.write_text(source.replace(old, new, 1), encoding="utf-8") + executable = self.temp_path / f"driver-{name}" + compile_driver(executable, header_override=header) + return executable + + def test_reject_all_mutation_is_detected(self) -> None: + mutant = self._mutant_driver( + "reject-all", "BucketDecision{DecisionOutcome::Allow,", + "BucketDecision{DecisionOutcome::Limited,") + lines = ["D 10 1 8000000000 0 2 0"] + self.assertNotEqual(run_driver(mutant, lines), [oracle_command(line) for line in lines]) + + def test_double_debit_mutation_is_detected(self) -> None: + mutant = self._mutant_driver( + "double-debit", "available.balance_subunits - cost_subunits,", + "available.balance_subunits - (cost_subunits * 2),") + lines = ["D 10 1 8000000000 0 2 0"] + self.assertNotEqual(run_driver(mutant, lines), [oracle_command(line) for line in lines]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/certificate_registry_independent_test.cpp b/tools/tests/certificate_registry_independent_test.cpp new file mode 100644 index 0000000..640bbf8 --- /dev/null +++ b/tools/tests/certificate_registry_independent_test.cpp @@ -0,0 +1,426 @@ +#include "rateguard/security/certificate_registry.h" +#include "policy/canonical_codec.h" +#include "policy/policy_loader.h" +#include "ephemeral_pki.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; +using rateguard::security::test::EphemeralPki; + +namespace { +class FixedClock final : public sec::ITrustedWallClock { + public: + explicit FixedClock(sec::WallTime value) : value_(value) {} + sec::TrustedWallClockResult Now() override { + if (failure_) return sec::TrustedWallClockFailure{*failure_}; + return value_; + } + bool Healthy() const override { return !failure_.has_value(); } + void Set(sec::WallTime value) { value_ = value; } + void Fail() { failure_ = sec::TrustedWallClockFailureReason::UnsynchronizedFlag; } + private: + sec::WallTime value_; + std::optional failure_; +}; + +[[noreturn]] void Fail(std::string_view label) { + std::cerr << "FAIL " << label << '\n'; + std::exit(1); +} +void Check(bool condition, std::string_view label) { + if (!condition) Fail(label); +} + +std::string ReadFile(const char* path) { + std::ifstream in(path, std::ios::binary); + if (!in) Fail("fixture_open"); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} +std::string Hex(std::span bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string out; + out.reserve(bytes.size() * 2); + for (const auto b : bytes) { + out.push_back(digits[b >> 4]); + out.push_back(digits[b & 15]); + } + return out; +} +sec::Sha256Digest DerDigest(std::string_view pem) { + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (!raw_bio) Fail("fixture_parse"); + std::unique_ptr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (!raw_cert) Fail("fixture_parse"); + std::unique_ptr cert(raw_cert, X509_free); + const int size = i2d_X509(cert.get(), nullptr); + if (size <= 0) Fail("fixture_der"); + std::vector der(static_cast(size)); + auto* cursor = der.data(); + if (i2d_X509(cert.get(), &cursor) != size) Fail("fixture_der"); + sec::Sha256Digest digest{}; + unsigned int output_size = 0; + if (EVP_Digest(der.data(), der.size(), digest.data(), &output_size, + EVP_sha256(), nullptr) != 1 || output_size != digest.size()) { + Fail("fixture_sha256"); + } + return digest; +} +sec::WallTime CertTime(std::string_view pem, bool not_after) { + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (!raw_bio) Fail("fixture_time_parse"); + std::unique_ptr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (!raw_cert) Fail("fixture_time_parse"); + std::unique_ptr cert(raw_cert, X509_free); + std::tm fields{}; + const ASN1_TIME* value = not_after ? X509_get0_notAfter(cert.get()) + : X509_get0_notBefore(cert.get()); + if (ASN1_TIME_to_tm(value, &fields) != 1) Fail("fixture_time_convert"); + const std::time_t seconds = timegm(&fields); + if (seconds == static_cast(-1)) Fail("fixture_time_convert"); + return {static_cast(seconds), 0}; +} +std::string BindPolicyRoot(std::string json, const sec::Sha256Digest& digest) { + constexpr std::string_view key = "\"trust_root_sha256\": \""; + const auto begin = json.find(key); + if (begin == std::string::npos) Fail("fixture_policy_shape"); + const auto value_begin = begin + key.size(); + const auto value_end = json.find('"', value_begin); + if (value_end == std::string::npos) Fail("fixture_policy_shape"); + json.replace(value_begin, value_end - value_begin, Hex(digest)); + return json; +} +std::shared_ptr LoadPolicy( + const std::string& fixture_json, const sec::Sha256Digest& root_digest) { + auto parsed = pol::PolicyLoader::Load(BindPolicyRoot(fixture_json, root_digest)); + if (!std::holds_alternative>(parsed)) + Fail("fixture_policy_invalid"); + return std::get>(std::move(parsed)); +} +sec::PeerRole ToPeerRole(pol::PrincipalRole role) { + switch (role) { + case pol::PrincipalRole::Adapter: return sec::PeerRole::kAdapter; + case pol::PrincipalRole::Replica: return sec::PeerRole::kReplica; + case pol::PrincipalRole::Authority: return sec::PeerRole::kAuthority; + } + Fail("fixture_role"); +} +std::vector IssueAll(EphemeralPki& pki, + const pol::PolicySnapshot& policy) { + std::vector pems; + for (const auto& principal : policy.principals()) + pems.push_back(pki.Issue(ToPeerRole(principal.role), principal.uri).certificate_pem); + return pems; +} +std::vector Views(const std::vector& pems) { + std::vector result; + result.reserve(pems.size()); + for (const auto& pem : pems) result.emplace_back(pem); + return result; +} +using LoadResult = sec::CertificateRegistryResult>; +LoadResult Load(std::shared_ptr policy, + const std::string& root, const std::vector& leafs, + FixedClock& clock) { + const auto views = Views(leafs); + return sec::CertificateRegistryLoader::Load(std::move(policy), root, views, clock); +} +void ExpectError(const LoadResult& result, sec::CertificateRegistryErrorCode code, + std::string_view label) { + Check(std::holds_alternative(result), label); + Check(std::get(result).code == code, label); +} +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) Fail("usage_registry_fixture_json"); + const std::string policy_json = ReadFile(argv[1]); + const auto now_sec = static_cast(std::chrono::duration_cast< + std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count()); + FixedClock clock({now_sec, 0}); + EphemeralPki pki; + const auto root_digest = DerDigest(pki.root_certificate_pem()); + auto policy = LoadPolicy(policy_json, root_digest); + auto leaves = IssueAll(pki, *policy); + std::map> expected_leaf_digests; + Check(leaves.size() == policy->principals().size(), "fixture_leaf_count"); + for (std::size_t i = 0; i < leaves.size(); ++i) + expected_leaf_digests.emplace(policy->principals()[i].uri, DerDigest(leaves[i])); + + // Positive oracle: exact principal set, URI, role and independently computed + // SHA-256(DER) pins; reversed input order must not change lookup results. + std::reverse(leaves.begin(), leaves.end()); + auto loaded = Load(policy, pki.root_certificate_pem(), leaves, clock); + Check(std::holds_alternative>(loaded), "valid_registry"); + const auto registry = std::get>(loaded); + Check(registry->peers().size() == policy->principals().size(), "principal_count"); + Check(registry->epoch_id() == policy->epoch_id(), "epoch_binding"); + Check(registry->authority_incarnation() == policy->authority_incarnation(), "authority_binding"); + Check(registry->policy_digest() == std::get(pol::CanonicalPolicyCodec::Digest(*policy)), "policy_digest_binding"); + Check(registry->root_der_sha256() == root_digest, "root_der_digest"); + Check(registry->validated_at() == sec::WallTime{now_sec, 0}, "trusted_validation_time"); + Check(registry->AllValidAt({now_sec, 0}), "validity_inclusive_start"); + for (const auto& principal : policy->principals()) { + const auto* registered = registry->Find(principal.uri); + Check(registered != nullptr, "principal_lookup"); + Check(registered->peer.role == ToPeerRole(principal.role), "principal_role"); + Check(registered->peer.leaf_der_sha256 == expected_leaf_digests.at(principal.uri), + "leaf_der_pin"); + } + auto pins = registry->peer_pins(); + Check(pins && pins->valid(), "peer_pin_registry_valid"); + for (const auto& principal : policy->principals()) { + const auto* pin = pins->Find(principal.uri); + Check(pin && pin->role == ToPeerRole(principal.role), "peer_pin_identity"); + Check(pin->leaf_der_sha256 == registry->Find(principal.uri)->peer.leaf_der_sha256, + "peer_pin_digest"); + } + Check(registry->Find("spiffe://rateguard.local/adapter/not-registered") == nullptr, + "unknown_lookup_is_read_only"); + Check(registry->peers().size() == policy->principals().size(), + "unknown_lookup_did_not_insert"); + Check(std::is_sorted(registry->peers().begin(), registry->peers().end(), + [](const auto& a, const auto& b) { return a.peer.uri < b.peer.uri; }), + "registry_metadata_sorted"); + + // The snapshot must own only immutable metadata; it must remain usable after + // the caller drops all policy/PEM/PKI owners used for construction. + std::shared_ptr retained; + { + EphemeralPki short_lived_pki; + const auto short_lived_root_digest = DerDigest(short_lived_pki.root_certificate_pem()); + auto short_lived_policy = LoadPolicy(policy_json, short_lived_root_digest); + auto short_lived_leaves = IssueAll(short_lived_pki, *short_lived_policy); + FixedClock short_lived_clock({now_sec, 0}); + auto short_lived_result = Load(short_lived_policy, + short_lived_pki.root_certificate_pem(), short_lived_leaves, short_lived_clock); + Check(std::holds_alternative>( + short_lived_result), "owned_snapshot_setup"); + retained = std::get>( + std::move(short_lived_result)); + short_lived_policy.reset(); + } + Check(retained->epoch_id() == policy->epoch_id(), "snapshot_survives_input_lifetimes"); + Check(retained->Find("spiffe://rateguard.local/adapter/ingress1") != nullptr, + "retained_snapshot_lookup"); + Check(retained->peer_pins() && retained->peer_pins()->valid(), + "retained_snapshot_peer_pins"); + + // Root digest binds the actual DER root to the immutable policy. + auto wrong_root_hash_json = policy_json; + const auto marker = wrong_root_hash_json.find("\"trust_root_sha256\": \""); + Check(marker != std::string::npos, "fixture_root_key"); + const auto hash_begin = marker + std::string_view("\"trust_root_sha256\": \"").size(); + wrong_root_hash_json.replace(hash_begin, 64, 64, '0'); + auto wrong_hash_policy_result = pol::PolicyLoader::Load(wrong_root_hash_json); + Check(std::holds_alternative>(wrong_hash_policy_result), + "wrong_hash_policy_parses"); + const auto wrong_hash_policy = std::get>(wrong_hash_policy_result); + auto wrong_root_hash = Load(wrong_hash_policy, pki.root_certificate_pem(), leaves, clock); + ExpectError(wrong_root_hash, sec::CertificateRegistryErrorCode::RootFingerprintMismatch, + "wrong_root_digest_rejected"); + + // Exact set semantics and principal-to-certificate binding. + auto missing = leaves; + missing.pop_back(); + ExpectError(Load(policy, pki.root_certificate_pem(), missing, clock), + sec::CertificateRegistryErrorCode::LeafCountMismatch, "missing_leaf_rejected"); + auto duplicated = leaves; + duplicated.back() = duplicated.front(); + ExpectError(Load(policy, pki.root_certificate_pem(), duplicated, clock), + sec::CertificateRegistryErrorCode::DuplicateLeaf, "duplicate_leaf_rejected"); + auto unknown_pki = pki.Issue(sec::PeerRole::kAdapter, + "spiffe://rateguard.local/adapter/unknown"); + auto unknown = leaves; + unknown.back() = unknown_pki.certificate_pem; + ExpectError(Load(policy, pki.root_certificate_pem(), unknown, clock), + sec::CertificateRegistryErrorCode::UnknownPrincipal, "unknown_principal_rejected"); + auto key_material = pki.Issue(sec::PeerRole::kAdapter, + "spiffe://rateguard.local/adapter/private-material-control"); + auto certificate_plus_key = leaves; + certificate_plus_key.back() = key_material.certificate_pem + key_material.private_key_pem; + ExpectError(Load(policy, pki.root_certificate_pem(), certificate_plus_key, clock), + sec::CertificateRegistryErrorCode::InvalidPem, + "private_key_material_rejected_from_leaf_input"); + auto two_cert_root = pki.root_certificate_pem() + pki.root_certificate_pem(); + ExpectError(Load(policy, two_cert_root, leaves, clock), + sec::CertificateRegistryErrorCode::InvalidPem, + "multiple_root_certificates_rejected"); + auto two_cert_leafs = leaves; + two_cert_leafs.front() += pki.root_certificate_pem(); + ExpectError(Load(policy, pki.root_certificate_pem(), two_cert_leafs, clock), + sec::CertificateRegistryErrorCode::InvalidPem, + "multiple_leaf_certificates_rejected"); + + const auto adapter = std::find_if(policy->principals().begin(), policy->principals().end(), + [](const pol::Principal& p) { return p.role == pol::PrincipalRole::Adapter; }); + Check(adapter != policy->principals().end(), "fixture_adapter"); + const auto adapter_index = static_cast(std::distance(policy->principals().begin(), adapter)); + + EphemeralPki foreign_pki; + const auto foreign_adapter = foreign_pki.Issue(sec::PeerRole::kAdapter, adapter->uri); + auto wrong_chain_leafs = leaves; + wrong_chain_leafs[leaves.size() - 1 - adapter_index] = + foreign_adapter.certificate_pem; + ExpectError(Load(policy, pki.root_certificate_pem(), wrong_chain_leafs, clock), + sec::CertificateRegistryErrorCode::InvalidChain, + "foreign_direct_issuer_rejected"); + + // Create role/SAN/validity variants for this exact registered principal. + auto wrong_role = pki.Issue(sec::PeerRole::kAuthority, adapter->uri); + auto role_leafs = leaves; + // Locate the correct adapter PEM by SAN binding via the helper's registry metadata. + for (std::size_t i = 0; i < leaves.size(); ++i) { + // We know the helper initially issued leaves in policy order, then reversed them. + const auto original_index = leaves.size() - 1 - i; + if (original_index == adapter_index) role_leafs[i] = wrong_role.certificate_pem; + } + ExpectError(Load(policy, pki.root_certificate_pem(), role_leafs, clock), + sec::CertificateRegistryErrorCode::InvalidLeafProfile, "wrong_role_eku_rejected"); + auto multi_uri = pki.IssueWithUriSans(sec::PeerRole::kAdapter, + {adapter->uri, "spiffe://rateguard.local/adapter/extra"}); + auto multi_leafs = leaves; + const auto reversed_adapter_index = leaves.size() - 1 - adapter_index; + multi_leafs[reversed_adapter_index] = multi_uri.certificate_pem; + ExpectError(Load(policy, pki.root_certificate_pem(), multi_leafs, clock), + sec::CertificateRegistryErrorCode::IdentityMismatch, "multiple_uri_sans_rejected"); + + auto expired = pki.IssueWithValidity(sec::PeerRole::kAdapter, adapter->uri, -7200, -3600); + auto expired_leafs = leaves; + expired_leafs[reversed_adapter_index] = expired.certificate_pem; + ExpectError(Load(policy, pki.root_certificate_pem(), expired_leafs, clock), + sec::CertificateRegistryErrorCode::CertificateExpired, "expired_leaf_rejected"); + auto future = pki.IssueWithValidity(sec::PeerRole::kAdapter, adapter->uri, 3600, 7200); + auto future_leafs = leaves; + future_leafs[reversed_adapter_index] = future.certificate_pem; + ExpectError(Load(policy, pki.root_certificate_pem(), future_leafs, clock), + sec::CertificateRegistryErrorCode::CertificateNotYetValid, "future_leaf_rejected"); + + // Fractional trusted-now comparisons are tested on both half-open edges. + // The ASN.1 validity fields are second precision; the injected trusted clock + // carries nanoseconds and is independently positioned around those fields. + auto start_edge = pki.IssueWithValidity(sec::PeerRole::kAdapter, adapter->uri, -1, 3600); + auto start_edge_leafs = leaves; + start_edge_leafs[reversed_adapter_index] = start_edge.certificate_pem; + const auto not_before = CertTime(start_edge.certificate_pem, false); + clock.Set({not_before.unix_seconds, 0}); + Check(std::holds_alternative>( + Load(policy, pki.root_certificate_pem(), start_edge_leafs, clock)), + "not_before_exact_accepted"); + clock.Set({not_before.unix_seconds - 1, 999'999'999U}); + ExpectError(Load(policy, pki.root_certificate_pem(), start_edge_leafs, clock), + sec::CertificateRegistryErrorCode::CertificateNotYetValid, + "not_before_minus_one_ns_rejected"); + clock.Set({not_before.unix_seconds, 1}); + Check(std::holds_alternative>( + Load(policy, pki.root_certificate_pem(), start_edge_leafs, clock)), + "not_before_plus_one_ns_accepted"); + + auto end_edge = pki.IssueWithValidity(sec::PeerRole::kAdapter, adapter->uri, -7200, -1); + auto end_edge_leafs = leaves; + end_edge_leafs[reversed_adapter_index] = end_edge.certificate_pem; + const auto not_after = CertTime(end_edge.certificate_pem, true); + clock.Set({not_after.unix_seconds - 1, 999'999'999U}); + Check(std::holds_alternative>( + Load(policy, pki.root_certificate_pem(), end_edge_leafs, clock)), + "not_after_minus_one_ns_accepted"); + clock.Set({not_after.unix_seconds, 0}); + ExpectError(Load(policy, pki.root_certificate_pem(), end_edge_leafs, clock), + sec::CertificateRegistryErrorCode::CertificateExpired, + "not_after_exact_rejected"); + clock.Set({not_after.unix_seconds, 1}); + ExpectError(Load(policy, pki.root_certificate_pem(), end_edge_leafs, clock), + sec::CertificateRegistryErrorCode::CertificateExpired, + "not_after_plus_one_ns_rejected"); + + clock.Fail(); + ExpectError(Load(policy, pki.root_certificate_pem(), leaves, clock), + sec::CertificateRegistryErrorCode::ClockUntrusted, "untrusted_clock_rejected"); + + // Enforce byte caps before unbounded parsing and avoid emitting input data. + clock = FixedClock({now_sec, 0}); + auto oversized = leaves; + oversized.front().append(sec::CertificateRegistry::kMaxCertificatePemBytes + 1, + ' '); + ExpectError(Load(policy, pki.root_certificate_pem(), oversized, clock), + sec::CertificateRegistryErrorCode::ResourceLimit, "per_certificate_limit"); + + // The byte bound is inclusive. Surrounding ASCII whitespace is part of the + // input byte count but is permitted by the PEM grammar. + auto exact_leaf_cap = leaves; + exact_leaf_cap.front().append( + sec::CertificateRegistry::kMaxCertificatePemBytes - exact_leaf_cap.front().size(), ' '); + auto exact_leaf_result = Load(policy, pki.root_certificate_pem(), exact_leaf_cap, clock); + Check(std::holds_alternative>( + exact_leaf_result), "exact_per_certificate_cap_accepted"); + std::string exact_root_cap = pki.root_certificate_pem(); + exact_root_cap.append(sec::CertificateRegistry::kMaxCertificatePemBytes - + exact_root_cap.size(), ' '); + auto exact_root_result = Load(policy, exact_root_cap, leaves, clock); + Check(std::holds_alternative>( + exact_root_result), "exact_root_certificate_cap_accepted"); + auto oversized_root = exact_root_cap; + oversized_root.push_back(' '); + ExpectError(Load(policy, oversized_root, leaves, clock), + sec::CertificateRegistryErrorCode::ResourceLimit, + "root_certificate_limit_plus_one"); + + // Exercise aggregate-byte arithmetic before parsing/count validation using + // repeated views into one bounded valid PEM buffer. Exactly 64 MiB proceeds + // to the independently expected count error; one additional byte is capped. + const std::size_t aggregate_cap = sec::CertificateRegistry::kMaxAggregatePemBytes; + const std::size_t repeated_count = 1023; + std::string repeated_pem = leaves.front(); + repeated_pem.append(sec::CertificateRegistry::kMaxCertificatePemBytes - + repeated_pem.size(), ' '); + std::vector aggregate_views(repeated_count, repeated_pem); + const std::size_t root_size = pki.root_certificate_pem().size(); + const std::size_t last_size = aggregate_cap - root_size - + repeated_count * sec::CertificateRegistry::kMaxCertificatePemBytes; + Check(last_size <= sec::CertificateRegistry::kMaxCertificatePemBytes, + "aggregate_fixture_arithmetic"); + aggregate_views.emplace_back(repeated_pem.data(), last_size); + auto exact_aggregate = sec::CertificateRegistryLoader::Load( + policy, pki.root_certificate_pem(), aggregate_views, clock); + ExpectError(exact_aggregate, sec::CertificateRegistryErrorCode::LeafCountMismatch, + "exact_aggregate_cap_not_resource_limited"); + aggregate_views.back() = std::string_view(repeated_pem.data(), last_size + 1); + auto over_aggregate = sec::CertificateRegistryLoader::Load( + policy, pki.root_certificate_pem(), aggregate_views, clock); + ExpectError(over_aggregate, sec::CertificateRegistryErrorCode::ResourceLimit, + "aggregate_cap_plus_one_rejected"); + + std::vector principal_overflow( + sec::CertificateRegistry::kMaxPrincipalCount + 1, "x"); + ExpectError(sec::CertificateRegistryLoader::Load( + policy, pki.root_certificate_pem(), principal_overflow, clock), + sec::CertificateRegistryErrorCode::ResourceLimit, + "principal_count_cap_plus_one_rejected"); + + std::cout << "PASS registry_valid_binding_negative_identity_eku_time_caps" << '\n'; + return 0; +} diff --git a/tools/tests/clock_independent_test.cpp b/tools/tests/clock_independent_test.cpp new file mode 100644 index 0000000..7181a73 --- /dev/null +++ b/tools/tests/clock_independent_test.cpp @@ -0,0 +1,184 @@ +#include "platform/clock_linux.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::platform; +namespace detail = rateguard::platform::detail; + +namespace { +int failures = 0; +void Expect(bool value, const char* label) { + if (!value) { std::cerr << "FAIL: " << label << '\n'; ++failures; } +} +ClockFailure Error(ClockFailureReason reason) { + using namespace rateguard::v1::contract; + return {{ErrorCategory::Internal, ErrorCode::Internal, RetryDisposition::Never, + Commitment::NotCommitted}, reason}; +} +const std::string boot = "01234567-89ab-cdef-0123-456789abcdef\n"; +const std::string offsets = "monotonic 0 0\nboottime 0 0\n"; +const ClockIdentity expected{{0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef, + 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}, + 9, 31, 0, 0, 0, 0, 1}; + +class Platform final : public IClockPlatform { + public: + bool leader = true; + std::string boot_bytes = boot; + std::string offset_bytes = offsets; + std::int32_t clock_id = 1; + std::deque namespaces{{9,31},{9,31},{9,31},{9,31}}; + std::deque> samples; + unsigned reads = 0; + ClockResult IsProcessLeader() override { return leader; } + ClockResult ReadBootUuidFile() override { return boot_bytes; } + ClockResult StatTimeNamespace(bool) override { + if (namespaces.empty()) return Error(ClockFailureReason::NamespaceStat); + auto v = namespaces.front(); namespaces.pop_front(); return v; + } + ClockResult ReadTimeOffsetsFile() override { return offset_bytes; } + ClockResult MonotonicClockId() override { return clock_id; } + ClockResult ReadMonotonic() override { + ++reads; + if (samples.empty()) return ClockReading{0,0}; + auto v = std::move(samples.front()); samples.pop_front(); return v; + } +}; +auto Create(std::unique_ptr p, ClockIdentity identity = expected) { + return LinuxMonotonicClock::Create(identity, std::unique_ptr(std::move(p))); +} +bool IsError(const auto& value, ClockFailureReason reason) { + auto* f = std::get_if(&value); return f && f->reason == reason; +} + +void ParserCases() { + Expect(std::holds_alternative>(detail::ParseBootUuid(boot)), "valid UUID"); + for (const std::string s : {"01234567-89AB-cdef-0123-456789abcdef", " 01234567-89ab-cdef-0123-456789abcdef", "01234567-89ab-cdef-0123-456789abcdef\n\n"}) + Expect(IsError(detail::ParseBootUuid(s), ClockFailureReason::MalformedBootUuid), "strict UUID grammar"); + Expect(IsError(detail::ParseBootUuid(std::string(65,'0')), ClockFailureReason::InputTooLong), "UUID bound"); + const auto max_off = detail::ParseTimeOffsets("monotonic -9223372036854775808 999999999\t\nboottime 9223372036854775807 0"); + Expect(std::holds_alternative(max_off), "int64 offset endpoints and whitespace"); + const std::array bad{{ + "monotonic +1 0\nboottime 0 0", "monotonic -0 0\nboottime 0 0", + "monotonic 01 0\nboottime 0 0", "monotonic 0 00\nboottime 0 0", + "monotonic 0 1000000000\nboottime 0 0", "monotonic 0 4294967296\nboottime 0 0", + "monotonic 9223372036854775808 0\nboottime 0 0", "monotonic 0 0\r\nboottime 0 0", + "monotonic 0 0\n\nboottime 0 0", "monotonic 0 0\nmonotonic 1 0", + "monotonic 0 0\nboottime 0 0 extra", "monotonic 0 0\nunknown 0 0", + std::string("monotonic 0 0\nboottime 0 0").append(1, '\0')}}; + for (const auto& s : bad) Expect(std::holds_alternative(detail::ParseTimeOffsets(s)), "malformed offset input rejected"); + Expect(IsError(detail::ParseTimeOffsets(std::string(513,'x')), ClockFailureReason::InputTooLong), "offset bound"); + char temp_path[] = "/tmp/rateguard-clock-XXXXXX"; + const int temp_fd = ::mkstemp(temp_path); + Expect(temp_fd >= 0, "unique temporary file created"); + if (temp_fd < 0) return; + auto set_bytes = [temp_fd](const std::string& bytes) { + if (::ftruncate(temp_fd, 0) != 0 || ::lseek(temp_fd, 0, SEEK_SET) < 0) return false; + std::size_t offset = 0; + while (offset < bytes.size()) { + const auto n = ::write(temp_fd, bytes.data() + offset, bytes.size() - offset); + if (n <= 0) return false; + offset += static_cast(n); + } + return ::lseek(temp_fd, 0, SEEK_SET) == 0; + }; + Expect(set_bytes(""), "empty bounded-reader fixture created"); + const auto empty_file = detail::ReadBoundedFd(temp_fd, 0); + Expect(std::get_if(&empty_file) && std::get(empty_file).empty(), + "zero-byte bound accepts empty input"); + Expect(set_bytes("x"), "one-byte bounded-reader fixture created"); + Expect(IsError(detail::ReadBoundedFd(temp_fd,0),ClockFailureReason::InputTooLong), + "zero-byte bound detects one byte over"); + Expect(set_bytes(std::string(64, 'x')), "exact-limit bounded-reader fixture created"); + const auto exact_file = detail::ReadBoundedFd(temp_fd,64); + Expect(std::get_if(&exact_file) != nullptr, "bounded reader accepts exact limit"); + Expect(set_bytes(std::string(65, 'x')), "over-limit bounded-reader fixture created"); + Expect(IsError(detail::ReadBoundedFd(temp_fd,64),ClockFailureReason::InputTooLong), + "bounded reader detects one byte over limit"); + Expect(IsError(detail::ReadBoundedFd(temp_fd,513),ClockFailureReason::InputTooLong), + "maximum bound itself is capped"); + Expect(IsError(detail::ReadBoundedFd(-1,0),ClockFailureReason::PlatformRead), + "negative descriptor is a platform read failure"); + Expect(::fcntl(temp_fd, F_GETFD) >= 0, "bounded reader leaves caller-owned fd open"); + ::close(temp_fd); + Expect(IsError(detail::ReadBoundedFd(temp_fd,0),ClockFailureReason::PlatformRead), + "closed descriptor read is surfaced as platform failure"); + ::unlink(temp_path); +} + +void IdentityCases() { + auto p = std::make_unique(); + auto ok = Create(std::move(p)); + Expect(std::holds_alternative>(ok), "matching manifest identity starts"); + for (int field=0; field<8; ++field) { + auto e=expected; + switch(field) { + case 0:e.boot_uuid[15]^=1;break; case 1:e.namespace_device++;break; case 2:e.namespace_inode++;break; + case 3:e.monotonic_offset_seconds++;break; case 4:e.monotonic_offset_nanoseconds++;break; + case 5:e.boottime_offset_seconds++;break; case 6:e.boottime_offset_nanoseconds++;break; default:e.clock_id=2; + } + Expect(IsError(Create(std::make_unique(),e), ClockFailureReason::ExpectedIdentityMismatch), "all manifest identity fields compared"); + } + auto wrong_clock=std::make_unique(); wrong_clock->clock_id=99; + auto wrong_expected=expected; wrong_expected.clock_id=99; + Expect(IsError(Create(std::move(wrong_clock),wrong_expected),ClockFailureReason::ExpectedIdentityMismatch), + "factory rejects non-Linux CLOCK_MONOTONIC id even if manifest matches"); + auto p1=std::make_unique(); p1->leader=false; + Expect(IsError(Create(std::move(p1)),ClockFailureReason::NotProcessLeader),"nonleader rejected"); + auto p2=std::make_unique(); p2->namespaces={{9,31},{9,32},{9,31},{9,31}}; + Expect(IsError(Create(std::move(p2)),ClockFailureReason::NamespaceChanged),"current and children namespace split rejected"); + auto p3=std::make_unique(); p3->namespaces={{9,31},{9,31},{9,32},{9,31}}; + Expect(IsError(Create(std::move(p3)),ClockFailureReason::NamespaceChanged),"namespace change during offset snapshot rejected"); + auto regressed_after_start=std::make_unique(); + regressed_after_start->samples={ClockReading{5,0},ClockReading{4,999'999'999}}; + auto started=Create(std::move(regressed_after_start)); + auto& started_clock=**std::get_if>(&started); + Expect(IsError(started_clock.Now(),ClockFailureReason::BackwardsSample), + "successful factory sample is retained as first regression reference"); + auto failed_start=std::make_unique(); + failed_start->samples={Error(ClockFailureReason::ClockSyscall)}; + Expect(IsError(Create(std::move(failed_start)),ClockFailureReason::ClockSyscall), + "factory withholds readiness when initial clock sample fails"); + auto invalid_start=std::make_unique(); + invalid_start->samples={ClockReading{-1,0}}; + Expect(IsError(Create(std::move(invalid_start)),ClockFailureReason::InvalidTimespec), + "factory withholds readiness when initial clock sample is invalid"); +} + +void SampleCases() { + constexpr std::uint64_t max = std::numeric_limits::max(); + constexpr std::int64_t max_seconds = static_cast(max/1'000'000'000ULL); + constexpr std::int64_t max_nanos = static_cast(max%1'000'000'000ULL); + auto p=std::make_unique(); p->samples={ClockReading{0,0},ClockReading{max_seconds,max_nanos}}; + auto created=Create(std::move(p)); auto& c=**std::get_if>(&created); + auto endpoint=c.Now(); Expect(std::get_if(&endpoint)&&std::get(endpoint).value==max,"largest representable nanosecond timestamp accepted"); + + auto p2=std::make_unique(); p2->samples={ClockReading{0,0},ClockReading{max_seconds,max_nanos+1},ClockReading{8,0}}; + auto c2=Create(std::move(p2)); auto& clock=**std::get_if>(&c2); + Expect(IsError(clock.Now(),ClockFailureReason::NanosecondOverflow),"one beyond uint64 nanoseconds rejected"); + Expect(!clock.Healthy(),"overflow latches unhealthy"); + Expect(IsError(clock.Now(),ClockFailureReason::NanosecondOverflow),"failure remains sticky"); + + auto p3=std::make_unique(); p3->samples={ClockReading{9,0},ClockReading{10,0},ClockReading{9,999'999'999},ClockReading{11,0}}; + auto c3=Create(std::move(p3)); auto& clock3=**std::get_if>(&c3); + Expect(std::holds_alternative(clock3.Now()),"first sample succeeds"); + Expect(IsError(clock3.Now(),ClockFailureReason::BackwardsSample),"backward sample rejected, never clamped"); + Expect(IsError(clock3.Provenance(),ClockFailureReason::BackwardsSample),"provenance reports latched error"); + auto p4=std::make_unique(); p4->samples={ClockReading{0,0},ClockReading{1,0},ClockReading{1,0}}; + auto c4=Create(std::move(p4)); auto& clock4=**std::get_if>(&c4); + Expect(std::holds_alternative(clock4.Now())&&std::holds_alternative(clock4.Now()),"equal readings are legal"); +} +} +int main() { ParserCases(); IdentityCases(); SampleCases(); if(failures) return EXIT_FAILURE; std::cout<<"independent RG003 checks passed\n"; return EXIT_SUCCESS; } diff --git a/tools/tests/clock_mutation_test.py b/tools/tests/clock_mutation_test.py new file mode 100644 index 0000000..a2550c0 --- /dev/null +++ b/tools/tests/clock_mutation_test.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Prove the independent clock suite rejects a backward-time clamp mutant. + +Set RG003_SOURCE_ROOT to the directory containing platform/clock_linux.cpp +(normally /src), and RG003_INCLUDE_ROOT to the directory containing +rateguard/v1/error_contract.h (normally /include). CXX may select the +compiler; default is c++ so CI uses its recorded toolchain. +""" +from __future__ import annotations + +import os +from pathlib import Path +import subprocess +import tempfile + + +GUARD = " if (last_sample_ && sample.value < last_sample_->value)\n return Latch(ClockFailureReason::BackwardsSample);\n" +CLAMP = " if (last_sample_ && sample.value < last_sample_->value)\n return *last_sample_;\n" +EXPECTED_FAILURES = ( + "FAIL: backward sample rejected, never clamped", + "FAIL: provenance reports latched error", + "FAIL: successful factory sample is retained as first regression reference", +) + + +def main() -> int: + source_root = Path(os.environ["RG003_SOURCE_ROOT"]).resolve() + include_root = Path(os.environ["RG003_INCLUDE_ROOT"]).resolve() + production = source_root / "platform" / "clock_linux.cpp" + test_source = Path(__file__).with_name("clock_independent_test.cpp") + if not production.is_file() or not test_source.is_file(): + raise SystemExit("required RG003 production/test source is missing") + original = production.read_text() + if original.count(GUARD) != 1: + raise SystemExit("backward-sample guard anchor is missing or ambiguous") + + with tempfile.TemporaryDirectory(prefix="rateguard-clock-mutant-") as work: + work_path = Path(work) + mutant = work_path / "clock_linux_clamp_mutant.cpp" + mutant.write_text(original.replace(GUARD, CLAMP, 1)) + executable = work_path / "clock_mutant_test" + compiler = os.environ.get("CXX", "c++") + compile_cmd = [ + compiler, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-pedantic", + "-pthread", "-I", str(source_root), "-I", str(include_root), + str(test_source), str(mutant), "-o", str(executable), + ] + built = subprocess.run(compile_cmd, text=True, capture_output=True, timeout=90) + if built.returncode != 0: + raise SystemExit("mutant compile failed:\n" + built.stdout + built.stderr) + result = subprocess.run([str(executable)], text=True, capture_output=True, timeout=30) + if result.returncode == 0: + raise SystemExit("independent suite failed to detect clamp mutant") + missing = [line for line in EXPECTED_FAILURES if line not in result.stderr] + if missing: + raise SystemExit("mutant failed for unexpected reason; missing: " + repr(missing) + + "\nstderr:\n" + result.stderr) + print("independent clock suite rejected backward-time clamp mutant") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/tests/generate_b2_mutants.py b/tools/tests/generate_b2_mutants.py new file mode 100644 index 0000000..6165541 --- /dev/null +++ b/tools/tests/generate_b2_mutants.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Create isolated RG004-B2 unsafe variants for CI mutation checks. + +The inputs are production source files. Outputs are test-only source copies and +must never be compiled into the normal library or shipped. +""" +from __future__ import annotations + +import argparse +from pathlib import Path + + +PAIR_GUARDS = ( + """ if (!snapshot.IsAuthorized(peer.uri(), principal->role, + request.tenant_id(), request.operation_id())) + return Denied(Reason::UnauthorizedPair);""", +) +PIN_GUARD = """ if (presented_digest != registered->peer.leaf_der_sha256) { + return Failure(PeerAuthFailureReason::LeafPinMismatch, + PeerAuthDisposition::Unauthenticated); + }""" + + +def replace_exact(source: str, anchor: str, replacement: str, count: int) -> str: + found = source.count(anchor) + if found != count: + raise ValueError(f"mutation anchor count {found}; expected {count}") + return source.replace(anchor, replacement) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--resolver-src", type=Path, required=True) + parser.add_argument("--auth-src", type=Path, required=True) + parser.add_argument("--out-dir", type=Path, required=True) + args = parser.parse_args() + resolver = args.resolver_src.read_text(encoding="utf-8") + auth = args.auth_src.read_text(encoding="utf-8") + args.out_dir.mkdir(parents=True, exist_ok=True) + pair_mutant = resolver + for anchor in PAIR_GUARDS: + pair_mutant = replace_exact( + pair_mutant, anchor, " // MUTATION: permission guard omitted", 1) + pin_mutant = replace_exact(auth, PIN_GUARD, " // MUTATION: certificate pin comparison omitted", 1) + (args.out_dir / "authorization_resolver_pair_mutant.cpp").write_text( + pair_mutant, encoding="utf-8") + (args.out_dir / "peer_authenticator_pin_mutant.cpp").write_text( + pin_mutant, encoding="utf-8") + print("generated isolated pair and pin mutants") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/tests/generate_client_preflight_mutant.py b/tools/tests/generate_client_preflight_mutant.py new file mode 100644 index 0000000..8f03b1d --- /dev/null +++ b/tools/tests/generate_client_preflight_mutant.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Generate one test-only preflight bypass without changing normal targets.""" +from pathlib import Path +import argparse + +def main(): + p = argparse.ArgumentParser() + p.add_argument('--source', required=True, type=Path) + p.add_argument('--output', required=True, type=Path) + a = p.parse_args() + source = a.source.read_text() + marker = 'ClientCallGuard::ValidateBeforeCall() const {' + if source.count(marker) != 1: + raise SystemExit('expected one pre-call method') + begin = source.index(marker) + end = source.index('\nstd::variant time_result{WallTime{0, 0}};' + ' // TEST-ONLY MUTANT: skip current certificate/time validation.', 1) + a.output.parent.mkdir(parents=True, exist_ok=True) + a.output.write_text(source[:begin] + body + source[end:]) + print('generated isolated preflight bypass mutant') + +if __name__ == '__main__': + main() diff --git a/tools/tests/generate_mtls_verifier_bypass_mutant.py b/tools/tests/generate_mtls_verifier_bypass_mutant.py new file mode 100644 index 0000000..641aa19 --- /dev/null +++ b/tools/tests/generate_mtls_verifier_bypass_mutant.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Generate a test-only custom-verifier bypass while retaining TLS chain checks.""" +from __future__ import annotations + +import argparse +from pathlib import Path + + +START = "bool PinnedPeerVerifier::Verify(" +END = "\n\n} // namespace rateguard::security" +MUTANT = '''bool PinnedPeerVerifier::Verify( + grpc::experimental::TlsCustomVerificationCheckRequest* request, + std::function callback, grpc::Status* sync_status) { + (void)request; + (void)callback; + if (sync_status != nullptr) *sync_status = grpc::Status::OK; + return true; +}''' + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--source", required=True, type=Path, + help="production tls_certificate_verifier.cpp") + parser.add_argument("--output", required=True, type=Path, + help="temporary test-only mutant source") + args = parser.parse_args() + source = args.source.read_text() + if source.count(START) != 1 or source.count(END) != 1: + raise SystemExit("verifier mutation anchors missing or ambiguous") + begin = source.index(START) + end = source.index(END, begin) + if end <= begin: + raise SystemExit("verifier mutation anchors are out of order") + original_function = source[begin:end].rstrip() + if "return true;" not in original_function or "*sync_status = grpc::Status::OK;" not in original_function: + raise SystemExit("source verifier function does not match the reviewed implementation") + mutant = source[:begin] + MUTANT + source[end:] + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(mutant) + print("generated test-only accept-all custom verifier; normal TLS chain checks remain configured") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/tests/generate_wrong_root_pin_mutant.py b/tools/tests/generate_wrong_root_pin_mutant.py new file mode 100644 index 0000000..2abaaf3 --- /dev/null +++ b/tools/tests/generate_wrong_root_pin_mutant.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Create a test-only mutant that skips only the certificate root-pin check.""" +from __future__ import annotations + +import argparse +from pathlib import Path + +ANCHOR = """ if (root_digest != snapshot->trust_root_sha256()) + return Error{ErrorCode::RootFingerprintMismatch};""" +REPLACEMENT = """ // TEST-ONLY MUTANT: deliberately bypass the policy root fingerprint guard. + // The remaining profile, chain, principal, EKU, validity and size checks stay active.""" + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--source", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + source = args.source.read_text(encoding="utf-8") + if source.count(ANCHOR) != 1: + raise SystemExit("expected exactly one root-fingerprint guard anchor") + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(source.replace(ANCHOR, REPLACEMENT, 1), encoding="utf-8") + print("generated test-only root-pin bypass mutant") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/tests/history_inspector_integration.py b/tools/tests/history_inspector_integration.py new file mode 100644 index 0000000..2fafccc --- /dev/null +++ b/tools/tests/history_inspector_integration.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +"""Independent end-to-end fixture for the offline history inspector.""" + +import json +import pathlib +import struct +import subprocess +import sys +import tempfile + +MASK64 = (1 << 64) - 1 +FNV_OFFSET = 14695981039346656037 +FNV_PRIME = 1099511628211 + + +def u8(value): + return struct.pack(">B", value) + + +def u32(value): + return struct.pack(">I", value) + + +def u64(value): + return struct.pack(">Q", value) + + +def fnv(data): + value = FNV_OFFSET + for byte in data: + value ^= byte + value = (value * FNV_PRIME) & MASK64 + return value + + +def make_history(): + epoch = bytes.fromhex("00112233445566778899aabbccddeeff") + policy_digest = bytes.fromhex( + "00112233445566778899aabbccddeeff" + "00112233445566778899aabbccddeeff" + ) + # owner, stage, outcome: every strict Release A producer role is represented. + producers = [ + (1, 1, 0), # generator / offered + (2, 2, 1), # authority / strict decision + (3, 3, 1), # replica / response + (4, 4, 1), # adapter / received + (5, 6, 1), # backend / completed + ] + planned_bytes = 80 + 17 + len(producers) * (13 + 51 + 26) + budget_bytes = planned_bytes + producer_rows = [] + for owner, stage, outcome in producers: + attempt_id = bytes([owner]) * 16 + timestamp = owner * 100 + cost = 1 + event = (b"RGEV1" + u8(stage) + u8(outcome) + attempt_id + + u64(timestamp) + u64(cost)) + event_checksum = fnv(event) + slot = { + "status": 2, + "sequence": 1, + "stage": stage, + "outcome": outcome, + "attempt_id": attempt_id, + "timestamp": timestamp, + "cost": cost, + "checksum": event_checksum, + } + seal = (b"RGPS1" + u8(owner) + u32(0) + u64(1) + u64(1) + u64(1) + + u8(1) + u8(0) + u8(slot["status"]) + u64(slot["sequence"]) + + u64(event_checksum)) + producer_rows.append({ + "owner": owner, + "index": 0, + "capacity": 1, + "slot": slot, + "seal_checksum": fnv(seal), + }) + + run_data = (b"RGRN1" + u32(1) + epoch + policy_digest + u32(len(producers)) + + u64(planned_bytes) + u64(budget_bytes)) + for producer in producer_rows: + run_data += (u8(producer["owner"]) + u32(producer["index"]) + + u64(producer["capacity"]) + u64(producer["seal_checksum"])) + run_checksum = fnv(run_data + u8(1)) + + output = bytearray(b"RGHIST01") + output += u32(1) + epoch + policy_digest + u32(len(producers)) + output += u64(planned_bytes) + u64(budget_bytes) + for producer in producer_rows: + slot = producer["slot"] + output += u8(producer["owner"]) + u32(producer["index"]) + output += u64(producer["capacity"]) + output += (u8(slot["status"]) + u64(slot["sequence"]) + u8(slot["stage"]) + + u8(slot["outcome"]) + slot["attempt_id"] + u64(slot["timestamp"]) + + u64(slot["cost"]) + u64(slot["checksum"])) + output += (u8(1) + u8(0) + u64(1) + u64(1) + + u64(producer["seal_checksum"])) + output += u8(1) + u64(planned_bytes) + u64(run_checksum) + + plan = { + "schema_version": 1, + "epoch_id": epoch.hex(), + "policy_digest": policy_digest.hex(), + "budget_bytes": str(budget_bytes), + # Deliberately unsorted: inspector must bind the roster independent of input order. + "producers": [ + {"producer_owner": owner, "producer_index": 0, "event_capacity": "1"} + for owner, _stage, _outcome in reversed(producers) + ], + } + return plan, bytes(output) + + +def invoke(binary, plan_path, history_path): + result = subprocess.run( + [str(binary), str(plan_path), str(history_path)], + check=False, + capture_output=True, + text=True, + timeout=10, + ) + if result.stderr: + raise AssertionError(f"unexpected stderr: {result.stderr!r}") + try: + payload = json.loads(result.stdout) + except json.JSONDecodeError as exc: + raise AssertionError(f"non-JSON output: {result.stdout!r}") from exc + return result.returncode, payload + + +def expect_error(binary, plan_path, history_path, expected): + code, payload = invoke(binary, plan_path, history_path) + assert code != 0, (expected, payload) + assert payload["status"] == "error", payload + assert payload["error"] == expected, (expected, payload) + assert payload["safety_verdict"] == "UNKNOWN", payload + + +def main(): + if len(sys.argv) != 2: + raise SystemExit("usage: history_inspector_integration.py INSPECTOR_BINARY") + binary = pathlib.Path(sys.argv[1]).resolve() + assert binary.is_file() and binary.stat().st_mode & 0o111, binary + + plan, good_history = make_history() + with tempfile.TemporaryDirectory(prefix="rateguard-history-inspect-") as tmp: + root = pathlib.Path(tmp) + plan_path = root / "plan.json" + history_path = root / "history.bin" + plan_path.write_text(json.dumps(plan, separators=(",", ":")), encoding="utf-8") + history_path.write_bytes(good_history) + + code, payload = invoke(binary, plan_path, history_path) + assert code == 0, payload + assert payload["status"] == "structurally_complete", payload + assert payload["safety_verdict"] == "UNKNOWN", payload + assert payload["event_count"] == "5", payload + assert payload["history_bytes"] == str(len(good_history)), payload + assert payload["budget_bytes"] == str(plan["budget_bytes"]), payload + + missing_history = root / "missing.bin" + expect_error(binary, plan_path, missing_history, "history_file_unavailable") + + corrupt = bytearray(good_history) + corrupt[-1] ^= 1 + history_path.write_bytes(corrupt) + expect_error(binary, plan_path, history_path, "history_incomplete") + + history_path.write_bytes(good_history[:-1]) + expect_error(binary, plan_path, history_path, "history_size_mismatch") + + history_path.write_bytes(good_history + b"\x00") + expect_error(binary, plan_path, history_path, "history_size_mismatch") + + history_path.write_bytes(good_history) + plan_path.write_text( + '{"schema_version":1,"schema_version":1,' + '"epoch_id":"' + plan["epoch_id"] + '",' + '"policy_digest":"' + plan["policy_digest"] + '",' + '"budget_bytes":"' + plan["budget_bytes"] + '","producers":[]}', + encoding="utf-8", + ) + expect_error(binary, plan_path, history_path, "json_duplicate_key") + + plan_path.write_text(json.dumps({**plan, "unexpected": 1}), encoding="utf-8") + expect_error(binary, plan_path, history_path, "plan_unknown_key") + + float_plan = dict(plan) + float_plan["schema_version"] = 1.0 + plan_path.write_text(json.dumps(float_plan), encoding="utf-8") + expect_error(binary, plan_path, history_path, "json_float") + + plan_path.write_bytes(b"{" + b" " * (1024 * 1024)) + expect_error(binary, plan_path, history_path, "plan_too_large") + + # Each producer extent fits uint64 individually, but their sum does not. + # This guards against unsigned subtraction underflow during accumulation. + overflow_plan = { + "schema_version": 1, + "epoch_id": plan["epoch_id"], + "policy_digest": plan["policy_digest"], + "budget_bytes": str((1 << 30) - 1), + "producers": [ + {"producer_owner": owner, "producer_index": 0, + "event_capacity": "190000000000000000"} + for owner in (1, 2) + ], + } + plan_path.write_text(json.dumps(overflow_plan), encoding="utf-8") + expect_error(binary, plan_path, history_path, "plan_extent_overflow") + + print("history inspector integration cases passed") + + +if __name__ == "__main__": + main() diff --git a/tools/tests/mtls_probe_output_test.py b/tools/tests/mtls_probe_output_test.py new file mode 100644 index 0000000..3afefa5 --- /dev/null +++ b/tools/tests/mtls_probe_output_test.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Black-box acceptance checks for the ephemeral mTLS RPC probe output.""" +from __future__ import annotations + +import re +import json +import subprocess +import sys + + +EXPECTED = { + "valid": ("OK", 1), + "wrong_uri": ("REJECTED", 0), + "same_uri_wrong_leaf_pin": ("REJECTED", 0), + "wrong_eku": ("REJECTED", 0), + "unknown_ca": ("REJECTED", 0), + "missing_client_certificate": ("REJECTED", 0), + "expired_client_leaf": ("REJECTED", 0), + "not_yet_valid_client_leaf": ("REJECTED", 0), + "multiple_uri_sans": ("REJECTED", 0), + "wrong_server_uri": ("REJECTED", 0), + "same_uri_wrong_server_leaf_pin": ("REJECTED", 0), + "unknown_server_ca": ("REJECTED", 0), + "reused_channel_two_rpcs": ("OK", 2), +} +PEM_ARMOR = re.compile(r"-----BEGIN [A-Z0-9 ]{1,80}-----") +PKI_PREFLIGHT = re.compile( + r"PKI_PREFLIGHT_FAIL server_error=(-?[0-9]{1,10}) client_error=(-?[0-9]{1,10})" +) + + +def main() -> int: + if len(sys.argv) != 2: + raise SystemExit("usage: mtls_probe_output_test.py /path/to/mtls_probe_test") + result = subprocess.run([sys.argv[1]], text=True, capture_output=True, timeout=90) + output = result.stdout + result.stderr + if len(output) > 64 * 1024: + raise SystemExit("mTLS probe output exceeded 64 KiB") + if PEM_ARMOR.search(output): + raise SystemExit("mTLS probe output contains PEM-encoded material; child output withheld") + if result.returncode == 3: + match = PKI_PREFLIGHT.fullmatch(result.stderr.strip()) + if match is None or result.stdout: + raise SystemExit("mTLS PKI preflight failed with unexpected output; child output withheld") + server_error, client_error = (int(value) for value in match.groups()) + print(json.dumps({ + "probe_exit_code": 3, + "pki_preflight": {"result": "failed", "server_error": server_error, + "client_error": client_error}, + "scenarios": [], + }, separators=(",", ":"))) + raise SystemExit("mTLS PKI preflight failed; only allowlisted numeric codes were emitted") + observed: dict[str, tuple[str, str, int]] = {} + for line in result.stdout.splitlines(): + match = re.fullmatch(r"([a-z_]+): (PASS|FAIL) rpc=(OK|REJECTED) handler_calls=([0-9]+)", line) + if not match: + raise SystemExit("mTLS probe emitted an unexpected line; child output withheld") + name, assertion, status, calls = match.groups() + if name in observed: + raise SystemExit("mTLS probe emitted a duplicate scenario; child output withheld") + observed[name] = (assertion, status, int(calls)) + summary = { + "probe_exit_code": result.returncode, + "scenarios": [ + {"name": name, "assertion": observed[name][0], + "rpc": observed[name][1], "handler_calls": observed[name][2]} + for name in EXPECTED if name in observed + ], + } + print(json.dumps(summary, separators=(",", ":"))) + correct = {name: ("PASS", status, calls) for name, (status, calls) in EXPECTED.items()} + if result.returncode != 0 or observed != correct: + raise SystemExit("mTLS probe acceptance failed; only allowlisted scenario fields were emitted") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/tests/mtls_verifier_bypass_mutation_test.py b/tools/tests/mtls_verifier_bypass_mutation_test.py new file mode 100644 index 0000000..9300fcf --- /dev/null +++ b/tools/tests/mtls_verifier_bypass_mutation_test.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Require the real mTLS RPC probe to catch a verifier-bypass mutant.""" +from __future__ import annotations + +import re +import subprocess +import sys + + +EXPECTED_REJECTIONS = ( + "wrong_uri: FAIL rpc=OK handler_calls=1", + "same_uri_wrong_leaf_pin: FAIL rpc=OK handler_calls=1", + "wrong_server_uri: FAIL rpc=OK handler_calls=1", + "same_uri_wrong_server_leaf_pin: FAIL rpc=OK handler_calls=1", +) +FORBIDDEN = ( + "-----BEGIN CERTIFICATE-----", + "-----BEGIN PRIVATE KEY-----", + "-----BEGIN EC PRIVATE KEY-----", + "-----BEGIN RSA PRIVATE KEY-----", +) + + +def main() -> int: + if len(sys.argv) != 2: + raise SystemExit("usage: mtls_verifier_bypass_mutation_test.py /path/to/mutant_probe") + result = subprocess.run([sys.argv[1]], text=True, capture_output=True, timeout=90) + output = result.stdout + result.stderr + if result.returncode == 0: + raise SystemExit("mTLS probe did not detect the accept-all verifier mutant") + if len(output) > 64 * 1024: + raise SystemExit("mutant mTLS probe output exceeded 64 KiB") + if any(marker in output for marker in FORBIDDEN): + raise SystemExit("mutant probe output exposed certificate or private-key PEM") + for expected in EXPECTED_REJECTIONS: + if expected not in result.stdout: + raise SystemExit("mutant was not detected by the expected URI/leaf-pin case: " + expected + + "\nstdout:\n" + result.stdout + "\nstderr:\n" + result.stderr) + # Every emitted scenario line must be a C++ probe result, not a compiler or + # verifier diagnostic that happens to contain the expected substring. + for line in result.stdout.splitlines(): + if not re.fullmatch(r"[a-z_]+: (?:PASS|FAIL) rpc=(?:OK|REJECTED) handler_calls=[0-9]+", line): + raise SystemExit("unexpected mutation probe output: " + line) + print("mTLS RPC probe detected accept-all verifier mutant on URI and leaf-pin cases") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/tests/peer_authorization_rpc_test.cpp b/tools/tests/peer_authorization_rpc_test.cpp new file mode 100644 index 0000000..40614fb --- /dev/null +++ b/tools/tests/peer_authorization_rpc_test.cpp @@ -0,0 +1,800 @@ +#include "ephemeral_pki.h" +#include "rateguard/v1/channel_policy.h" + +#include "policy/canonical_codec.h" +#include "policy/policy_loader.h" +#include "proto/rateguard/v1/admission.grpc.pb.h" +#include "proto/rateguard/v1/authority.grpc.pb.h" +#include "rateguard/security/authorization_resolver.h" +#include "rateguard/security/peer_authenticator.h" +#include "rateguard/security/tls_certificate_verifier.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; +namespace rg = rateguard::v1; +using grpc::experimental::IdentityKeyCertPair; +using grpc::experimental::StaticDataCertificateProvider; + +namespace { + +[[noreturn]] void Fail(std::string_view label) { + std::cerr << "FAIL " << label << '\n'; + std::exit(1); +} +void Check(bool condition, std::string_view label) { + if (!condition) Fail(label); +} + +class MutableClock final : public sec::ITrustedWallClock { + public: + explicit MutableClock(sec::WallTime value) : value_(value) {} + sec::TrustedWallClockResult Now() override { + std::lock_guard lock(mutex_); + ++samples_; + if (!healthy_) return sec::TrustedWallClockFailure{ + sec::TrustedWallClockFailureReason::PlatformUnavailable}; + return value_; + } + bool Healthy() const override { + std::lock_guard lock(mutex_); + return healthy_; + } + // This mutable fake permits independent test subcases. It is not the + // production clock's sticky-failure/reset contract and proves no epoch + // recovery, rollback, readiness, or fencing behavior. + void Set(sec::WallTime value) { + std::lock_guard lock(mutex_); + value_ = value; + } + void SetHealthy(bool value) { + std::lock_guard lock(mutex_); + healthy_ = value; + } + private: + mutable std::mutex mutex_; + sec::WallTime value_; + bool healthy_{true}; + std::uint64_t samples_{}; +}; + +class CountingPinnedVerifier final + : public grpc::experimental::ExternalCertificateVerifier { + public: + CountingPinnedVerifier(std::shared_ptr registry, + std::optional expected, + std::shared_ptr> count) + : delegate_(std::move(registry), std::move(expected)), count_(std::move(count)) {} + bool Verify(grpc::experimental::TlsCustomVerificationCheckRequest* request, + std::function callback, + grpc::Status* sync_status) override { + count_->fetch_add(1, std::memory_order_relaxed); + return delegate_.Verify(request, std::move(callback), sync_status); + } + void Cancel(grpc::experimental::TlsCustomVerificationCheckRequest* request) override { + delegate_.Cancel(request); + } + private: + sec::PinnedPeerVerifier delegate_; + std::shared_ptr> count_; +}; + +std::string ReadFile(const std::string& path) { + std::ifstream in(path, std::ios::binary); + if (!in) return {}; + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} +std::string Hex(std::span bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string result; + result.reserve(bytes.size() * 2); + for (const auto byte : bytes) { + result.push_back(digits[byte >> 4]); + result.push_back(digits[byte & 15]); + } + return result; +} +pol::Digest32 RootDigest(std::string_view pem) { + BIO* raw_bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (!raw_bio) Fail("fixture_root_parse"); + std::unique_ptr bio(raw_bio, BIO_free); + X509* raw_cert = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (!raw_cert) Fail("fixture_root_parse"); + std::unique_ptr cert(raw_cert, X509_free); + const int length = i2d_X509(cert.get(), nullptr); + if (length <= 0 || length > 64 * 1024) Fail("fixture_root_der"); + std::vector der(static_cast(length)); + auto* cursor = der.data(); + if (i2d_X509(cert.get(), &cursor) != length) Fail("fixture_root_der"); + pol::Digest32 digest{}; + unsigned int written = 0; + if (EVP_Digest(der.data(), der.size(), digest.data(), &written, + EVP_sha256(), nullptr) != 1 || written != digest.size()) + Fail("fixture_root_hash"); + return digest; +} + +struct Fixture final { + sec::test::EphemeralPki pki; + std::shared_ptr policy; + std::shared_ptr registry; + std::vector identities; + const sec::test::EphemeralIdentity* adapter{}; + const sec::test::EphemeralIdentity* replica{}; + const sec::test::EphemeralIdentity* authority{}; + pol::Digest32 digest{}; + sec::WallTime now{}; + + explicit Fixture(const std::string& fixture_path) { + auto document = nlohmann::json::parse(ReadFile(fixture_path)); + document["trust_root_sha256"] = Hex(RootDigest(pki.root_certificate_pem())); + for (auto& principal : document["principals"]) { + if (principal["role"] == "replica" && principal.value("slot_id", 0U) == 7U) { + principal["permissions"].push_back({{"tenant_id", "zeta"}, + {"operation_id", "list"}}); + } + } + auto loaded = pol::PolicyLoader::Load(document.dump()); + const auto* parsed = std::get_if>(&loaded); + Check(parsed != nullptr, "policy_fixture_loads"); + policy = *parsed; + auto digest_result = pol::CanonicalPolicyCodec::Digest(*policy); + const auto* digest_value = std::get_if(&digest_result); + Check(digest_value != nullptr, "policy_digest_available"); + digest = *digest_value; + + std::vector leaf_pems; + identities.reserve(policy->principals().size()); + leaf_pems.reserve(policy->principals().size()); + for (const auto& principal : policy->principals()) { + sec::PeerRole role = sec::PeerRole::kAdapter; + if (principal.role == pol::PrincipalRole::Replica) role = sec::PeerRole::kReplica; + if (principal.role == pol::PrincipalRole::Authority) role = sec::PeerRole::kAuthority; + const auto& identity = pki.IssueWithValidity(role, principal.uri, -60, 3600); + identities.push_back(&identity); + leaf_pems.push_back(identity.certificate_pem); + if (principal.role == pol::PrincipalRole::Adapter && adapter == nullptr) adapter = &identity; + if (principal.role == pol::PrincipalRole::Replica && principal.slot_id == 7U) replica = &identity; + if (principal.role == pol::PrincipalRole::Authority && authority == nullptr) authority = &identity; + } + const auto wall_seconds = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + now = {wall_seconds, 0}; + MutableClock initial_clock(now); + auto built = sec::CertificateRegistryLoader::Load( + policy, pki.root_certificate_pem(), leaf_pems, initial_clock); + const auto* value = std::get_if>(&built); + Check(value != nullptr, "registry_fixture_loads"); + registry = *value; + Check(adapter != nullptr && replica != nullptr && authority != nullptr, + "fixture_has_all_endpoint_roles"); + } +}; + +std::shared_ptr Provider( + const std::string& root, const sec::test::EphemeralIdentity& identity) { + std::vector pairs{{identity.private_key_pem, + identity.certificate_pem}}; + return std::make_shared(root, pairs); +} + +std::shared_ptr ClientCredentials( + const Fixture& fixture, const sec::test::EphemeralIdentity& client, + const sec::test::EphemeralIdentity& server) { + grpc::experimental::TlsChannelCredentialsOptions options; + options.set_certificate_provider(Provider(fixture.pki.root_certificate_pem(), client)); + options.watch_root_certs(); + options.watch_identity_key_cert_pairs(); + options.set_verify_server_certs(true); + options.set_check_call_host(false); + options.set_certificate_verifier( + grpc::experimental::ExternalCertificateVerifier::Create( + fixture.registry->peer_pins(), sec::ExpectedPeer{ + server.registered.uri, server.registered.leaf_der_sha256, + server.registered.role})); + return grpc::experimental::TlsCredentials(options); +} + +struct StateSpy final { + void Call(std::uint64_t cost) { + last_cost.store(cost, std::memory_order_relaxed); + calls.fetch_add(1, std::memory_order_release); + } + std::atomic calls{0}; + std::atomic last_cost{0}; +}; + +grpc::Status Reject(sec::PeerAuthDisposition disposition) { + switch (disposition) { + case sec::PeerAuthDisposition::Unauthenticated: + return {grpc::StatusCode::UNAUTHENTICATED, "peer rejected"}; + case sec::PeerAuthDisposition::ApplicationUnavailable: + return grpc::Status::OK; + } + return {grpc::StatusCode::INTERNAL, "internal rejection"}; +} +grpc::Status Reject(sec::AuthorizationDisposition disposition) { + switch (disposition) { + case sec::AuthorizationDisposition::Unauthenticated: + return {grpc::StatusCode::UNAUTHENTICATED, "peer rejected"}; + case sec::AuthorizationDisposition::InvalidArgument: + return {grpc::StatusCode::INVALID_ARGUMENT, "request rejected"}; + case sec::AuthorizationDisposition::PermissionDenied: + return {grpc::StatusCode::PERMISSION_DENIED, "operation denied"}; + case sec::AuthorizationDisposition::ApplicationUnavailable: + return grpc::Status::OK; + } + return {grpc::StatusCode::INTERNAL, "internal rejection"}; +} + +class AdmissionProbe final : public rg::AdmissionService::Service { + public: + struct Observation final { + unsigned calls{}; + std::string peer; + std::shared_ptr auth_context; + bool properties_ok{}; + }; + AdmissionProbe(std::shared_ptr registry, + sec::ITrustedWallClock& clock, StateSpy& spy, + std::string expected_uri, std::string expected_leaf_pem) + : authenticator_(registry, clock), spy_(spy), + expected_uri_(std::move(expected_uri)), expected_leaf_pem_(std::move(expected_leaf_pem)) { + auto result = sec::AuthorizationResolver::Create(std::move(registry), clock); + const auto* value = std::get_if(&result); + Check(value != nullptr, "admission_resolver_factory_succeeds"); + resolver_.emplace(*value); + } + + grpc::Status CheckAdmission(grpc::ServerContext* context, + const rg::CheckAdmissionRequest* request, + rg::AdmissionDecision* response) override { + const unsigned call_number = handler_calls.fetch_add(1, std::memory_order_relaxed) + 1; + auto current_auth_context = context->auth_context(); + if (!current_auth_context) return {grpc::StatusCode::UNAUTHENTICATED, "peer rejected"}; + const auto transports = current_auth_context->FindPropertyValues( + GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME); + const auto uris = current_auth_context->FindPropertyValues(GRPC_PEER_URI_PROPERTY_NAME); + const auto leafs = current_auth_context->FindPropertyValues(GRPC_X509_PEM_CERT_PROPERTY_NAME); + const bool properties_ok = transports.size() == 1 && uris.size() == 1 && leafs.size() == 1 && + transports.front().data() != nullptr && uris.front().data() != nullptr && + leafs.front().data() != nullptr && + std::string_view(transports.front().data(), transports.front().size()) == + GRPC_TLS_TRANSPORT_SECURITY_TYPE && + std::string_view(uris.front().data(), uris.front().size()) == expected_uri_ && + std::string_view(leafs.front().data(), leafs.front().size()) == expected_leaf_pem_; + { + std::lock_guard lock(observation_mutex_); + observation_ = Observation{call_number, context->peer(), current_auth_context, properties_ok}; + } + const auto authenticated = authenticator_.Authenticate(*current_auth_context); + const auto* peer = std::get_if(&authenticated); + if (!peer) { + const auto& failure = std::get(authenticated); + if (failure.disposition == sec::PeerAuthDisposition::ApplicationUnavailable) { + response->set_outcome(rg::DECISION_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + return Reject(failure.disposition); + } + const auto authorized = resolver_->Resolve(*peer, sec::RpcMethod::AdapterCheckAdmission, + *request); + const auto* operation = std::get_if(&authorized); + if (!operation) { + const auto& failure = std::get(authorized); + if (failure.disposition == sec::AuthorizationDisposition::ApplicationUnavailable) { + response->set_outcome(rg::DECISION_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + return Reject(failure.disposition); + } + spy_.Call(operation->cost_units()); + // This is a test sink, not a quota implementation. Avoid returning ALLOW. + response->set_outcome(rg::DECISION_OUTCOME_UNAVAILABLE); + response->set_attempt_id(request->attempt_id()); + response->set_epoch_id(reinterpret_cast(operation->epoch_id().data()), + operation->epoch_id().size()); + response->set_policy_digest(reinterpret_cast(operation->policy_digest().data()), + operation->policy_digest().size()); + response->set_mode(operation->mode() == pol::Mode::Credit + ? rg::ADMISSION_MODE_CREDIT + : rg::ADMISSION_MODE_STRICT); + return grpc::Status::OK; + } + + [[nodiscard]] Observation Snapshot() const { + std::lock_guard lock(observation_mutex_); + return observation_; + } + private: + std::atomic handler_calls{0}; + mutable std::mutex observation_mutex_; + Observation observation_; + sec::PeerAuthenticator authenticator_; + StateSpy& spy_; + std::string expected_uri_; + std::string expected_leaf_pem_; + std::optional resolver_; +}; + +class AuthorityProbe final : public rg::AuthorityService::Service { + public: + AuthorityProbe(std::shared_ptr registry, + sec::ITrustedWallClock& clock, StateSpy& spy, + std::string expected_uri, std::string expected_leaf_pem) + : authenticator_(registry, clock), spy_(spy), + expected_uri_(std::move(expected_uri)), expected_leaf_pem_(std::move(expected_leaf_pem)) { + auto result = sec::AuthorizationResolver::Create(std::move(registry), clock); + const auto* value = std::get_if(&result); + Check(value != nullptr, "authority_resolver_factory_succeeds"); + resolver_.emplace(*value); + } + + grpc::Status StrictCheck(grpc::ServerContext* context, + const rg::CheckAdmissionRequest* request, + rg::AdmissionDecision* response) override { + return HandleStrictCheck(context, request, response, sec::RpcMethod::ReplicaStrictCheck); + } + grpc::Status AcquireCredit(grpc::ServerContext* context, + const rg::AcquireCreditRequest* request, + rg::AcquireCreditResponse* response) override { + handler_calls.fetch_add(1, std::memory_order_relaxed); + auto auth_context = context->auth_context(); + if (!auth_context) return {grpc::StatusCode::UNAUTHENTICATED, "peer rejected"}; + last_properties_ok.store(HasExpectedProperties(*auth_context), std::memory_order_relaxed); + const auto authenticated = authenticator_.Authenticate(*auth_context); + const auto* peer = std::get_if(&authenticated); + if (!peer) { + const auto disposition = std::get(authenticated).disposition; + if (disposition == sec::PeerAuthDisposition::ApplicationUnavailable) { + response->set_grant_outcome(rg::GRANT_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + return Reject(disposition); + } + const auto authorized = resolver_->Resolve(*peer, sec::RpcMethod::ReplicaAcquireCredit, + *request); + const auto* grant = std::get_if(&authorized); + if (!grant) { + const auto disposition = std::get(authorized).disposition; + if (disposition == sec::AuthorizationDisposition::ApplicationUnavailable) { + response->set_grant_outcome(rg::GRANT_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + return Reject(disposition); + } + spy_.Call(grant->cost_units()); + // Authorization is not a committed grant; response is a probe sentinel. + response->set_grant_outcome(rg::GRANT_OUTCOME_UNAVAILABLE); + response->set_sequence(grant->sequence()); + response->set_epoch_id(request->epoch_id()); + response->set_policy_digest(request->policy_digest()); + return grpc::Status::OK; + } + + std::atomic handler_calls{0}; + std::atomic last_properties_ok{false}; + private: + bool HasExpectedProperties(const grpc::AuthContext& context) const { + const auto transports = context.FindPropertyValues(GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME); + const auto uris = context.FindPropertyValues(GRPC_PEER_URI_PROPERTY_NAME); + const auto leaves = context.FindPropertyValues(GRPC_X509_PEM_CERT_PROPERTY_NAME); + return transports.size() == 1 && uris.size() == 1 && leaves.size() == 1 && + transports.front().data() != nullptr && uris.front().data() != nullptr && + leaves.front().data() != nullptr && + std::string_view(transports.front().data(), transports.front().size()) == + GRPC_TLS_TRANSPORT_SECURITY_TYPE && + std::string_view(uris.front().data(), uris.front().size()) == expected_uri_ && + std::string_view(leaves.front().data(), leaves.front().size()) == expected_leaf_pem_; + } + grpc::Status HandleStrictCheck(grpc::ServerContext* context, + const rg::CheckAdmissionRequest* request, + rg::AdmissionDecision* response, sec::RpcMethod method) { + handler_calls.fetch_add(1, std::memory_order_relaxed); + const auto auth_context = context->auth_context(); + if (!auth_context) return {grpc::StatusCode::UNAUTHENTICATED, "peer rejected"}; + last_properties_ok.store(HasExpectedProperties(*auth_context), std::memory_order_relaxed); + const auto authenticated = authenticator_.Authenticate(*auth_context); + const auto* peer = std::get_if(&authenticated); + if (!peer) { + const auto disposition = std::get(authenticated).disposition; + if (disposition == sec::PeerAuthDisposition::ApplicationUnavailable) { + response->set_outcome(rg::DECISION_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + return Reject(disposition); + } + const auto authorized = resolver_->Resolve(*peer, method, *request); + const auto* operation = std::get_if(&authorized); + if (!operation) { + const auto disposition = std::get(authorized).disposition; + if (disposition == sec::AuthorizationDisposition::ApplicationUnavailable) { + response->set_outcome(rg::DECISION_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + return Reject(disposition); + } + spy_.Call(operation->cost_units()); + response->set_outcome(rg::DECISION_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + sec::PeerAuthenticator authenticator_; + StateSpy& spy_; + std::string expected_uri_; + std::string expected_leaf_pem_; + std::optional resolver_; +}; + +std::shared_ptr ServerCredentials( + const Fixture& fixture, const sec::test::EphemeralIdentity& server, + std::shared_ptr> verify_count) { + grpc::experimental::TlsServerCredentialsOptions options( + Provider(fixture.pki.root_certificate_pem(), server)); + options.watch_root_certs(); + options.watch_identity_key_cert_pairs(); + options.set_cert_request_type( + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); + options.set_certificate_verifier( + grpc::experimental::ExternalCertificateVerifier::Create( + fixture.registry->peer_pins(), std::nullopt, std::move(verify_count))); + return grpc::experimental::TlsServerCredentials(options); +} + +struct AdmissionNode final { + AdmissionProbe service; + std::unique_ptr server; + int port{}; + AdmissionNode(const Fixture& fixture, sec::ITrustedWallClock& clock, + StateSpy& spy, std::shared_ptr> verify_count) + : service(fixture.registry, clock, spy, fixture.adapter->registered.uri, + fixture.adapter->certificate_pem) { + grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", + ServerCredentials(fixture, *fixture.replica, std::move(verify_count)), &port); + builder.RegisterService(&service); + server = builder.BuildAndStart(); + Check(server != nullptr && port > 0, "admission_tls_server_starts"); + } + ~AdmissionNode() { if (server) server->Shutdown(); } +}; +struct AuthorityNode final { + AuthorityProbe service; + std::unique_ptr server; + int port{}; + AuthorityNode(const Fixture& fixture, sec::ITrustedWallClock& clock, + StateSpy& spy, std::shared_ptr> verify_count) + : service(fixture.registry, clock, spy, fixture.replica->registered.uri, + fixture.replica->certificate_pem) { + grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", + ServerCredentials(fixture, *fixture.authority, std::move(verify_count)), &port); + builder.RegisterService(&service); + server = builder.BuildAndStart(); + Check(server != nullptr && port > 0, "authority_tls_server_starts"); + } + ~AuthorityNode() { if (server) server->Shutdown(); } +}; + +rg::CheckAdmissionRequest AdmissionRequest(const Fixture& fixture) { + rg::CheckAdmissionRequest request; + request.set_tenant_id("zeta"); + request.set_operation_id("list"); + request.set_attempt_id(std::string(16, 'a')); + request.set_epoch_id(reinterpret_cast(fixture.policy->epoch_id().data()), 16); + request.set_policy_digest(reinterpret_cast(fixture.digest.data()), 32); + return request; +} +rg::AcquireCreditRequest CreditRequest(const Fixture& fixture) { + rg::AcquireCreditRequest request; + request.set_tenant_id("zeta"); + request.set_slot(7); + const auto& slot = *std::find_if(fixture.policy->replica_slots().begin(), + fixture.policy->replica_slots().end(), [](const auto& value) { return value.slot_id == 7; }); + request.set_incarnation_id(reinterpret_cast(slot.incarnation_id.data()), 16); + request.set_epoch_id(reinterpret_cast(fixture.policy->epoch_id().data()), 16); + request.set_policy_digest(reinterpret_cast(fixture.digest.data()), 32); + request.set_sequence(1); + request.set_trigger_cost_units(2); + request.set_trigger_operation_id("list"); + return request; +} +void SetDeadline(grpc::ClientContext& context) { + context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(5)); +} + +void Run(const std::string& policy_path) { + Fixture fixture(policy_path); + MutableClock clock(fixture.now); + StateSpy admission_spy; + StateSpy authority_spy; + auto admission_verifications = std::make_shared>(0); + auto authority_verifications = std::make_shared>(0); + AdmissionNode admission(fixture, clock, admission_spy, admission_verifications); + AuthorityNode authority(fixture, clock, authority_spy, authority_verifications); + + auto admission_channel = rg::transport::CreateEnforcementChannel( + "127.0.0.1:" + std::to_string(admission.port), + ClientCredentials(fixture, *fixture.adapter, *fixture.replica)); + auto admission_stub = rg::AdmissionService::NewStub(admission_channel); + auto request = AdmissionRequest(fixture); + rg::AdmissionDecision response; + grpc::ClientContext first_context; + SetDeadline(first_context); + const auto first_status = admission_stub->CheckAdmission(&first_context, request, &response); + Check(first_status.ok() && response.outcome() == rg::DECISION_OUTCOME_UNAVAILABLE, + "adapter_tls_rpc_authenticates_and_resolves_without_claiming_allow"); + Check(admission_spy.calls.load() == 1 && admission_spy.last_cost.load() == 2, + "policy_cost_reaches_only_authorized_state_spy"); + const auto first_observation = admission.service.Snapshot(); + Check(first_observation.auth_context != nullptr && !first_observation.peer.empty(), + "real_server_context_auth_and_peer_observed_without_logging_identity"); + Check(first_observation.properties_ok, + "real_tls_auth_context_exposes_exact_single_uri_and_leaf_properties"); + // Keep the first context alive for the full same-channel comparison so an + // allocator cannot recycle its address and create a false pointer match. + const auto retained_first_auth_context = first_observation.auth_context; + const auto peer_endpoint = first_observation.peer; + const auto handshake_count = admission_verifications->load(); + Check(handshake_count == 1, "server_leaf_verifier_runs_once_for_first_channel_rpc"); + + // Unknown protobuf field 6 is deliberately not a cost input. The resolver + // must use the immutable policy cost even when a client sends that unknown tag. + auto forged_cost = AdmissionRequest(fixture); + forged_cost.GetReflection()->MutableUnknownFields(&forged_cost)->AddVarint(6, 999); + rg::AdmissionDecision forged_response; + grpc::ClientContext forged_context; + SetDeadline(forged_context); + const auto forged_status = admission_stub->CheckAdmission( + &forged_context, forged_cost, &forged_response); + Check(forged_status.ok() && forged_response.outcome() == rg::DECISION_OUTCOME_UNAVAILABLE && + admission_spy.calls.load() == 2 && admission_spy.last_cost.load() == 2, + "unknown_wire_cost_cannot_change_authorized_policy_cost"); + + auto unknown = AdmissionRequest(fixture); + unknown.set_operation_id("unknown"); + rg::AdmissionDecision ignored; + grpc::ClientContext unknown_context; + SetDeadline(unknown_context); + const auto unknown_status = admission_stub->CheckAdmission(&unknown_context, unknown, &ignored); + Check(unknown_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + admission_spy.calls.load() == 2, + "unknown_operation_maps_invalid_argument_before_state_spy"); + + auto forbidden = AdmissionRequest(fixture); + forbidden.set_operation_id("delete"); + grpc::ClientContext forbidden_context; + SetDeadline(forbidden_context); + const auto forbidden_status = admission_stub->CheckAdmission( + &forbidden_context, forbidden, &ignored); + Check(forbidden_status.error_code() == grpc::StatusCode::PERMISSION_DENIED && + admission_spy.calls.load() == 2, + "known_unauthorized_pair_maps_permission_denied_before_state_spy"); + + auto stale = AdmissionRequest(fixture); + stale.set_policy_digest(std::string(32, 'x')); + grpc::ClientContext stale_context; + SetDeadline(stale_context); + const auto stale_status = admission_stub->CheckAdmission(&stale_context, stale, &ignored); + Check(stale_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + admission_spy.calls.load() == 2, + "stale_digest_maps_invalid_argument_before_state_spy"); + + auto short_id = AdmissionRequest(fixture); + short_id.set_attempt_id(std::string(15, 'a')); + grpc::ClientContext short_id_context; + SetDeadline(short_id_context); + const auto short_id_status = admission_stub->CheckAdmission( + &short_id_context, short_id, &ignored); + Check(short_id_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + admission_spy.calls.load() == 2, + "malformed_attempt_width_maps_invalid_argument_before_state_spy"); + + auto oversized = AdmissionRequest(fixture); + oversized.GetReflection()->MutableUnknownFields(&oversized)->AddLengthDelimited( + 100, std::string(16 * 1024, 'x')); + grpc::ClientContext oversized_context; + SetDeadline(oversized_context); + const auto oversized_status = admission_stub->CheckAdmission( + &oversized_context, oversized, &ignored); + Check(oversized_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + admission_spy.calls.load() == 2, + "decoded_oversize_maps_invalid_argument_before_state_spy"); + + // Advance only the injected trusted clock; OS/TLS wall time and channel do + // not change. The existing connection must be rejected by the per-call + // application guard, not by a reconnect or a second TLS verification. + const auto* adapter_record = fixture.registry->Find(fixture.adapter->registered.uri); + Check(adapter_record != nullptr, "registered_adapter_record"); + if (adapter_record) { + Check(fixture.registry->root_validity().Contains(adapter_record->validity.not_after), + "root_remains_valid_at_leaf_expiration_boundary"); + clock.Set(adapter_record->validity.not_after); + } + rg::AdmissionDecision expired_response; + grpc::ClientContext expired_context; + SetDeadline(expired_context); + const auto expired_status = admission_stub->CheckAdmission( + &expired_context, request, &expired_response); + Check(expired_status.error_code() == grpc::StatusCode::UNAUTHENTICATED && + admission_spy.calls.load() == 2, + "same_channel_expiry_fails_auth_before_state_spy"); + const auto expired_observation = admission.service.Snapshot(); + Check(retained_first_auth_context != nullptr && expired_observation.auth_context != nullptr && + expired_observation.properties_ok && expired_observation.peer == peer_endpoint && + admission_verifications->load() == handshake_count, + "expiry_call_reused_peer_identity_endpoint_and_tls_handshake"); + + clock.Set(fixture.now); + clock.SetHealthy(false); + rg::AdmissionDecision clock_response; + grpc::ClientContext clock_context; + SetDeadline(clock_context); + const auto clock_status = admission_stub->CheckAdmission( + &clock_context, request, &clock_response); + Check(clock_status.ok() && clock_response.outcome() == rg::DECISION_OUTCOME_UNAVAILABLE && + admission_spy.calls.load() == 2, + "clock_failure_is_application_unavailable_with_no_state_call"); + + // Restore time and verify the separate authority endpoint uses its own + // server role (authority) and accepts only the registered replica identity. + clock.SetHealthy(true); + + const auto pre_tls_negative = admission.service.Snapshot(); + const auto& unregistered_client = fixture.pki.Issue( + sec::PeerRole::kAdapter, "spiffe://rateguard.local/adapter/not-registered"); + const auto& same_uri_alternate_leaf = fixture.pki.Issue( + sec::PeerRole::kAdapter, fixture.adapter->registered.uri); + for (const auto* rejected_client : {&unregistered_client, &same_uri_alternate_leaf}) { + auto rejected_channel = rg::transport::CreateEnforcementChannel( + "127.0.0.1:" + std::to_string(admission.port), + ClientCredentials(fixture, *rejected_client, *fixture.replica)); + auto rejected_stub = rg::AdmissionService::NewStub(rejected_channel); + rg::AdmissionDecision rejected_response; + grpc::ClientContext rejected_context; + SetDeadline(rejected_context); + const auto rejected_status = rejected_stub->CheckAdmission( + &rejected_context, request, &rejected_response); + Check(!rejected_status.ok() && admission.service.Snapshot().calls == pre_tls_negative.calls && + admission_spy.calls.load() == 2, + rejected_client == &unregistered_client + ? "unregistered_valid_ca_client_rejected_before_handler" + : "same_uri_alternate_leaf_rejected_before_handler"); + rejected_channel.reset(); + } + + auto authority_channel = rg::transport::CreateEnforcementChannel( + "127.0.0.1:" + std::to_string(authority.port), + ClientCredentials(fixture, *fixture.replica, *fixture.authority)); + auto authority_stub = rg::AuthorityService::NewStub(authority_channel); + auto grant = CreditRequest(fixture); + rg::AcquireCreditResponse grant_response; + grpc::ClientContext grant_context; + SetDeadline(grant_context); + const auto grant_status = authority_stub->AcquireCredit( + &grant_context, grant, &grant_response); + Check(grant_status.ok() && grant_response.grant_outcome() == rg::GRANT_OUTCOME_UNAVAILABLE && + authority_spy.calls.load() == 1 && authority_spy.last_cost.load() == 2, + "replica_tls_rpc_resolves_credit_without_claiming_a_grant"); + Check(authority.service.last_properties_ok.load(std::memory_order_relaxed), + "authority_service_auth_context_exposes_registered_replica_properties"); + clock.SetHealthy(false); + rg::AcquireCreditResponse unavailable_grant; + grpc::ClientContext unavailable_grant_context; + SetDeadline(unavailable_grant_context); + const auto unavailable_grant_status = authority_stub->AcquireCredit( + &unavailable_grant_context, grant, &unavailable_grant); + Check(unavailable_grant_status.ok() && + unavailable_grant.grant_outcome() == rg::GRANT_OUTCOME_UNAVAILABLE && + authority_spy.calls.load() == 1, + "authority_clock_failure_returns_application_unavailable_without_state_call"); + clock.SetHealthy(true); + + auto grant_bad = CreditRequest(fixture); + grant_bad.set_sequence(0); + grpc::ClientContext zero_sequence_context; + SetDeadline(zero_sequence_context); + const auto zero_sequence_status = authority_stub->AcquireCredit( + &zero_sequence_context, grant_bad, &grant_response); + Check(zero_sequence_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + authority_spy.calls.load() == 1, + "zero_grant_sequence_maps_invalid_argument_before_state_spy"); + grant_bad = CreditRequest(fixture); + grant_bad.set_slot(2); + grpc::ClientContext slot_context; + SetDeadline(slot_context); + const auto slot_status = authority_stub->AcquireCredit(&slot_context, grant_bad, &grant_response); + Check(slot_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + authority_spy.calls.load() == 1, + "wrong_replica_slot_maps_invalid_argument_before_state_spy"); + grant_bad = CreditRequest(fixture); + grant_bad.set_incarnation_id(std::string(16, 'x')); + grpc::ClientContext incarnation_context; + SetDeadline(incarnation_context); + const auto incarnation_status = authority_stub->AcquireCredit( + &incarnation_context, grant_bad, &grant_response); + Check(incarnation_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + authority_spy.calls.load() == 1, + "wrong_replica_incarnation_maps_invalid_argument_before_state_spy"); + grant_bad = CreditRequest(fixture); + grant_bad.set_trigger_cost_units(999); + grpc::ClientContext cost_context; + SetDeadline(cost_context); + const auto trigger_cost_status = authority_stub->AcquireCredit( + &cost_context, grant_bad, &grant_response); + Check(trigger_cost_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + authority_spy.calls.load() == 1, + "wrong_trigger_cost_maps_invalid_argument_before_state_spy"); + + auto strict_request = AdmissionRequest(fixture); + rg::AdmissionDecision strict_response; + grpc::ClientContext strict_context; + SetDeadline(strict_context); + const auto strict_status = authority_stub->StrictCheck( + &strict_context, strict_request, &strict_response); + Check(strict_status.error_code() == grpc::StatusCode::INVALID_ARGUMENT && + authority_spy.calls.load() == 1, + "strict_method_rejected_in_credit_mode_before_state_spy"); + + // A registered adapter cannot invoke the internal authority method even if + // its selectors happen to name a valid operation. + auto adapter_to_authority = rg::transport::CreateEnforcementChannel( + "127.0.0.1:" + std::to_string(authority.port), + ClientCredentials(fixture, *fixture.adapter, *fixture.authority)); + auto adapter_authority_stub = rg::AuthorityService::NewStub(adapter_to_authority); + auto adapter_grant = CreditRequest(fixture); + grpc::ClientContext wrong_role_context; + SetDeadline(wrong_role_context); + const auto wrong_role_status = adapter_authority_stub->AcquireCredit( + &wrong_role_context, adapter_grant, &grant_response); + Check(wrong_role_status.error_code() == grpc::StatusCode::PERMISSION_DENIED && + authority_spy.calls.load() == 1, + "adapter_cannot_call_replica_authority_method"); + + admission_channel.reset(); + authority_channel.reset(); + adapter_to_authority.reset(); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) Fail("usage"); + try { + Run(argv[1]); + } catch (const std::exception&) { + // Do not echo exception text: it may contain peer-controlled or credential data. + Fail("fixture_or_rpc_exception"); + } + std::cout << "PASS peer_authorization_real_tls_rpc" << '\n'; + return 0; +} diff --git a/tools/tests/pinned_client_test_runner.py b/tools/tests/pinned_client_test_runner.py new file mode 100644 index 0000000..23223b4 --- /dev/null +++ b/tools/tests/pinned_client_test_runner.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Bound/redact TLS test output and retain exact session qualification facts.""" +import argparse +import json +import os +from pathlib import Path +import re +import resource +import signal +import subprocess +import tempfile + +LIMIT = 64 * 1024 +ARMOR = re.compile(rb'-----BEGIN [A-Z0-9 ]{1,80}-----') +NORMAL = b'PASS pinned_peer_rpc_client_fresh_guard' +DEFECT = b'FAIL fresh_per_call_guard_blocks_expired_pinned_identity_before_dispatch' +ALLOWED = {'status', 'actual_resumed', 'new_transport', 'client_leaf_pin', + 'server_leaf_pin', 'client_verifier_calls', 'server_verifier_calls', + 'client_verifier_delta', 'server_verifier_delta', 'verifiers_ran', + 'uncached_reconnects_passed', 'cache_attempts', 'cache_capacity', + 'max_attempts', 'dispatch_unchanged', 'server_reused_property', + 'handler_dispatched'} + +def cap(): + resource.setrlimit(resource.RLIMIT_FSIZE, (LIMIT, LIMIT)) + +def run(binary, fixture, qualify=False): + args = [binary, fixture] + (['--qualify-session'] if qualify else []) + with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err: + child = subprocess.Popen(args, stdout=out, stderr=err, + start_new_session=True, preexec_fn=cap) + try: + code = child.wait(timeout=120) + except subprocess.TimeoutExpired: + try: + os.killpg(child.pid, signal.SIGKILL) + except ProcessLookupError: + pass + child.wait() + raise RuntimeError('TLS test timed out; output withheld') from None + out.seek(0); err.seek(0) + stdout, stderr = out.read(LIMIT + 1), err.read(LIMIT + 1) + if len(stdout) + len(stderr) >= LIMIT or ARMOR.search(stdout + stderr): + raise RuntimeError('TLS output rejected by bound/privacy check') + return code, stdout.strip(), stderr + +def positive(binary, fixture): + code, stdout, stderr = run(binary, fixture) + if code != 0 or stdout != NORMAL: + labels = [s for s in stderr.splitlines() + if re.fullmatch(rb'FAIL [a-z0-9_]{1,128}', s)] + for label in labels[:2]: + print(label.decode('ascii')) + raise RuntimeError('normal TLS suite failed; raw output withheld') + +def main(): + p = argparse.ArgumentParser() + p.add_argument('--binary', required=True) + p.add_argument('--fixture', required=True) + p.add_argument('--mutant') + p.add_argument('--qualify', action='store_true') + p.add_argument('--output', type=Path) + a = p.parse_args() + if a.qualify: + if a.mutant or not a.output: + p.error('qualification requires output and no mutant') + code, stdout, _ = run(a.binary, a.fixture, True) + try: + data = json.loads(stdout) + except (ValueError, UnicodeDecodeError): + raise RuntimeError('qualification did not return one JSON record') from None + if not isinstance(data, dict) or set(data) - ALLOWED: + raise RuntimeError('qualification has unsupported fields') + if any(not isinstance(v, (str, bool, int)) for v in data.values()): + raise RuntimeError('qualification has unsupported value types') + counts = {'client_verifier_calls', 'server_verifier_calls', 'client_verifier_delta', + 'server_verifier_delta', 'cache_attempts', 'cache_capacity', 'max_attempts'} + for key, value in data.items(): + if key == 'status': + continue + if key in counts: + if type(value) is not int or not 0 <= value <= 100000: + raise RuntimeError('invalid qualification counter') + elif type(value) is not bool: + raise RuntimeError('invalid qualification boolean') + if data.get('status') in {'qualified', 'not_demonstrated', 'not_qualified_no_dispatch_observed'} and ( + data.get('uncached_reconnects_passed') is not True or data.get('cache_capacity') != 1): + raise RuntimeError('missing uncached control or bounded-cache evidence') + status = data.get('status') + safe_statuses = {'qualified', 'not_demonstrated', + 'not_qualified_no_dispatch_observed'} + if status not in safe_statuses and not ( + isinstance(status, str) and re.fullmatch(r'unsafe_[a-z_]{1,80}', status)): + raise RuntimeError('qualification has unsupported status') + if status == 'qualified' and not all(data.get(k) is True for k in ( + 'actual_resumed', 'new_transport', 'client_leaf_pin', + 'server_leaf_pin', 'uncached_reconnects_passed')): + raise RuntimeError('qualified record lacks required proof') + if status == 'qualified' and any(type(data.get(k)) is not int or data[k] < 1 + for k in ('client_verifier_delta', 'server_verifier_delta')): + raise RuntimeError('qualified record lacks fresh verifier deltas') + if status == 'not_demonstrated' and data.get('actual_resumed') is not False: + raise RuntimeError('contradictory non-demonstration') + if status == 'not_qualified_no_dispatch_observed' and ( + data.get('actual_resumed') is not True or data.get('dispatch_unchanged') is not True): + raise RuntimeError('missing no-dispatch observation') + record = {'schema_version': 1, 'scope': 'SDK qualification only; production cache disabled', + 'exit_code': code, 'observation': data} + a.output.parent.mkdir(parents=True, exist_ok=True) + a.output.write_text(json.dumps(record, indent=2) + '\n') + print(json.dumps(record, sort_keys=True)) + if code != 0 or status not in safe_statuses: + raise RuntimeError('resumed path failed qualification') + return + positive(a.binary, a.fixture) + if a.mutant: + code, stdout, stderr = run(a.mutant, a.fixture) + failures = [line.strip() for line in stderr.splitlines() if line.startswith(b'FAIL')] + if code != 1 or stdout or failures != [DEFECT]: + raise RuntimeError('preflight mutant escaped its exact expected check') + print('PASS independent client suite detects preflight bypass') + else: + print('PASS sealed pinned client TLS checks') + +if __name__ == '__main__': + try: + main() + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError): + raise SystemExit('B3 test check failed; bounded raw output withheld') from None diff --git a/tools/tests/pinned_peer_rpc_client_test.cpp b/tools/tests/pinned_peer_rpc_client_test.cpp new file mode 100644 index 0000000..0d9a9ec --- /dev/null +++ b/tools/tests/pinned_peer_rpc_client_test.cpp @@ -0,0 +1,959 @@ +#include "ephemeral_pki.h" + +#include "policy/canonical_codec.h" +#include "policy/policy_loader.h" +#include "proto/rateguard/v1/admission.grpc.pb.h" +#include "rateguard/security/pinned_peer_rpc_client.h" +#include "rateguard/security/tls_certificate_verifier.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace sec = rateguard::security; +namespace pol = rateguard::policy; +namespace rg = rateguard::v1; +using grpc::experimental::IdentityKeyCertPair; +using grpc::experimental::StaticDataCertificateProvider; + +namespace { + +[[noreturn]] void Fail(std::string_view label) { + std::cerr << "FAIL " << label << '\n'; + std::exit(1); +} +void Check(bool condition, std::string_view label) { + if (!condition) Fail(label); +} + +class MutableClock final : public sec::ITrustedWallClock { + public: + explicit MutableClock(sec::WallTime value) : value_(value) {} + sec::TrustedWallClockResult Now() override { + std::lock_guard lock(mutex_); + if (!healthy_) return sec::TrustedWallClockFailure{ + sec::TrustedWallClockFailureReason::PlatformUnavailable}; + return value_; + } + bool Healthy() const override { + std::lock_guard lock(mutex_); + return healthy_; + } + // This mutable clock separates test subcases. It is not the production + // clock's sticky-loss/recovery behavior and says nothing about fencing. + void Set(sec::WallTime value) { + std::lock_guard lock(mutex_); + value_ = value; + } + void SetHealthy(bool value) { + std::lock_guard lock(mutex_); + healthy_ = value; + } + private: + mutable std::mutex mutex_; + sec::WallTime value_; + bool healthy_{true}; +}; + +std::string ReadFile(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) return {}; + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} +void RemoveCreditBatchFields(nlohmann::json& value) { + if (value.is_object()) { + value.erase("credit_batch_units"); + for (auto& [key, child] : value.items()) { + (void)key; + RemoveCreditBatchFields(child); + } + } else if (value.is_array()) { + for (auto& child : value) RemoveCreditBatchFields(child); + } +} +std::string Hex(std::span bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string out; + out.reserve(bytes.size() * 2); + for (const auto byte : bytes) { + out.push_back(digits[byte >> 4]); + out.push_back(digits[byte & 15]); + } + return out; +} +pol::Digest32 RootDigest(std::string_view pem) { + BIO* raw = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + if (!raw) Fail("fixture_root_bio"); + std::unique_ptr bio(raw, BIO_free); + X509* cert_raw = PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr); + if (!cert_raw) Fail("fixture_root_cert"); + std::unique_ptr cert(cert_raw, X509_free); + const int length = i2d_X509(cert.get(), nullptr); + if (length <= 0 || length > 64 * 1024) Fail("fixture_root_der"); + std::vector der(static_cast(length)); + auto* cursor = der.data(); + if (i2d_X509(cert.get(), &cursor) != length) Fail("fixture_root_der"); + pol::Digest32 digest{}; + unsigned int written = 0; + if (EVP_Digest(der.data(), der.size(), digest.data(), &written, + EVP_sha256(), nullptr) != 1 || written != digest.size()) + Fail("fixture_root_digest"); + return digest; +} + +struct Fixture final { + sec::test::EphemeralPki pki; + std::shared_ptr policy; + std::shared_ptr registry; + std::vector identities; + const sec::test::EphemeralIdentity* adapter{}; + const sec::test::EphemeralIdentity* replica{}; + const sec::test::EphemeralIdentity* authority{}; + pol::Digest32 digest{}; + sec::WallTime now{}; + + Fixture(const std::string& policy_path, long adapter_expiry_delta, + long replica_expiry_delta, long others_expiry_delta = 48 * 60 * 60, + bool strict_policy = false) { + auto document = nlohmann::json::parse(ReadFile(policy_path)); + document["trust_root_sha256"] = Hex(RootDigest(pki.root_certificate_pem())); + if (strict_policy) { + document["mode"] = "strict"; + RemoveCreditBatchFields(document); + } + auto loaded = pol::PolicyLoader::Load(document.dump()); + const auto* policy_value = std::get_if>(&loaded); + if (policy_value == nullptr) { + // Fixed numeric error category only; never print policy/credential input. + const auto* error = std::get_if(&loaded); + Fail(error ? "fixture_policy_load_code_" + + std::to_string(static_cast(error->code)) : + "fixture_policy_load_unknown"); + } + policy = *policy_value; + const auto digest_result = pol::CanonicalPolicyCodec::Digest(*policy); + const auto* digest_value = std::get_if(&digest_result); + Check(digest_value != nullptr, "fixture_policy_digest"); + digest = *digest_value; + + std::vector leaves; + identities.reserve(policy->principals().size()); + leaves.reserve(policy->principals().size()); + for (const auto& principal : policy->principals()) { + sec::PeerRole role = sec::PeerRole::kAdapter; + if (principal.role == pol::PrincipalRole::Replica) role = sec::PeerRole::kReplica; + if (principal.role == pol::PrincipalRole::Authority) role = sec::PeerRole::kAuthority; + long expiry = others_expiry_delta; + if (principal.role == pol::PrincipalRole::Adapter) expiry = adapter_expiry_delta; + if (principal.role == pol::PrincipalRole::Replica && principal.slot_id == 7U) + expiry = replica_expiry_delta; + const auto& identity = pki.IssueWithValidity(role, principal.uri, -60, expiry); + identities.push_back(&identity); + leaves.push_back(identity.certificate_pem); + if (principal.role == pol::PrincipalRole::Adapter && adapter == nullptr) + adapter = &identity; + if (principal.role == pol::PrincipalRole::Replica && principal.slot_id == 7U) + replica = &identity; + if (principal.role == pol::PrincipalRole::Authority && authority == nullptr) + authority = &identity; + } + const auto seconds = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + now = {seconds, 0}; + MutableClock initial(now); + const auto built = sec::CertificateRegistryLoader::Load( + policy, pki.root_certificate_pem(), leaves, initial); + const auto* registry_value = std::get_if< + std::shared_ptr>(&built); + Check(registry_value != nullptr, "fixture_registry_load"); + registry = *registry_value; + Check(adapter != nullptr && replica != nullptr && authority != nullptr, + "fixture_has_required_roles"); + } + + sec::PinnedPeerClientConfig ClientConfig(int port) const { + return {sec::ClientCallPurpose::AdapterToReplicaAdmission, + "127.0.0.1:" + std::to_string(port), adapter->registered.uri, + replica->registered.uri, pki.root_certificate_pem(), + adapter->certificate_pem, adapter->private_key_pem}; + } + sec::PinnedPeerClientConfig AuthorityClientConfig(int port) const { + return {sec::ClientCallPurpose::ReplicaToAuthority, + "127.0.0.1:" + std::to_string(port), replica->registered.uri, + authority->registered.uri, pki.root_certificate_pem(), + replica->certificate_pem, replica->private_key_pem}; + } +}; + +std::shared_ptr Provider( + const std::string& root, const sec::test::EphemeralIdentity& identity) { + std::vector pairs{{identity.private_key_pem, + identity.certificate_pem}}; + return std::make_shared(root, pairs); +} + +class CountingClientVerifier final + : public grpc::experimental::ExternalCertificateVerifier { + public: + CountingClientVerifier(std::shared_ptr registry, + sec::ExpectedPeer expected, + std::shared_ptr> count) + : delegate_(std::move(registry), std::move(expected)), count_(std::move(count)) {} + bool Verify(grpc::experimental::TlsCustomVerificationCheckRequest* request, + std::function callback, + grpc::Status* status) override { + count_->fetch_add(1, std::memory_order_relaxed); + return delegate_.Verify(request, std::move(callback), status); + } + void Cancel(grpc::experimental::TlsCustomVerificationCheckRequest* request) override { + delegate_.Cancel(request); + } + private: + sec::PinnedPeerVerifier delegate_; + std::shared_ptr> count_; +}; + +std::shared_ptr ServerCredentials( + const Fixture& fixture, const sec::test::EphemeralIdentity& server, + std::shared_ptr> verify_count = {}) { + grpc::experimental::TlsServerCredentialsOptions options( + Provider(fixture.pki.root_certificate_pem(), server)); + options.watch_root_certs(); + options.watch_identity_key_cert_pairs(); + options.set_cert_request_type( + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); + if (verify_count) { + class CountingVerifier final : public grpc::experimental::ExternalCertificateVerifier { + public: + CountingVerifier(std::shared_ptr registry, + std::shared_ptr> count) + : delegate_(std::move(registry)), count_(std::move(count)) {} + bool Verify(grpc::experimental::TlsCustomVerificationCheckRequest* request, + std::function callback, + grpc::Status* status) override { + count_->fetch_add(1, std::memory_order_relaxed); + return delegate_.Verify(request, std::move(callback), status); + } + void Cancel(grpc::experimental::TlsCustomVerificationCheckRequest* request) override { + delegate_.Cancel(request); + } + private: + sec::PinnedPeerVerifier delegate_; + std::shared_ptr> count_; + }; + options.set_certificate_verifier( + grpc::experimental::ExternalCertificateVerifier::Create( + fixture.registry->peer_pins(), std::move(verify_count))); + } else { + options.set_certificate_verifier( + grpc::experimental::ExternalCertificateVerifier::Create( + fixture.registry->peer_pins())); + } + return grpc::experimental::TlsServerCredentials(options); +} + +class AdmissionSink final : public rg::AdmissionService::Service { + public: + grpc::Status CheckAdmission(grpc::ServerContext* context, + const rg::CheckAdmissionRequest* request, + rg::AdmissionDecision* response) override { + if (context->auth_context()) { + const auto transports = context->auth_context()->FindPropertyValues( + GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME); + const auto uris = context->auth_context()->FindPropertyValues( + GRPC_PEER_URI_PROPERTY_NAME); + const auto leafs = context->auth_context()->FindPropertyValues( + GRPC_X509_PEM_CERT_PROPERTY_NAME); + const bool leaf_matches = leafs.size() == 1 && leafs.front().data() != nullptr && + std::string_view(leafs.front().data(), leafs.front().size()) == expected_leaf_pem; + last_properties_ok.store(transports.size() == 1 && uris.size() == 1 && + leafs.size() == 1 && transports.front().data() != nullptr && + uris.front().data() != nullptr && leafs.front().data() != nullptr && + std::string_view(transports.front().data(), transports.front().size()) == + GRPC_TLS_TRANSPORT_SECURITY_TYPE && + std::string_view(uris.front().data(), uris.front().size()) == expected_uri && + leaf_matches, + std::memory_order_release); + const auto resumed = context->auth_context()->FindPropertyValues( + GRPC_SSL_SESSION_REUSED_PROPERTY); + const bool session_property_present = resumed.size() == 1 && resumed.front().data() != nullptr; + const bool session_reused = session_property_present && + std::string_view(resumed.front().data(), resumed.front().size()) == "true"; + std::lock_guard lock(observation_mutex); + observed.push_back({context->peer(), session_property_present, session_reused, leaf_matches}); + } + calls.fetch_add(1, std::memory_order_release); + if (request->operation_id() == "transport_unavailable") + return {grpc::StatusCode::UNAVAILABLE, "synthetic transport failure"}; + response->set_outcome(rg::DECISION_OUTCOME_UNAVAILABLE); + response->set_attempt_id(request->attempt_id()); + return grpc::Status::OK; + } + std::string expected_uri; + std::string expected_leaf_pem; + std::atomic calls{0}; + std::atomic last_properties_ok{false}; + std::mutex observation_mutex; + struct Observation final { + std::string peer; + bool session_property_present; + bool resumed; + bool leaf_matches; + }; + std::vector observed; +}; + +struct ServerNode final { + AdmissionSink service; + std::unique_ptr server; + int port{}; + ServerNode(const Fixture& fixture, const sec::test::EphemeralIdentity& server_identity, + std::shared_ptr> verify_count = {}) + : service{} { + service.expected_uri = fixture.adapter->registered.uri; + service.expected_leaf_pem = fixture.adapter->certificate_pem; + grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", + ServerCredentials(fixture, server_identity, std::move(verify_count)), &port); + builder.RegisterService(&service); + server = builder.BuildAndStart(); + Check(server != nullptr && port > 0, "probe_tls_server_started"); + } + ~ServerNode() { + if (server) { + server->Shutdown(); + server->Wait(); + } + } +}; + +class AuthoritySink final : public rg::AuthorityService::Service { + public: + grpc::Status StrictCheck(grpc::ServerContext*, const rg::CheckAdmissionRequest* request, + rg::AdmissionDecision* response) override { + calls.fetch_add(1, std::memory_order_release); + if (request->operation_id() == "slow") + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + response->set_outcome(rg::DECISION_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + grpc::Status AcquireCredit(grpc::ServerContext*, const rg::AcquireCreditRequest* request, + rg::AcquireCreditResponse* response) override { + calls.fetch_add(1, std::memory_order_release); + if (request->trigger_operation_id() == "slow") + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + response->set_grant_outcome(rg::GRANT_OUTCOME_UNAVAILABLE); + return grpc::Status::OK; + } + std::atomic calls{0}; +}; + +struct AuthorityNode final { + AuthoritySink service; + std::unique_ptr server; + int port{}; + explicit AuthorityNode(const Fixture& fixture) { + grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", + ServerCredentials(fixture, *fixture.authority), &port); + builder.RegisterService(&service); + server = builder.BuildAndStart(); + Check(server != nullptr && port > 0, "authority_tls_server_started"); + } + ~AuthorityNode() { + if (server) { server->Shutdown(); server->Wait(); } + } +}; + +rg::CheckAdmissionRequest Request(const Fixture& fixture, + std::string operation = "list") { + rg::CheckAdmissionRequest request; + request.set_tenant_id("zeta"); + request.set_operation_id(std::move(operation)); + request.set_attempt_id(std::string(16, 'a')); + request.set_epoch_id(reinterpret_cast(fixture.policy->epoch_id().data()), 16); + request.set_policy_digest(reinterpret_cast(fixture.digest.data()), 32); + return request; +} +auto Deadline() { + return std::chrono::system_clock::now() + std::chrono::seconds(5); +} + +std::variant +CreateClient(const Fixture& fixture, int port, MutableClock& clock) { + return sec::PinnedPeerRpcClient::Create(fixture.ClientConfig(port), fixture.registry, clock); +} + +sec::PinnedPeerRpcClient& RequireClient( + std::variant& storage) { + auto* client = std::get_if(&storage); + Check(client != nullptr, "typed_pinned_client_factory_succeeds"); + return *client; +} + +sec::WallTime OneNanosecondBefore(sec::WallTime value) { + if (value.nanoseconds != 0) return {value.unix_seconds, value.nanoseconds - 1}; + return {value.unix_seconds - 1, 999'999'999U}; +} + +void AssertNotSent(const auto& result, sec::ClientGuardFailureReason reason, + sec::ClientGuardDisposition disposition, std::string_view label) { + const auto* not_sent = std::get_if(&result); + Check(not_sent != nullptr, label); + Check(not_sent->failure.guard_failure.has_value(), label); + Check(not_sent->failure.guard_failure->reason == reason && + not_sent->failure.guard_failure->disposition == disposition, label); +} + +void AssertFactoryFailure(const Fixture& fixture, sec::PinnedPeerClientConfig config, + MutableClock& clock, + sec::PinnedClientFactoryFailureReason expected, + std::string_view label) { + const auto result = sec::PinnedPeerRpcClient::Create( + std::move(config), fixture.registry, clock); + const auto* failure = std::get_if(&result); + Check(failure != nullptr && failure->reason == expected, label); +} + +void RunClientFactoryValidationCases(const std::string& policy_path) { + Fixture fixture(policy_path, 48 * 60 * 60, 48 * 60 * 60); + MutableClock clock(fixture.now); + const auto base = fixture.ClientConfig(1); + auto bad_root = base; + bad_root.root_certificate_pem = "not a certificate"; + AssertFactoryFailure(fixture, std::move(bad_root), clock, + sec::PinnedClientFactoryFailureReason::InvalidRootPem, "invalid_root_pem_rejected"); + sec::test::EphemeralPki other_pki; + auto wrong_root = base; + wrong_root.root_certificate_pem = other_pki.root_certificate_pem(); + AssertFactoryFailure(fixture, std::move(wrong_root), clock, + sec::PinnedClientFactoryFailureReason::RootPinMismatch, "wrong_root_pin_rejected"); + auto prefix_cert = base; + prefix_cert.local_certificate_pem = "junk\n" + prefix_cert.local_certificate_pem; + AssertFactoryFailure(fixture, std::move(prefix_cert), clock, + sec::PinnedClientFactoryFailureReason::InvalidClientCertificatePem, + "junk_before_client_certificate_rejected"); + const auto& alternate = fixture.pki.IssueWithValidity( + sec::PeerRole::kAdapter, fixture.adapter->registered.uri, -60, 48 * 60 * 60); + auto wrong_pin = base; + wrong_pin.local_certificate_pem = alternate.certificate_pem; + AssertFactoryFailure(fixture, std::move(wrong_pin), clock, + sec::PinnedClientFactoryFailureReason::ClientPinMismatch, + "same_uri_alternate_local_leaf_pin_rejected"); + auto wrong_key = base; + wrong_key.local_private_key_pem = fixture.authority->private_key_pem; + AssertFactoryFailure(fixture, std::move(wrong_key), clock, + sec::PinnedClientFactoryFailureReason::PrivateKeyMismatch, + "mismatched_private_key_rejected"); + auto prefix_key = base; + prefix_key.local_private_key_pem = "junk\n" + prefix_key.local_private_key_pem; + AssertFactoryFailure(fixture, std::move(prefix_key), clock, + sec::PinnedClientFactoryFailureReason::InvalidPrivateKeyPem, + "junk_before_private_key_rejected"); + auto multiple_keys = base; + multiple_keys.local_private_key_pem += multiple_keys.local_private_key_pem; + AssertFactoryFailure(fixture, std::move(multiple_keys), clock, + sec::PinnedClientFactoryFailureReason::InvalidPrivateKeyPem, + "multiple_private_keys_rejected"); + auto encrypted_key = base; + encrypted_key.local_private_key_pem = + "-----BEGIN ENCRYPTED PRIVATE KEY-----\nZmFrZQ==\n-----END ENCRYPTED PRIVATE KEY-----\n"; + AssertFactoryFailure(fixture, std::move(encrypted_key), clock, + sec::PinnedClientFactoryFailureReason::InvalidPrivateKeyPem, + "encrypted_private_key_rejected_without_prompt"); + auto oversized = base; + oversized.root_certificate_pem.assign(64U * 1024U + 1U, ' '); + AssertFactoryFailure(fixture, std::move(oversized), clock, + sec::PinnedClientFactoryFailureReason::OversizedCredential, + "oversized_credential_rejected_before_parse"); +} + +void RunExpiryCase(const std::string& policy_path, long adapter_delta, + long server_delta, bool expire_root, bool expire_adapter, + bool expire_server) { + Check((expire_root ? 1 : 0) + (expire_adapter ? 1 : 0) + (expire_server ? 1 : 0) == 1, + "exactly_one_expiry_case_selected"); + Fixture fixture(policy_path, adapter_delta, server_delta, + expire_root ? 48 * 60 * 60 : 48 * 60 * 60); + MutableClock clock(fixture.now); + ServerNode server(fixture, *fixture.replica); + auto client_storage = CreateClient(fixture, server.port, clock); + auto& client = RequireClient(client_storage); + const auto request = Request(fixture); + + const auto infinite_deadline = client.CheckAdmission( + request, std::chrono::system_clock::time_point::max()); + const auto* infinite_not_sent = std::get_if(&infinite_deadline); + Check(infinite_not_sent && + infinite_not_sent->failure.reason == sec::PinnedClientCallFailureReason::InvalidDeadline, + "infinite_deadline_rejected_before_stub"); + const auto elapsed_deadline = client.CheckAdmission( + request, std::chrono::system_clock::now() - std::chrono::seconds(1)); + const auto* elapsed_not_sent = std::get_if(&elapsed_deadline); + Check(elapsed_not_sent && + elapsed_not_sent->failure.reason == sec::PinnedClientCallFailureReason::InvalidDeadline, + "expired_deadline_rejected_before_stub"); + const auto wrong_method = client.StrictCheck(request, Deadline()); + const auto* wrong_method_not_sent = std::get_if(&wrong_method); + Check(wrong_method_not_sent && wrong_method_not_sent->failure.reason == + sec::PinnedClientCallFailureReason::PurposeMethodMismatch, + "adapter_client_cannot_invoke_authority_method"); + const auto wrong_credit_method = client.AcquireCredit(rg::AcquireCreditRequest{}, Deadline()); + const auto* wrong_credit_not_sent = std::get_if(&wrong_credit_method); + Check(wrong_credit_not_sent && wrong_credit_not_sent->failure.reason == + sec::PinnedClientCallFailureReason::PurposeMethodMismatch, + "adapter_client_cannot_invoke_credit_authority_method"); + Check(server.service.calls.load(std::memory_order_acquire) == 0, + "preflight_validation_rejections_do_not_dispatch"); + + auto first = client.CheckAdmission(request, Deadline()); + const auto* invocation = std::get_if>(&first); + Check(invocation != nullptr && invocation->has_transport_status() && + invocation->transport_status()->ok() && + invocation->raw_response().outcome() == rg::DECISION_OUTCOME_UNAVAILABLE, + "warm_tls_rpc_returns_untrusted_probe_sentinel"); + Check(server.service.calls.load(std::memory_order_acquire) == 1 && + server.service.last_properties_ok.load(std::memory_order_acquire), + "actual_mtls_handler_observed_registered_adapter_properties_once"); + if (!invocation) return; + + const auto forward_valid = client.ValidateBeforeForward(*invocation); + Check(std::holds_alternative(forward_valid), + "forward_guard_rechecks_time_while_currently_valid_without_forwarding"); + + sec::WallTime boundary{}; + sec::ClientGuardFailureReason expected_reason{}; + if (expire_root) { + boundary = fixture.registry->root_validity().not_after; + expected_reason = sec::ClientGuardFailureReason::RootExpired; + Check(boundary < fixture.registry->Find(fixture.adapter->registered.uri)->validity.not_after && + boundary < fixture.registry->Find(fixture.replica->registered.uri)->validity.not_after, + "root_expiry_isolated_from_leaf_expiry"); + } else if (expire_adapter) { + boundary = fixture.registry->Find(fixture.adapter->registered.uri)->validity.not_after; + expected_reason = sec::ClientGuardFailureReason::ClientExpired; + Check(fixture.registry->root_validity().Contains(boundary) && + fixture.registry->Find(fixture.replica->registered.uri)->validity.Contains( + OneNanosecondBefore(boundary)), + "client_leaf_expiry_isolated_from_root_and_server_leaf"); + } else { + boundary = fixture.registry->Find(fixture.replica->registered.uri)->validity.not_after; + expected_reason = sec::ClientGuardFailureReason::ServerExpired; + Check(fixture.registry->root_validity().Contains(boundary) && + fixture.registry->Find(fixture.adapter->registered.uri)->validity.Contains( + OneNanosecondBefore(boundary)), + "server_leaf_expiry_isolated_from_root_and_client_leaf"); + } + + clock.Set(boundary); + const auto forward_expired = client.ValidateBeforeForward(*invocation); + const auto* forward_failure = std::get_if(&forward_expired); + Check(forward_failure != nullptr && forward_failure->reason == expected_reason && + forward_failure->disposition == sec::ClientGuardDisposition::CredentialInvalid, + "pre_forward_guard_rechecks_expired_certificate_without_backend_call"); + auto expired_call = client.CheckAdmission(request, Deadline()); + AssertNotSent(expired_call, expected_reason, + sec::ClientGuardDisposition::CredentialInvalid, + "fresh_per_call_guard_blocks_expired_pinned_identity_before_dispatch"); + Check(server.service.calls.load(std::memory_order_acquire) == 1, + "expired_warm_channel_attempt_not_dispatched"); + + clock.Set(fixture.now); + clock.SetHealthy(false); + auto clock_failure = client.CheckAdmission(request, Deadline()); + AssertNotSent(clock_failure, sec::ClientGuardFailureReason::ClockUntrusted, + sec::ClientGuardDisposition::ApplicationUnavailable, + "clock_loss_is_local_unavailable_before_dispatch"); + Check(server.service.calls.load(std::memory_order_acquire) == 1, + "untrusted_clock_attempt_not_dispatched"); +} + +void RunRetryAndReconnectCases(const std::string& policy_path) { + Fixture fixture(policy_path, 48 * 60 * 60, 48 * 60 * 60); + MutableClock clock(fixture.now); + ServerNode server(fixture, *fixture.replica); + auto storage = CreateClient(fixture, server.port, clock); + auto& client = RequireClient(storage); + const auto request = Request(fixture, "transport_unavailable"); + const auto result = client.CheckAdmission(request, Deadline()); + const auto* invoked = std::get_if>(&result); + Check(invoked && invoked->has_transport_status() && + invoked->transport_status()->error_code() == grpc::StatusCode::UNAVAILABLE, + "invoked_transport_failure_retained_as_raw_status"); + Check(server.service.calls.load(std::memory_order_acquire) == 1, + "enforcement_wrapper_does_not_retry_an_invoked_rpc"); +} + +void RunChangedServerPinCase(const std::string& policy_path) { + Fixture fixture(policy_path, 48 * 60 * 60, 48 * 60 * 60); + // The alternate certificate has the registered server URI but a different + // DER leaf. It is intentionally not added to the registry. + const auto& replacement = fixture.pki.IssueWithValidity( + sec::PeerRole::kReplica, fixture.replica->registered.uri, -60, 48 * 60 * 60); + MutableClock clock(fixture.now); + ServerNode replacement_server(fixture, replacement); + auto storage = CreateClient(fixture, replacement_server.port, clock); + auto& client = RequireClient(storage); + const auto result = client.CheckAdmission(Request(fixture), Deadline()); + const auto* invoked = std::get_if>(&result); + Check(invoked != nullptr && invoked->has_transport_status() && + !invoked->transport_status()->ok(), + "new_endpoint_same_uri_replacement_leaf_fails_tls_pin"); + Check(replacement_server.service.calls.load(std::memory_order_acquire) == 0, + "replacement_server_leaf_rejected_before_handler"); +} + +void RunAuthorityWrapperCase(const std::string& policy_path, bool strict_policy) { + Fixture fixture(policy_path, 48 * 60 * 60, 48 * 60 * 60, + 48 * 60 * 60, strict_policy); + Check(fixture.policy->mode() == + (strict_policy ? pol::Mode::Strict : pol::Mode::Credit), + "authority_fixture_has_requested_policy_mode"); + MutableClock clock(fixture.now); + AuthorityNode server(fixture); + auto result = sec::PinnedPeerRpcClient::Create( + fixture.AuthorityClientConfig(server.port), fixture.registry, clock); + auto* client = std::get_if(&result); + Check(client != nullptr, "replica_to_authority_wrapper_factory_succeeds"); + if (client == nullptr) return; + + const auto forbidden_adapter_method = client->CheckAdmission(Request(fixture), Deadline()); + const auto* forbidden_not_sent = std::get_if(&forbidden_adapter_method); + Check(forbidden_not_sent && forbidden_not_sent->failure.reason == + sec::PinnedClientCallFailureReason::PurposeMethodMismatch, + "replica_authority_client_cannot_call_adapter_admission"); + + rg::CheckAdmissionRequest strict_request = Request(fixture); + auto strict_result = client->StrictCheck(strict_request, Deadline()); + if (fixture.policy->mode() == pol::Mode::Strict) { + const auto* strict_invoked = + std::get_if>(&strict_result); + Check(strict_invoked && strict_invoked->has_transport_status() && + strict_invoked->transport_status()->ok() && + strict_invoked->raw_response().outcome() == rg::DECISION_OUTCOME_UNAVAILABLE, + "replica_to_authority_strict_rpc_invoked_once_and_raw_response_retained"); + } else { + const auto* strict_not_sent = std::get_if(&strict_result); + Check(strict_not_sent && strict_not_sent->failure.reason == + sec::PinnedClientCallFailureReason::PolicyModeMismatch, + "strict_rpc_rejected_for_credit_policy_before_stub"); + } + + rg::AcquireCreditRequest grant_request; + grant_request.set_tenant_id("zeta"); + grant_request.set_slot(7); + const auto slot = std::find_if(fixture.policy->replica_slots().begin(), + fixture.policy->replica_slots().end(), [](const auto& value) { return value.slot_id == 7; }); + Check(slot != fixture.policy->replica_slots().end(), "fixture_replica_slot_found"); + if (slot == fixture.policy->replica_slots().end()) return; + grant_request.set_incarnation_id( + reinterpret_cast(slot->incarnation_id.data()), slot->incarnation_id.size()); + grant_request.set_epoch_id(reinterpret_cast(fixture.policy->epoch_id().data()), 16); + grant_request.set_policy_digest(reinterpret_cast(fixture.digest.data()), 32); + grant_request.set_sequence(1); + grant_request.set_trigger_cost_units(2); + grant_request.set_trigger_operation_id("list"); + auto grant_result = client->AcquireCredit(grant_request, Deadline()); + if (fixture.policy->mode() == pol::Mode::Credit) { + const auto* grant_invoked = + std::get_if>(&grant_result); + Check(grant_invoked && grant_invoked->has_transport_status() && + grant_invoked->transport_status()->ok() && + grant_invoked->raw_response().grant_outcome() == rg::GRANT_OUTCOME_UNAVAILABLE, + "replica_to_authority_credit_rpc_invoked_once_and_raw_response_retained"); + } else { + const auto* grant_not_sent = std::get_if(&grant_result); + Check(grant_not_sent && grant_not_sent->failure.reason == + sec::PinnedClientCallFailureReason::PolicyModeMismatch, + "credit_rpc_rejected_for_strict_policy_before_stub"); + } + Check(server.service.calls.load(std::memory_order_acquire) == 1U, + "only_policy_mode_supported_authority_method_dispatched_once"); + + const unsigned calls_before_timeout = server.service.calls.load(std::memory_order_acquire); + if (fixture.policy->mode() == pol::Mode::Strict) { + strict_request.set_operation_id("slow"); + const auto timeout_result = client->StrictCheck(strict_request, Deadline()); + const auto* invoked = std::get_if>(&timeout_result); + Check(invoked && invoked->has_transport_status() && + invoked->transport_status()->error_code() == grpc::StatusCode::DEADLINE_EXCEEDED, + "authority_deadline_is_bounded_and_invoked_status_preserved"); + } else { + grant_request.set_trigger_operation_id("slow"); + const auto timeout_result = client->AcquireCredit(grant_request, Deadline()); + const auto* invoked = std::get_if>(&timeout_result); + Check(invoked && invoked->has_transport_status() && + invoked->transport_status()->error_code() == grpc::StatusCode::DEADLINE_EXCEEDED, + "authority_deadline_is_bounded_and_invoked_status_preserved"); + } + Check(server.service.calls.load(std::memory_order_acquire) == calls_before_timeout + 1, + "bounded_authority_timeout_has_single_server_dispatch"); +} + +void RunSessionCacheQualification(const std::string& policy_path) { + Fixture fixture(policy_path, 48 * 60 * 60, 48 * 60 * 60); + auto server_verifier_calls = std::make_shared>(0); + auto client_verifier_calls = std::make_shared>(0); + ServerNode server(fixture, *fixture.replica, server_verifier_calls); + + grpc::experimental::TlsChannelCredentialsOptions client_options; + client_options.set_certificate_provider( + Provider(fixture.pki.root_certificate_pem(), *fixture.adapter)); + client_options.watch_root_certs(); + client_options.watch_identity_key_cert_pairs(); + client_options.set_verify_server_certs(true); + client_options.set_check_call_host(false); + client_options.set_certificate_verifier( + grpc::experimental::ExternalCertificateVerifier::Create< + CountingClientVerifier>(fixture.registry->peer_pins(), + sec::ExpectedPeer{fixture.replica->registered.uri, + fixture.replica->registered.leaf_der_sha256, + fixture.replica->registered.role}, client_verifier_calls)); + auto credentials = grpc::experimental::TlsCredentials(client_options); + Check(credentials != nullptr, "session_probe_tls_credentials_created"); + + std::string first_fresh_peer; + for (unsigned attempt = 0; attempt < 2; ++attempt) { + grpc::ChannelArguments fresh_args; + fresh_args.SetInt("grpc.use_local_subchannel_pool", 1); + fresh_args.SetInt("grpc.enable_retries", 0); + fresh_args.SetInt("grpc.experimental.enable_hedging", 0); + auto fresh_channel = grpc::CreateCustomChannel( + "127.0.0.1:" + std::to_string(server.port), credentials, fresh_args); + Check(fresh_channel != nullptr, "fresh_reconnect_channel_created"); + auto fresh_stub = rg::AdmissionService::NewStub(fresh_channel); + grpc::ClientContext fresh_context; + fresh_context.set_deadline(Deadline()); + rg::AdmissionDecision fresh_response; + const auto fresh_status = fresh_stub->CheckAdmission( + &fresh_context, Request(fixture), &fresh_response); + Check(fresh_status.ok() && + fresh_response.outcome() == rg::DECISION_OUTCOME_UNAVAILABLE, + "fresh_reconnect_rpc_sentinel"); + const auto fresh_auth = fresh_context.auth_context(); + Check(fresh_auth != nullptr, "fresh_reconnect_auth_context"); + if (fresh_auth == nullptr) continue; + const auto reused_values = fresh_auth->FindPropertyValues( + GRPC_SSL_SESSION_REUSED_PROPERTY); + const auto server_uri = fresh_auth->FindPropertyValues(GRPC_PEER_URI_PROPERTY_NAME); + const auto server_leaf = fresh_auth->FindPropertyValues(GRPC_X509_PEM_CERT_PROPERTY_NAME); + const bool client_says_fresh = reused_values.size() == 1 && + reused_values.front().data() != nullptr && + std::string_view(reused_values.front().data(), reused_values.front().size()) == "false"; + Check(client_says_fresh && server_uri.size() == 1 && server_leaf.size() == 1 && + server_uri.front().data() != nullptr && server_leaf.front().data() != nullptr && + std::string_view(server_uri.front().data(), server_uri.front().size()) == + fixture.replica->registered.uri && + std::string_view(server_leaf.front().data(), server_leaf.front().size()) == + fixture.replica->certificate_pem, + "uncached_new_transport_has_exact_server_identity_and_no_resume"); + std::string peer; + { + std::lock_guard lock(server.service.observation_mutex); + Check(server.service.observed.size() > attempt, + "fresh_reconnect_server_observed_transport"); + if (server.service.observed.size() > attempt) { + const auto& observation = server.service.observed[attempt]; + peer = observation.peer; + Check(observation.session_property_present && !observation.resumed && + observation.leaf_matches, + "uncached_server_auth_context_is_fresh_and_pinned"); + } + } + if (attempt == 0) first_fresh_peer = std::move(peer); + else Check(!peer.empty() && peer != first_fresh_peer, + "uncached_reconnect_uses_distinct_tcp_endpoint"); + } + const std::size_t cache_observation_base = 2; + Check(client_verifier_calls->load() > 0 && server_verifier_calls->load() > 0, + "uncached_handshakes_invoked_both_real_pin_verifiers"); + + grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(1); + Check(cache != nullptr, "bounded_one_entry_session_cache_created"); + grpc_arg cache_arg = grpc_ssl_session_cache_create_channel_arg(cache); + + std::vector peers; + bool saw_resume_with_leaf_proof = false; + bool saw_resume_without_leaf_proof = false; + bool client_leaf_exact_on_resume = false; + unsigned client_delta_on_resume = 0; + unsigned server_delta_on_resume = 0; + bool new_transport = false; + unsigned cache_handler_calls = 0; + unsigned cache_attempts = 0; + for (unsigned attempt = 0; attempt < 8; ++attempt) { + cache_attempts = attempt + 1; + grpc::ChannelArguments args; + args.SetInt("grpc.use_local_subchannel_pool", 1); + args.SetInt("grpc.enable_retries", 0); + args.SetInt("grpc.experimental.enable_hedging", 0); + args.SetPointerWithVtable(cache_arg.key, cache_arg.value.pointer.p, + cache_arg.value.pointer.vtable); + auto channel = grpc::CreateCustomChannel("127.0.0.1:" + std::to_string(server.port), + credentials, args); + Check(channel != nullptr, "session_probe_channel_created"); + auto stub = rg::AdmissionService::NewStub(channel); + const unsigned handler_calls_before = server.service.calls.load(std::memory_order_acquire); + const unsigned client_verifier_calls_before = client_verifier_calls->load(); + const unsigned server_verifier_calls_before = server_verifier_calls->load(); + grpc::ClientContext context; + context.set_deadline(Deadline()); + rg::AdmissionDecision response; + const auto status = stub->CheckAdmission(&context, Request(fixture), &response); + const auto auth = context.auth_context(); + if (auth == nullptr) { + if (attempt == 0) Fail("initial_session_probe_auth_context_missing"); + break; + } + const auto reused = auth->FindPropertyValues(GRPC_SSL_SESSION_REUSED_PROPERTY); + const auto uri = auth->FindPropertyValues(GRPC_PEER_URI_PROPERTY_NAME); + const auto leaf = auth->FindPropertyValues(GRPC_X509_PEM_CERT_PROPERTY_NAME); + const bool is_reused = reused.size() == 1 && reused.front().data() != nullptr && + std::string_view(reused.front().data(), reused.front().size()) == "true"; + const bool client_leaf_exact = uri.size() == 1 && leaf.size() == 1 && + uri.front().data() != nullptr && leaf.front().data() != nullptr && + std::string_view(uri.front().data(), uri.front().size()) == + fixture.replica->registered.uri && + std::string_view(leaf.front().data(), leaf.front().size()) == + fixture.replica->certificate_pem; + std::string peer; + bool server_reused = false; + bool server_session_property_present = false; + bool server_leaf_exact = false; + { + std::lock_guard lock(server.service.observation_mutex); + if (server.service.observed.size() > cache_observation_base + attempt) { + const auto& observation = server.service.observed.back(); + peer = observation.peer; + server_session_property_present = observation.session_property_present; + server_reused = observation.resumed; + server_leaf_exact = observation.leaf_matches; + } + } + if (is_reused) { + client_leaf_exact_on_resume = client_leaf_exact; + new_transport = !peers.empty() && !peer.empty() && peer != peers.front(); + if (!status.ok()) { + const unsigned handler_calls_after = server.service.calls.load(std::memory_order_acquire); + saw_resume_without_leaf_proof = handler_calls_after == handler_calls_before; + if (!saw_resume_without_leaf_proof) { + std::cout << nlohmann::json{{"status", "unsafe_resumed_failure_after_dispatch"}, + {"actual_resumed", true}, {"dispatch_unchanged", false}}.dump() << '\n'; + grpc_ssl_session_cache_destroy(cache); + std::exit(2); + } + break; + } + Check(response.outcome() == rg::DECISION_OUTCOME_UNAVAILABLE, + "resumed_probe_sentinel_response"); + client_delta_on_resume = client_verifier_calls->load() - client_verifier_calls_before; + server_delta_on_resume = server_verifier_calls->load() - server_verifier_calls_before; + const bool verifiers_ran = client_delta_on_resume > 0 && server_delta_on_resume > 0; + saw_resume_with_leaf_proof = client_leaf_exact && server_session_property_present && + server_reused && server_leaf_exact && verifiers_ran; + cache_handler_calls = server.service.calls.load(std::memory_order_acquire); + if (!saw_resume_with_leaf_proof || !new_transport || + cache_handler_calls != handler_calls_before + 1) { + std::cout << nlohmann::json{{"status", "unsafe_resumed_path_without_complete_proof"}, + {"actual_resumed", true}, {"new_transport", new_transport}, + {"client_leaf_pin", client_leaf_exact}, {"server_leaf_pin", server_leaf_exact}, + {"server_reused_property", server_session_property_present && server_reused}, + {"verifiers_ran", client_verifier_calls->load() > client_verifier_calls_before && + server_verifier_calls->load() > server_verifier_calls_before}, + {"handler_dispatched", cache_handler_calls == handler_calls_before + 1}}.dump() + << '\n'; + grpc_ssl_session_cache_destroy(cache); + std::exit(2); + } + break; + } + if (!status.ok()) { + if (attempt == 0) Fail("initial_session_probe_rpc_failed"); + break; + } + Check(response.outcome() == rg::DECISION_OUTCOME_UNAVAILABLE, + "session_probe_rpc_sentinel_response"); + peers.push_back(std::move(peer)); + // Scope exit destroys the channel/stub before the next forced transport. + } + if (saw_resume_with_leaf_proof && new_transport && client_leaf_exact_on_resume) { + std::cout << nlohmann::json{{"status", "qualified"}, {"actual_resumed", true}, + {"client_verifier_delta", client_delta_on_resume}, + {"server_verifier_delta", server_delta_on_resume}, + {"new_transport", true}, {"client_leaf_pin", true}, {"server_leaf_pin", true}, + {"uncached_reconnects_passed", true}, {"cache_attempts", cache_attempts}, + {"cache_capacity", 1}, + {"client_verifier_calls", client_verifier_calls->load()}, + {"server_verifier_calls", server_verifier_calls->load()}}.dump() << '\n'; + } else if (saw_resume_without_leaf_proof) { + std::cout << nlohmann::json{{"status", "not_qualified_no_dispatch_observed"}, + {"actual_resumed", true}, {"dispatch_unchanged", true}, + {"new_transport", new_transport}, {"uncached_reconnects_passed", true}, + {"cache_attempts", cache_attempts}, {"cache_capacity", 1}, + {"client_verifier_calls", client_verifier_calls->load()}, + {"server_verifier_calls", server_verifier_calls->load()}}.dump() << '\n'; + } else { + std::cout << nlohmann::json{{"status", "not_demonstrated"}, + {"actual_resumed", false}, {"max_attempts", 8}, + {"cache_attempts", cache_attempts}, {"uncached_reconnects_passed", true}, + {"cache_capacity", 1}, + {"client_verifier_calls", client_verifier_calls->load()}, + {"server_verifier_calls", server_verifier_calls->load()}}.dump() << '\n'; + } + grpc_ssl_session_cache_destroy(cache); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2 && argc != 3) Fail("usage"); + if (argc == 3 && std::string_view(argv[2]) != "--qualify-session") Fail("usage"); + try { + if (argc == 3 && std::string_view(argv[2]) == "--qualify-session") { + RunSessionCacheQualification(argv[1]); + return 0; + } + RunExpiryCase(argv[1], 48 * 60 * 60, 48 * 60 * 60, + true, false, false); + RunExpiryCase(argv[1], 60 * 60, 48 * 60 * 60, + false, true, false); + RunExpiryCase(argv[1], 48 * 60 * 60, 60 * 60, + false, false, true); + RunRetryAndReconnectCases(argv[1]); + RunChangedServerPinCase(argv[1]); + RunClientFactoryValidationCases(argv[1]); + RunAuthorityWrapperCase(argv[1], false); + RunAuthorityWrapperCase(argv[1], true); + } catch (const std::exception&) { + Fail("fixture_or_rpc_exception"); + } + std::cout << "PASS pinned_peer_rpc_client_fresh_guard" << '\n'; + return 0; +} diff --git a/tools/tests/policy_loader_integration.py b/tools/tests/policy_loader_integration.py new file mode 100644 index 0000000..8657b22 --- /dev/null +++ b/tools/tests/policy_loader_integration.py @@ -0,0 +1,548 @@ +"""End-to-end Python oracle for the CMake-built PolicyLoader/Codec/Digest driver.""" +from __future__ import annotations + +import copy +import hashlib +import json +import os +import subprocess +import tempfile +import unittest +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from policy_v1_oracle import digest, encode_policy, load_fixture + +QA_ROOT = Path(__file__).resolve().parents[2] +REPO_ROOT = Path(os.environ.get("RATEGUARD_REPO_ROOT", QA_ROOT)) +DRIVER = Path(os.environ.get("RATEGUARD_POLICY_DRIVER", REPO_ROOT / "build" / "policy_driver")) +FIXTURE = Path(os.environ.get( + "RATEGUARD_POLICY_FIXTURE", QA_ROOT / "tests" / "fixtures" / "policy_v1.json")) +CANONICAL_FIXTURE = Path(os.environ.get( + "RATEGUARD_CANONICAL_FIXTURE", + QA_ROOT / "tests" / "fixtures" / "policy_v1.canonical.hex")) + + +def run_driver(raw: str, timeout: int = 15) -> tuple[int, dict]: + with tempfile.NamedTemporaryFile("w", encoding="utf-8", suffix=".json") as file: + file.write(raw) + file.flush() + process = subprocess.run([str(DRIVER), file.name], capture_output=True, + text=True, timeout=timeout, check=False) + try: + result = json.loads(process.stdout) + except json.JSONDecodeError as exc: + raise AssertionError( + f"driver emitted invalid JSON (exit {process.returncode}): " + f"{process.stdout!r}; stderr={process.stderr!r}") from exc + return process.returncode, result + + +def call_valid(policy: dict) -> dict: + status, result = run_driver(json.dumps(policy, separators=(",", ":"), ensure_ascii=True)) + if status != 0 or result.get("status") != "ok": + raise AssertionError(f"valid policy rejected: rc={status}, result={result}") + expected_hex = encode_policy(policy).hex() + expected_digest = digest(policy) + if result.get("canonical_hex") != expected_hex: + raise AssertionError("production canonical bytes differ from independent oracle") + if result.get("sha256") != expected_digest: + raise AssertionError("production digest differs from independent SHA-256 oracle") + return result + + +def assert_rejected(test: unittest.TestCase, raw: str, label: str, code: str | None = None, + timeout: int = 15) -> None: + status, result = run_driver(raw, timeout=timeout) + test.assertNotEqual(status, 0, f"{label}: driver unexpectedly returned success") + test.assertEqual(result.get("status"), "error", f"{label}: expected structured error") + test.assertIn("code", result, f"{label}: error code absent") + if code is not None: + test.assertEqual(result["code"], code, f"{label}: wrong error category") + test.assertLessEqual(len(result.get("message", "")), 256, f"{label}: unbounded diagnostic") + + + +def compact_json(policy: dict) -> str: + return json.dumps(policy, separators=(",", ":"), ensure_ascii=True) + + +def minimal_policy(capacity: int = 1, rate: int = 1, cost: int = 1, + mode: str = "strict", credit_batch: int | None = None, + tenant_id: str = "tenant", operation_id: str = "op") -> dict: + authority_incarnation = "101112131415161718191a1b1c1d1e1f" + slot_id = 7 + slot_incarnation = "303132333435363738393a3b3c3d3e3f" + tenant = { + "tenant_id": tenant_id, + "capacity_units": str(capacity), + "rate_units_per_second": str(rate), + "operations": [{"operation_id": operation_id, "cost_units": str(cost)}], + } + if mode == "credit": + tenant["credit_batch_units"] = str(credit_batch if credit_batch is not None else cost) + return { + "schema_version": 1, + "mode": mode, + "epoch_id": "000102030405060708090a0b0c0d0e0f", + "authority_incarnation": authority_incarnation, + "trust_root_sha256": "fee742f3d97b519e6b7a8ee84b88b019cea856aadcd44d0dc2ac113852a6432f", + "replica_slots": [{"slot_id": slot_id, "incarnation_id": slot_incarnation}], + "tenants": [tenant], + "principals": [ + {"uri": "spiffe://rateguard.local/adapter/ingress1", + "role": "adapter", "permissions": []}, + {"uri": "spiffe://rateguard.local/authority/" + authority_incarnation, + "role": "authority", "permissions": []}, + {"uri": f"spiffe://rateguard.local/replica/{slot_id}/{slot_incarnation}", + "role": "replica", "slot_id": slot_id, "permissions": []}, + ], + } + + +def policy_with_slots(count: int) -> dict: + policy = minimal_policy() + policy["replica_slots"] = [] + policy["principals"] = [p for p in policy["principals"] if p["role"] != "replica"] + slot_ids = [2, 7, *range(10, 10 + max(0, count - 2))] + for slot_id in slot_ids[:count]: + incarnation = f"{slot_id + 100:032x}" + policy["replica_slots"].append({"slot_id": slot_id, "incarnation_id": incarnation}) + policy["principals"].append({ + "uri": f"spiffe://rateguard.local/replica/{slot_id}/{incarnation}", + "role": "replica", "slot_id": slot_id, "permissions": [], + }) + return policy + + +def policy_with_tenants(count: int, total_operations: int | None = None) -> dict: + policy = minimal_policy() + policy["tenants"] = [] + if total_operations is None: + total_operations = count + base, remainder = divmod(total_operations, count) + for tenant_index in range(count): + operation_count = base + (1 if tenant_index < remainder else 0) + policy["tenants"].append({ + "tenant_id": f"tenant{tenant_index:05d}", + "capacity_units": "1", + "rate_units_per_second": "1", + "operations": [ + {"operation_id": f"op{operation_index:03d}", "cost_units": "1"} + for operation_index in range(operation_count) + ], + }) + return policy + + +def policy_with_operations(count: int) -> dict: + policy = minimal_policy() + policy["tenants"][0]["operations"] = [ + {"operation_id": f"op{index:03d}", "cost_units": "1"} + for index in range(count) + ] + return policy + + +def policy_with_principals(count: int) -> dict: + policy = minimal_policy() + policy["principals"] = [ + principal for principal in policy["principals"] if principal["role"] != "adapter" + ] + for index in range(count - 2): + policy["principals"].append({ + "uri": f"spiffe://rateguard.local/adapter/agent{index:05d}", + "role": "adapter", "permissions": [], + }) + return policy + + +def policy_with_permissions(count: int) -> dict: + policy = minimal_policy() + policy["tenants"][0]["operations"] = [ + {"operation_id": f"op{index:02d}", "cost_units": "1"} + for index in range(64) + ] + policy["principals"] = [ + principal for principal in policy["principals"] if principal["role"] != "adapter" + ] + per_principal = 64 + full, remainder = divmod(count, per_principal) + adapter_count = full + (1 if remainder else 0) + for principal_index in range(adapter_count): + permission_count = per_principal if principal_index < full else remainder + policy["principals"].append({ + "uri": f"spiffe://rateguard.local/adapter/agent{principal_index:05d}", + "role": "adapter", + "permissions": [ + {"tenant_id": "tenant", + "operation_id": f"op{operation_index:02d}"} + for operation_index in range(permission_count) + ], + }) + return policy + + +def assert_accepted(test: unittest.TestCase, raw: str, label: str, + timeout: int = 60) -> dict: + status, result = run_driver(raw, timeout=timeout) + test.assertEqual(status, 0, f"{label}: expected accepted policy, got rc={status} {result}") + test.assertEqual(result.get("status"), "ok", f"{label}: expected success object") + canonical = result.get("canonical_hex") + sha = result.get("sha256") + test.assertIsInstance(canonical, str, f"{label}: missing canonical output") + test.assertTrue(canonical and len(canonical) % 2 == 0 and + all(c in "0123456789abcdef" for c in canonical), + f"{label}: malformed canonical output") + test.assertIsInstance(sha, str, f"{label}: missing SHA-256 output") + test.assertRegex(sha, r"^[0-9a-f]{64}$", f"{label}: malformed SHA-256 output") + return result + +def authority(policy: dict) -> dict: + return next(p for p in policy["principals"] if p["role"] == "authority") + + +def replica(policy: dict, slot: int) -> dict: + return next(p for p in policy["principals"] + if p["role"] == "replica" and p["slot_id"] == slot) + + +def adapter(policy: dict) -> dict: + return next(p for p in policy["principals"] if p["role"] == "adapter") + + +class PolicyLoaderIntegrationTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + if not DRIVER.is_file(): + raise FileNotFoundError(f"CMake-built production policy_driver is required: {DRIVER}") + if not FIXTURE.is_file(): + raise FileNotFoundError(f"policy fixture is required: {FIXTURE}") + if not CANONICAL_FIXTURE.is_file(): + raise FileNotFoundError(f"independent canonical hex fixture is required: {CANONICAL_FIXTURE}") + cls.policy = load_fixture(FIXTURE) + cls.expected_hex = encode_policy(cls.policy).hex() + cls.expected_sha = hashlib.sha256(bytes.fromhex(cls.expected_hex)).hexdigest() + frozen_hex = CANONICAL_FIXTURE.read_text(encoding="ascii").strip() + if not frozen_hex or any(c not in "0123456789abcdef" for c in frozen_hex): + raise ValueError(f"canonical fixture must be one lowercase hex line: {CANONICAL_FIXTURE}") + if frozen_hex != cls.expected_hex: + raise AssertionError("independent canonical hex fixture is stale or corrupt") + if cls.expected_sha != digest(cls.policy): + raise AssertionError("oracle digest cross-check failed") + + def test_aggregate_fixture_bytes_and_digest(self) -> None: + result = call_valid(self.policy) + self.assertEqual(result["canonical_hex"], self.expected_hex) + self.assertEqual(result["sha256"], self.expected_sha) + self.assertEqual(len(bytes.fromhex(result["canonical_hex"])), 580) + + def test_input_array_order_is_irrelevant(self) -> None: + changed = copy.deepcopy(self.policy) + changed["replica_slots"].reverse() + changed["tenants"].reverse() + changed["principals"].reverse() + for tenant in changed["tenants"]: + tenant["operations"].reverse() + adapter(changed)["permissions"].reverse() + result = call_valid(changed) + self.assertEqual(result["canonical_hex"], self.expected_hex) + self.assertEqual(result["sha256"], self.expected_sha) + + def test_valid_identity_authorization_and_quota_changes_change_digest(self) -> None: + candidates: list[tuple[str, dict]] = [] + + changed = copy.deepcopy(self.policy) + changed["epoch_id"] = "100102030405060708090a0b0c0d0e0f" + candidates.append(("epoch_id", changed)) + + changed = copy.deepcopy(self.policy) + changed["authority_incarnation"] = "111112131415161718191a1b1c1d1e1f" + authority(changed)["uri"] = ( + "spiffe://rateguard.local/authority/" + changed["authority_incarnation"]) + candidates.append(("authority incarnation/URI", changed)) + + changed = copy.deepcopy(self.policy) + changed["trust_root_sha256"] = ( + "0ee742f3d97b519e6b7a8ee84b88b019cea856aadcd44d0dc2ac113852a6432f") + candidates.append(("trust root fingerprint", changed)) + + changed = copy.deepcopy(self.policy) + slot = next(x for x in changed["replica_slots"] if x["slot_id"] == 7) + slot["incarnation_id"] = "404142434445464748494a4b4c4d4e4f" + replica(changed, 7)["uri"] = ( + "spiffe://rateguard.local/replica/7/" + slot["incarnation_id"]) + candidates.append(("slot incarnation", changed)) + + changed = copy.deepcopy(self.policy) + slot = next(x for x in changed["replica_slots"] if x["slot_id"] == 7) + slot["slot_id"] = 8 + replica(changed, 7)["slot_id"] = 8 + replica(changed, 8)["uri"] = ( + "spiffe://rateguard.local/replica/8/" + slot["incarnation_id"]) + candidates.append(("slot identity", changed)) + + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + zeta["tenant_id"] = "omega" + for principal in changed["principals"]: + for permission in principal["permissions"]: + if permission["tenant_id"] == "zeta": + permission["tenant_id"] = "omega" + candidates.append(("tenant identity", changed)) + + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + next(x for x in zeta["operations"] if x["operation_id"] == "list")["operation_id"] = "browse" + for permission in adapter(changed)["permissions"]: + if permission["tenant_id"] == "zeta" and permission["operation_id"] == "list": + permission["operation_id"] = "browse" + candidates.append(("operation identity", changed)) + + changed = copy.deepcopy(self.policy) + old_replica = replica(changed, 7) + changed["principals"].remove(old_replica) + former_adapter = adapter(changed) + incarnation = next(x for x in changed["replica_slots"] if x["slot_id"] == 7)["incarnation_id"] + former_adapter["role"] = "replica" + former_adapter["slot_id"] = 7 + former_adapter["uri"] = f"spiffe://rateguard.local/replica/7/{incarnation}" + changed["principals"].append({ + "uri": "spiffe://rateguard.local/adapter/ingress2", + "role": "adapter", + "permissions": [], + }) + candidates.append(("principal role", changed)) + + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + zeta["capacity_units"] = "21" + candidates.append(("capacity", changed)) + + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + zeta["rate_units_per_second"] = "4" + candidates.append(("rate", changed)) + + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + zeta["credit_batch_units"] = "7" + candidates.append(("credit batch", changed)) + + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + operation = next(x for x in zeta["operations"] if x["operation_id"] == "list") + operation["cost_units"] = "3" + candidates.append(("operation cost", changed)) + + changed = copy.deepcopy(self.policy) + adapter(changed)["uri"] = "spiffe://rateguard.local/adapter/ingress2" + candidates.append(("adapter principal URI", changed)) + + changed = copy.deepcopy(self.policy) + permission = adapter(changed)["permissions"][0] + permission["tenant_id"] = "alpha" + permission["operation_id"] = "write" + candidates.append(("permission", changed)) + + for label, candidate in candidates: + with self.subTest(field=label): + result = call_valid(candidate) + self.assertNotEqual(result["sha256"], self.expected_sha) + + def test_strict_policy_has_q_presence_zero_and_matches_oracle(self) -> None: + strict = copy.deepcopy(self.policy) + strict["mode"] = "strict" + for tenant in strict["tenants"]: + del tenant["credit_batch_units"] + result = call_valid(strict) + self.assertNotEqual(result["sha256"], self.expected_sha) + self.assertEqual(result["canonical_hex"], encode_policy(strict).hex()) + + def test_policy_unit_minimum_and_maximum_are_accepted(self) -> None: + minimum = minimal_policy(1, 1, 1, mode="credit", credit_batch=1) + call_valid(minimum) + maximum = minimal_policy( + 1_000_000_000, 1_000_000_000, 1_000_000_000, + mode="credit", credit_batch=1_000_000_000) + call_valid(maximum) + for field, value in (("capacity_units", "0"), + ("capacity_units", "1000000001"), + ("rate_units_per_second", "0"), + ("rate_units_per_second", "1000000001")): + invalid = copy.deepcopy(minimum) + invalid["tenants"][0][field] = value + assert_rejected(self, compact_json(invalid), f"{field}={value}", "invalid_value") + invalid = copy.deepcopy(maximum) + invalid["tenants"][0]["capacity_units"] = "18446744073709551616" + assert_rejected(self, compact_json(invalid), "capacity uint64 overflow", "invalid_value") + invalid = copy.deepcopy(maximum) + invalid["tenants"][0]["rate_units_per_second"] = "18446744073709551616" + assert_rejected(self, compact_json(invalid), "rate uint64 overflow", "invalid_value") + invalid = copy.deepcopy(maximum) + invalid["tenants"][0]["operations"][0]["cost_units"] = "18446744073709551616" + assert_rejected(self, compact_json(invalid), "cost uint64 overflow", "invalid_value") + slot_zero = copy.deepcopy(minimum) + slot_zero["replica_slots"][0]["slot_id"] = 0 + slot_zero["principals"][2]["slot_id"] = 0 + slot_zero["principals"][2]["uri"] = ( + "spiffe://rateguard.local/replica/0/" + + slot_zero["replica_slots"][0]["incarnation_id"]) + call_valid(slot_zero) + slot_max = copy.deepcopy(minimum) + slot_max["replica_slots"][0]["slot_id"] = 4_294_967_295 + slot_max["principals"][2]["slot_id"] = 4_294_967_295 + slot_max["principals"][2]["uri"] = ( + "spiffe://rateguard.local/replica/4294967295/" + + slot_max["replica_slots"][0]["incarnation_id"]) + call_valid(slot_max) + invalid = copy.deepcopy(minimum) + invalid["replica_slots"][0]["slot_id"] = 4_294_967_296 + invalid["principals"][2]["slot_id"] = 4_294_967_296 + assert_rejected(self, compact_json(invalid), "slot uint32 overflow", "invalid_value") + invalid = copy.deepcopy(minimum) + invalid["replica_slots"][0]["slot_id"] = "7" + assert_rejected(self, compact_json(invalid), "string slot_id", "invalid_value") + longest_ids = minimal_policy(tenant_id="a" * 128, operation_id="b" * 128) + call_valid(longest_ids) + too_long_tenant = minimal_policy(tenant_id="a" * 129) + assert_rejected(self, compact_json(too_long_tenant), "tenant identifier length 129", + "invalid_value") + too_long_operation = minimal_policy(operation_id="b" * 129) + assert_rejected(self, compact_json(too_long_operation), "operation identifier length 129", + "invalid_value") + + def test_slot_cap_accepts_eight_and_rejects_nine(self) -> None: + assert_accepted(self, compact_json(policy_with_slots(8)), "eight registered slots") + assert_rejected(self, compact_json(policy_with_slots(9)), "nine registered slots", + "resource_limit") + + def test_tenant_cap_accepts_ten_thousand_and_rejects_ten_thousand_one(self) -> None: + assert_accepted(self, compact_json(policy_with_tenants(10_000)), + "10,000 configured tenants") + assert_rejected(self, compact_json(policy_with_tenants(10_001)), + "10,001 configured tenants", "resource_limit") + + def test_operation_caps_accept_boundary_and_reject_overflow(self) -> None: + assert_accepted(self, compact_json(policy_with_operations(64)), + "64 operations for one tenant") + assert_rejected(self, compact_json(policy_with_operations(65)), + "65 operations for one tenant", "resource_limit") + assert_accepted(self, compact_json(policy_with_tenants(10_000, 100_000)), + "100,000 operations total") + assert_rejected(self, compact_json(policy_with_tenants(10_000, 100_001)), + "100,001 operations total", "resource_limit") + + def test_principal_cap_accepts_ten_thousand_and_rejects_ten_thousand_one(self) -> None: + assert_accepted(self, compact_json(policy_with_principals(10_000)), + "10,000 registered principals") + assert_rejected(self, compact_json(policy_with_principals(10_001)), + "10,001 registered principals", "resource_limit") + + def test_permission_cap_accepts_one_hundred_thousand_and_rejects_overflow(self) -> None: + assert_accepted(self, compact_json(policy_with_permissions(100_000)), + "100,000 permission pairs") + assert_rejected(self, compact_json(policy_with_permissions(100_001)), + "100,001 permission pairs", "resource_limit") + + def test_rejects_duplicate_unknown_and_malformed_json(self) -> None: + original = FIXTURE.read_text(encoding="utf-8") + duplicate_key = original.replace( + '"mode": "credit",', '"mode": "credit",\n "mode": "credit",', 1) + assert_rejected(self, duplicate_key, "duplicate root key", "invalid_json") + unknown_root = copy.deepcopy(self.policy) + unknown_root["unexpected"] = True + assert_rejected(self, compact_json(unknown_root), "unknown root field", "invalid_schema") + assert_rejected(self, original + "\n{}", "trailing JSON value", "invalid_json") + assert_rejected(self, '{"schema_version":', "truncated malformed JSON", "invalid_json") + assert_rejected(self, original.replace('"schema_version": 1', '"schema_version": 2'), + "unsupported schema version", "invalid_schema") + assert_rejected(self, original.replace('"schema_version": 1', '"schema_version": true'), + "boolean schema version", "invalid_value") + assert_rejected(self, original.replace('"schema_version": 1', '"schema_version": -1'), + "negative schema version", "invalid_value") + assert_rejected(self, original.replace('"schema_version": 1', '"schema_version": 1.0'), + "float schema version", "invalid_json") + assert_rejected(self, original.replace('"capacity_units": "20"', '"capacity_units": 20.0'), + "float policy value", "invalid_json") + assert_rejected(self, original.replace('"capacity_units": "20"', '"capacity_units": "020"'), + "noncanonical decimal", "invalid_value") + + def test_rejects_unknown_permission_and_operation_cost_bounds(self) -> None: + changed = copy.deepcopy(self.policy) + adapter(changed)["permissions"][0]["tenant_id"] = "missing" + assert_rejected(self, json.dumps(changed), "unknown permission tenant", "invalid_value") + changed = copy.deepcopy(self.policy) + adapter(changed)["permissions"][0]["operation_id"] = "missing" + assert_rejected(self, json.dumps(changed), "unknown permission operation", "invalid_value") + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + next(x for x in zeta["operations"] if x["operation_id"] == "list")["cost_units"] = "21" + assert_rejected(self, json.dumps(changed), "operation cost exceeds capacity", "invalid_value") + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + zeta["credit_batch_units"] = "5" + assert_rejected(self, json.dumps(changed), "batch below maximum operation cost", "invalid_value") + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + zeta["credit_batch_units"] = "21" + assert_rejected(self, json.dumps(changed), "batch above capacity", "invalid_value") + changed = copy.deepcopy(self.policy) + zeta = next(x for x in changed["tenants"] if x["tenant_id"] == "zeta") + next(x for x in zeta["operations"] if x["operation_id"] == "list")["cost_units"] = "0" + assert_rejected(self, json.dumps(changed), "zero operation cost", "invalid_value") + + def test_rejects_duplicate_slots_unknown_slots_and_identity_mismatches(self) -> None: + changed = copy.deepcopy(self.policy) + changed["replica_slots"].append(copy.deepcopy(changed["replica_slots"][0])) + assert_rejected(self, json.dumps(changed), "duplicate slot", "invalid_value") + changed = copy.deepcopy(self.policy) + replica(changed, 7)["slot_id"] = 99 + assert_rejected(self, json.dumps(changed), "unknown replica slot", "invalid_value") + changed = copy.deepcopy(self.policy) + replica(changed, 7)["uri"] = "spiffe://rateguard.local/replica/7/" + "f" * 32 + assert_rejected(self, json.dumps(changed), "replica URI incarnation mismatch", "invalid_value") + changed = copy.deepcopy(self.policy) + slot = next(x for x in changed["replica_slots"] if x["slot_id"] == 7) + slot["incarnation_id"] = "404142434445464748494a4b4c4d4e4f" + assert_rejected(self, json.dumps(changed), "slot incarnation and replica URI mismatch", "invalid_value") + changed = copy.deepcopy(self.policy) + authority(changed)["uri"] = "spiffe://rateguard.local/authority/" + "f" * 32 + assert_rejected(self, json.dumps(changed), "authority URI mismatch", "invalid_value") + changed = copy.deepcopy(self.policy) + adapter(changed)["uri"] = "spiffe://other.local/adapter/ingress1" + assert_rejected(self, json.dumps(changed), "adapter URI mismatch", "invalid_value") + changed = copy.deepcopy(self.policy) + replica(changed, 7)["slot_id"] = 7.0 + assert_rejected(self, json.dumps(changed), "float replica slot id", "invalid_json") + changed = copy.deepcopy(self.policy) + replica(changed, 7)["slot_id"] = True + assert_rejected(self, json.dumps(changed), "boolean replica slot id", "invalid_value") + changed = copy.deepcopy(self.policy) + changed["tenants"][0]["unknown"] = 1 + assert_rejected(self, json.dumps(changed), "unknown nested field", "invalid_schema") + changed = copy.deepcopy(self.policy) + changed["principals"].append(copy.deepcopy(changed["principals"][0])) + assert_rejected(self, json.dumps(changed), "duplicate principal URI", "invalid_value") + changed = copy.deepcopy(self.policy) + adapter(changed)["permissions"].append(copy.deepcopy(adapter(changed)["permissions"][0])) + assert_rejected(self, json.dumps(changed), "duplicate permission", "invalid_value") + changed = copy.deepcopy(self.policy) + changed["tenants"].append(copy.deepcopy(changed["tenants"][0])) + assert_rejected(self, json.dumps(changed), "duplicate tenant", "invalid_value") + + def test_rejects_strict_credit_q_presence_mismatch_and_depth_limit(self) -> None: + strict_with_q = copy.deepcopy(self.policy) + strict_with_q["mode"] = "strict" + assert_rejected(self, json.dumps(strict_with_q), "strict tenant has credit batch") + credit_without_q = copy.deepcopy(self.policy) + for tenant in credit_without_q["tenants"]: + del tenant["credit_batch_units"] + assert_rejected(self, json.dumps(credit_without_q), "credit tenant missing batch") + too_deep = '{"outer":' * 34 + '0' + '}' * 34 + assert_rejected(self, too_deep, "excessive nesting") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/root_pin_mutation_test.py b/tools/tests/root_pin_mutation_test.py new file mode 100644 index 0000000..9f22b9e --- /dev/null +++ b/tools/tests/root_pin_mutation_test.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Prove the independent registry acceptance test catches a root-pin defect.""" +from __future__ import annotations + +import argparse +import re +import subprocess + +PEM_ARMOR = re.compile(rb"-----BEGIN [A-Z0-9 ]{1,80}-----") +MAX_OUTPUT = 64 * 1024 +PASS_LINE = b"PASS registry_valid_binding_negative_identity_eku_time_caps" +MUTANT_FAILURE = b"FAIL wrong_root_digest_rejected" + + +def run(path: str, fixture: str) -> subprocess.CompletedProcess[bytes]: + return subprocess.run([path, fixture], stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=120, check=False) + + +def safe_output(result: subprocess.CompletedProcess[bytes]) -> bytes: + output = result.stdout + result.stderr + if len(output) > MAX_OUTPUT: + raise SystemExit("registry child output exceeded 64 KiB; withheld") + if PEM_ARMOR.search(output): + raise SystemExit("registry child output contained PEM armor; withheld") + return output + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--normal", required=True) + parser.add_argument("--mutant", required=True) + parser.add_argument("--fixture", required=True) + args = parser.parse_args() + + normal = run(args.normal, args.fixture) + normal_output = safe_output(normal) + if normal.returncode != 0 or normal_output.strip() != PASS_LINE: + raise SystemExit("normal registry fixture suite failed; child output withheld") + + mutant = run(args.mutant, args.fixture) + mutant_output = safe_output(mutant) + if mutant.returncode == 0 or mutant_output.strip() != MUTANT_FAILURE: + raise SystemExit("wrong-root-pin mutant escaped expected independent check; child output withheld") + print("PASS independent registry suite detects root-pin bypass mutant") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/tests/test_history_retention.py b/tools/tests/test_history_retention.py new file mode 100644 index 0000000..a058607 --- /dev/null +++ b/tools/tests/test_history_retention.py @@ -0,0 +1,36 @@ +import importlib.util +import tempfile +import unittest +from pathlib import Path + +module_path = Path(__file__).resolve().parents[1] / "history" / "retention.py" +spec = importlib.util.spec_from_file_location("retention", module_path) +retention = importlib.util.module_from_spec(spec) +spec.loader.exec_module(retention) + + +class RetentionTest(unittest.TestCase): + def test_exact_boundary_and_file_scope(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + def managed(second, digit): + return root / f"rg-history-v1-{second}-{digit * 32}.bin" + + expired, recent = managed(100, "a"), managed(101, "a") + unrelated, link, directory = root / "report.json", managed(99, "b"), managed(99, "c") + partial = Path(str(managed(100, "d")) + ".partial") + fresh_partial = Path(str(managed(101, "d")) + ".partial") + unrelated_partial = root / "notes.bin.partial" + for file in (expired, recent, unrelated, partial, fresh_partial, unrelated_partial): + file.write_bytes(b"synthetic") + link.symlink_to(unrelated) + directory.mkdir() + now = 100 + retention.RETENTION_SECONDS + self.assertEqual(retention.expire_local_exports(root, now), 2) + self.assertFalse(expired.exists()) + self.assertEqual(set(root.iterdir()), {recent, fresh_partial, unrelated, unrelated_partial, link, directory}) + self.assertEqual(retention.expire_local_exports(root, now), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_policy_v1_oracle.py b/tools/tests/test_policy_v1_oracle.py new file mode 100644 index 0000000..4d7f2c5 --- /dev/null +++ b/tools/tests/test_policy_v1_oracle.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import copy +import os +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from policy_v1_oracle import digest, encode_policy, load_fixture # noqa: E402 + +FIXTURE = Path(os.environ.get( + "RATEGUARD_POLICY_FIXTURE", + str(Path(__file__).resolve().parents[2] / "tests" / "fixtures" / "policy_v1.json"))) +EXPECTED_LENGTH = 580 +EXPECTED_SHA256 = "0fa75c3373b71fc7c21ce0417258ea6545986d884c69c16f2ee8d6d9fefe00ff" + + +class IndependentPolicyOracleTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + if not FIXTURE.is_file(): + raise FileNotFoundError(f"aggregate policy fixture missing: {FIXTURE}") + cls.policy = load_fixture(FIXTURE) + cls.encoded = encode_policy(cls.policy) + + def test_frozen_aggregate_golden(self) -> None: + self.assertEqual(len(self.encoded), EXPECTED_LENGTH) + self.assertEqual(digest(self.policy), EXPECTED_SHA256) + + def test_input_table_order_does_not_change_canonical_bytes(self) -> None: + changed = copy.deepcopy(self.policy) + changed["replica_slots"].reverse() + changed["tenants"].reverse() + changed["principals"].reverse() + for tenant in changed["tenants"]: + tenant["operations"].reverse() + next(p for p in changed["principals"] if p["role"] == "adapter")["permissions"].reverse() + self.assertEqual(encode_policy(changed), self.encoded) + + def test_identity_quota_and_permission_changes_affect_digest(self) -> None: + variations = [] + + def alter(name, path, value): + candidate = copy.deepcopy(self.policy) + target = candidate + for key in path[:-1]: + target = target[key] + target[path[-1]] = value + variations.append((name, candidate)) + + alter("epoch", ["epoch_id"], "100102030405060708090a0b0c0d0e0f") + alter("trust root", ["trust_root_sha256"], + "0ee742f3d97b519e6b7a8ee84b88b019cea856aadcd44d0dc2ac113852a6432f") + alter("tenant capacity", ["tenants", 0, "capacity_units"], "21") + alter("tenant rate", ["tenants", 0, "rate_units_per_second"], "4") + alter("credit batch", ["tenants", 0, "credit_batch_units"], "7") + alter("operation cost", ["tenants", 0, "operations", 0, "cost_units"], "3") + alter("adapter URI", ["principals", 1, "uri"], + "spiffe://rateguard.local/adapter/ingress2") + permission_change = copy.deepcopy(self.policy) + permission_change["principals"][1]["permissions"][0] = { + "tenant_id": "alpha", "operation_id": "write"} + variations.append(("permission", permission_change)) + + for label, candidate in variations: + with self.subTest(field=label): + self.assertNotEqual(digest(candidate), EXPECTED_SHA256) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_verify_build_manifest.py b/tools/tests/test_verify_build_manifest.py new file mode 100644 index 0000000..8356b2a --- /dev/null +++ b/tools/tests/test_verify_build_manifest.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from verify_build_manifest import verify # noqa: E402 + + +def valid_inputs() -> tuple[dict, dict]: + # Deliberately synthetic versions; these tests do not assert an environment. + packages = { + "nlohmann-json3-dev": "3.11.3-fixture", + "libgrpc++-dev": "1.51.1-3build1", + "libgrpc-dev": "1.51.1-3build1", + "libprotobuf-dev": "3.21.12-8.2ubuntu0.2", + "protobuf-compiler": "3.21.12-8.2ubuntu0.2", + "protobuf-compiler-grpc": "1.51.1-3build1", + "libssl-dev": "3.0.13-0ubuntu3.1", + "zlib1g-dev": "1:1.3.dfsg-3.1ubuntu2", + } + lock = { + "schema_version": 1, + "lock_status": "frozen_pending_verification", + "target": { + "runner_label": "ubuntu-24.04", + "os_id": "ubuntu", + "os_version_id": "24.04", + "architecture": "x86_64", + "language_standard": "C++20", + "dependency_mode": "ubuntu-packages", + }, + "tools": { + "cmake": "cmake version 3.31.6", + "ninja": "1.11.1", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0", + "protoc": "libprotoc 3.21.12", + }, + "dependencies": {"package_versions": packages}, + "validation": {"validated": False}, + } + manifest = { + "manifest_schema_version": 1, + "lock_status": "frozen_pending_verification", + "build_result": "passed", + "source": {"git_commit": "a" * 40}, + "build_configuration": { + "cxx_standard": "C++20", + "project_compile_commands_count": 3, + }, + "runner": { + "label_requested": "ubuntu-24.04", + "machine": "x86_64", + "os_release": {"ID": "ubuntu", "VERSION_ID": "24.04"}, + }, + "tools": { + "cmake": "cmake version 3.31.6", + "ninja": "1.11.1", + "cxx_compiler": "c++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0", + "protoc": "libprotoc 3.21.12", + }, + "system_packages": { + "nlohmann_json_dev": packages["nlohmann-json3-dev"], + "libgrpcpp_dev": packages["libgrpc++-dev"], + "libgrpc_dev": packages["libgrpc-dev"], + "libprotobuf_dev": packages["libprotobuf-dev"], + "protobuf_compiler": packages["protobuf-compiler"], + "protobuf_compiler_grpc": packages["protobuf-compiler-grpc"], + "libssl_dev": packages["libssl-dev"], + "zlib1g_dev": packages["zlib1g-dev"], + }, + "dependency_mode": "system_packages", + } + return lock, manifest + + +class VerifyBuildManifestTests(unittest.TestCase): + def test_matching_manifest_passes(self) -> None: + lock, manifest = valid_inputs() + self.assertEqual(verify(lock, manifest), []) + + def test_package_version_drift_fails(self) -> None: + lock, manifest = valid_inputs() + manifest["system_packages"]["libgrpc_dev"] = "different-version" + self.assertTrue(any("package version mismatch for libgrpc-dev" in e for e in verify(lock, manifest))) + + def test_json_package_version_drift_fails(self) -> None: + lock, manifest = valid_inputs() + manifest["system_packages"]["nlohmann_json_dev"] = "different-version" + self.assertTrue(any("package version mismatch for nlohmann-json3-dev" in e for e in verify(lock, manifest))) + + def test_tool_version_drift_fails(self) -> None: + lock, manifest = valid_inputs() + manifest["tools"]["protoc"] = "libprotoc 99.0" + self.assertTrue(any("protoc version mismatch" in e for e in verify(lock, manifest))) + + def test_target_os_or_arch_drift_fails(self) -> None: + lock, manifest = valid_inputs() + manifest["runner"]["machine"] = "aarch64" + self.assertTrue(any("architecture mismatch" in e for e in verify(lock, manifest))) + + def test_language_standard_mismatch_fails(self) -> None: + lock, manifest = valid_inputs() + manifest["build_configuration"]["cxx_standard"] = "gnu++17" + self.assertTrue(any("must both be 'C++20'" in e for e in verify(lock, manifest))) + + def test_missing_or_zero_project_compile_commands_fail(self) -> None: + lock, manifest = valid_inputs() + manifest["build_configuration"]["project_compile_commands_count"] = 0 + self.assertTrue(any("must be a positive integer" in e for e in verify(lock, manifest))) + del manifest["build_configuration"]["cxx_standard"] + self.assertTrue(any("must both be 'C++20'" in e for e in verify(lock, manifest))) + + def test_missing_expected_or_observed_values_fail(self) -> None: + lock, manifest = valid_inputs() + del lock["tools"]["cxx_compiler"] + manifest["system_packages"]["protobuf_compiler"] = None + errors = verify(lock, manifest) + self.assertTrue(any("tool version cxx_compiler is missing" in e for e in errors)) + self.assertTrue(any("package version protobuf-compiler is missing" in e for e in errors)) + + def test_failed_build_fails(self) -> None: + lock, manifest = valid_inputs() + manifest["build_result"] = "failed" + self.assertTrue(any("build_result must be 'passed'" in e for e in verify(lock, manifest))) + + def test_missing_source_commit_fails(self) -> None: + lock, manifest = valid_inputs() + manifest["source"]["git_commit"] = None + self.assertTrue(any("source.git_commit is required" in e for e in verify(lock, manifest))) + + def test_frozen_complete_lock_can_match_before_repeat_validation(self) -> None: + lock, manifest = valid_inputs() + self.assertEqual(verify(lock, manifest), []) + + def test_candidate_or_empty_lock_fails_closed(self) -> None: + lock, manifest = valid_inputs() + lock["lock_status"] = "candidate_unvalidated" + lock["dependencies"]["package_versions"] = {} + errors = verify(lock, manifest) + self.assertTrue(any("candidate locks cannot pass" in e for e in errors)) + self.assertTrue(any("package_versions must be populated" in e for e in errors)) + + def test_inconsistent_validation_flags_fail(self) -> None: + lock, manifest = valid_inputs() + lock["lock_status"] = "validated" + lock["validation"]["validated"] = False + manifest["lock_status"] = "validated" + self.assertTrue(any("validated lock requires" in e for e in verify(lock, manifest))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/trusted_wall_clock_independent_test.cpp b/tools/tests/trusted_wall_clock_independent_test.cpp new file mode 100644 index 0000000..80461a6 --- /dev/null +++ b/tools/tests/trusted_wall_clock_independent_test.cpp @@ -0,0 +1,204 @@ +#include "security/trusted_wall_clock.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rateguard::security; + +namespace { +int failures = 0; +void Expect(bool ok, const char* label) { + if (!ok) { std::cerr << "FAIL: " << label << '\n'; ++failures; } +} +TrustedWallClockFailure Error(TrustedWallClockFailureReason reason) { + return {reason}; +} +template bool FailedAs(const TrustedWallClockResult& value, + TrustedWallClockFailureReason reason) { + const auto* e = std::get_if(&value); + return e && e->reason == reason; +} + +void CommitmentMappingCases() { + using namespace rateguard::v1::contract; + const TrustedWallClockFailure failure{TrustedWallClockFailureReason::ClockErrorFlag}; + for (const auto phase : {Commitment::NotCommitted, Commitment::Possible, + Commitment::Committed}) { + const auto mapped = failure.ToServiceError(phase); + Expect(mapped.category == ErrorCategory::Dependency && + mapped.code == ErrorCode::Unavailable && + mapped.retry == RetryDisposition::Never && mapped.commitment == phase, + "wall-clock failures preserve explicitly supplied commitment phase"); + } + const auto post_allow = failure.ToServiceError(Commitment::Committed); + Expect(post_allow.commitment == Commitment::Committed, + "post-ALLOW clock trust loss cannot erase known committed outcome"); +} + +class FakePlatform final : public ITrustedWallClockPlatform { + public: + struct Counters { std::atomic sync_calls{0}; std::atomic time_calls{0}; }; + std::shared_ptr counters = std::make_shared(); + std::deque> syncs; + std::deque> times; + TrustedWallClockResult ReadSynchronization() override { + ++counters->sync_calls; + if (syncs.empty()) return SynchronizationStatus{0,0}; + auto result=std::move(syncs.front()); syncs.pop_front(); return result; + } + TrustedWallClockResult ReadRealtime() override { + ++counters->time_calls; + if (times.empty()) return RawWallTime{100,0}; + auto result=std::move(times.front()); times.pop_front(); return result; + } +}; +auto Create(std::unique_ptr p) { + return TrustedWallClock::Create(std::unique_ptr(std::move(p))); +} + +void StateAndFlagCases() { + for (std::int32_t state=0; state<=4; ++state) { + auto p=std::make_unique(); + p->syncs={SynchronizationStatus{state,0}}; + p->times={RawWallTime{1700000000,123},RawWallTime{1700000001,0}}; + auto c=Create(std::move(p)); + auto* clock=std::get_if>(&c); + Expect(clock && (*clock)->Healthy(), "synchronization states 0..4 accepted after initial sample"); + if (clock) { + auto n=(*clock)->Now(); + Expect(std::get_if(&n)!=nullptr, "accepted synchronization state permits later sample"); + } + } + auto time_error=std::make_unique(); + time_error->syncs={SynchronizationStatus{5,0}}; + Expect(FailedAs(Create(std::move(time_error)),TrustedWallClockFailureReason::TimeErrorState), + "TIME_ERROR state fails before factory readiness"); + for (std::int32_t state : {-1,6,std::numeric_limits::max()}) { + auto unknown=std::make_unique(); unknown->syncs={SynchronizationStatus{state,0}}; + Expect(FailedAs(Create(std::move(unknown)),TrustedWallClockFailureReason::UnknownState), + "unknown synchronization state fails closed"); + } + auto unsync=std::make_unique(); unsync->syncs={SynchronizationStatus{0,0x0040}}; + Expect(FailedAs(Create(std::move(unsync)),TrustedWallClockFailureReason::UnsynchronizedFlag), + "STA_UNSYNC fails closed"); + auto clockerr=std::make_unique(); clockerr->syncs={SynchronizationStatus{0,0x1000}}; + Expect(FailedAs(Create(std::move(clockerr)),TrustedWallClockFailureReason::ClockErrorFlag), + "STA_CLOCKERR fails closed"); + auto both=std::make_unique(); both->syncs={SynchronizationStatus{0,0x1040}}; + Expect(FailedAs(Create(std::move(both)),TrustedWallClockFailureReason::UnsynchronizedFlag), + "combined rejected flags fail with deterministic first reason"); + auto other=std::make_unique(); other->syncs={SynchronizationStatus{4,0x0002}}; + Expect(std::holds_alternative>(Create(std::move(other))), + "unrelated status flags do not cause false distrust"); +} + +void InitialReadAndNumericCases() { + auto unavailable=std::make_unique(); + unavailable->syncs={Error(TrustedWallClockFailureReason::SynchronizationSyscall)}; + Expect(FailedAs(Create(std::move(unavailable)),TrustedWallClockFailureReason::SynchronizationSyscall), + "initial adjtimex failure blocks readiness"); + auto time_failure=std::make_unique(); + time_failure->times={Error(TrustedWallClockFailureReason::RealtimeSyscall)}; + Expect(FailedAs(Create(std::move(time_failure)),TrustedWallClockFailureReason::RealtimeSyscall), + "initial realtime failure blocks readiness"); + + const std::array invalid{{{-1,0},{0,-1},{0,1'000'000'000}, + {std::numeric_limits::min(),0},{1, std::numeric_limits::max()}}}; + for (const auto raw : invalid) { + auto p=std::make_unique(); p->times={raw}; + Expect(std::holds_alternative(Create(std::move(p))), + "invalid initial wall sample blocks readiness"); + } + auto max_ok=std::make_unique(); + max_ok->times={RawWallTime{std::numeric_limits::max(),999'999'999}}; + auto max_clock=Create(std::move(max_ok)); + Expect(std::holds_alternative>(max_clock), + "maximum representable trusted wall time is accepted"); + auto boundary=std::make_unique(); boundary->times={RawWallTime{0,0}}; + auto c=Create(std::move(boundary)); + Expect(std::holds_alternative>(c), "Unix epoch boundary is valid"); +} + +void StickyAndOrderingCases() { + auto p=std::make_unique(); + p->syncs={SynchronizationStatus{0,0},SynchronizationStatus{5,0},SynchronizationStatus{0,0}}; + p->times={RawWallTime{100,0},RawWallTime{101,0},RawWallTime{102,0}}; + auto c=Create(std::move(p)); auto* ptr=std::get_if>(&c); + Expect(ptr && (*ptr)->Healthy(), "valid startup clock healthy"); + if (ptr) { + Expect(FailedAs((*ptr)->Now(),TrustedWallClockFailureReason::TimeErrorState), + "live TIME_ERROR latches failure"); + Expect(!(*ptr)->Healthy(), "latched wall-clock failure clears health"); + Expect(FailedAs((*ptr)->Now(),TrustedWallClockFailureReason::TimeErrorState), + "first error remains sticky without recovery"); + } + auto backwards=std::make_unique(); + backwards->times={RawWallTime{100,1},RawWallTime{100,0}}; + auto bc=Create(std::move(backwards)); auto* bp=std::get_if>(&bc); + if (bp) Expect(FailedAs((*bp)->Now(),TrustedWallClockFailureReason::BackwardsRead), + "backward UTC observation latches trust loss"); + else Expect(false,"backward scenario initialized"); + auto equal=std::make_unique(); equal->times={RawWallTime{100,7},RawWallTime{100,7}}; + auto ec=Create(std::move(equal)); auto* ep=std::get_if>(&ec); + if (ep) Expect(std::holds_alternative((*ep)->Now()),"equal realtime observations are legal"); + else Expect(false,"equal scenario initialized"); + auto short_circuit=std::make_unique(); + short_circuit->syncs={Error(TrustedWallClockFailureReason::SynchronizationSyscall)}; + auto counts=short_circuit->counters; + (void)Create(std::move(short_circuit)); + Expect(counts->time_calls.load()==0,"failed status check does not read realtime"); +} + +void ConcurrentSerializationCase() { + constexpr std::size_t n = 24; + auto p=std::make_unique(); + p->syncs.emplace_back(SynchronizationStatus{0,0}); + p->times.emplace_back(RawWallTime{100,0}); + for (std::size_t i=1;i<=n;++i) { + p->syncs.emplace_back(SynchronizationStatus{0,0}); + p->times.emplace_back(RawWallTime{100+static_cast(i),0}); + } + auto result=Create(std::move(p)); + auto* clock=std::get_if>(&result); + Expect(clock!=nullptr,"concurrency fixture creates trusted clock"); + if (!clock) return; + std::array values{}; + std::array ok{}; + std::array threads; + for (std::size_t i=0;iNow(); + if (const auto* value=std::get_if(&sample)) { + values[i]=value->unix_seconds; + ok[i]=true; + } + }); + } + for (auto& thread:threads) thread.join(); + for (bool success:ok) Expect(success,"serialized concurrent realtime query succeeds"); + std::sort(values.begin(),values.end()); + for (std::size_t i=0;i(i),"concurrent samples preserve increasing source order"); +} + +} // namespace + +int main() { + CommitmentMappingCases(); + StateAndFlagCases(); + InitialReadAndNumericCases(); + StickyAndOrderingCases(); + ConcurrentSerializationCase(); + if (failures != 0) return EXIT_FAILURE; + std::cout << "independent trusted wall-clock checks passed\n"; + return EXIT_SUCCESS; +} diff --git a/tools/verify_build_manifest.py b/tools/verify_build_manifest.py new file mode 100644 index 0000000..e72050b --- /dev/null +++ b/tools/verify_build_manifest.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +"""Fail closed unless an observed build manifest matches the validated build lock.""" +from __future__ import annotations + +import argparse +import json +import re +import sys +from pathlib import Path +from typing import Any + + +PACKAGE_FIELDS = { + "nlohmann-json3-dev": "nlohmann_json_dev", + "libgrpc++-dev": "libgrpcpp_dev", + "libgrpc-dev": "libgrpc_dev", + "libprotobuf-dev": "libprotobuf_dev", + "protobuf-compiler": "protobuf_compiler", + "protobuf-compiler-grpc": "protobuf_compiler_grpc", + "libssl-dev": "libssl_dev", + "zlib1g-dev": "zlib1g_dev", +} + + +def _get(data: dict[str, Any], *path: str) -> Any: + value: Any = data + for part in path: + if not isinstance(value, dict) or part not in value: + return None + value = value[part] + return value + + +def _nonempty_string(value: Any) -> bool: + return isinstance(value, str) and bool(value.strip()) + + +def _cmake_version(value: Any) -> str | None: + if not _nonempty_string(value): + return None + match = re.search(r"(?:cmake version\s+)?(\d+\.\d+(?:\.\d+)+)", value, re.IGNORECASE) + return match.group(1) if match else None + + +def verify(lock: dict[str, Any], manifest: dict[str, Any]) -> list[str]: + """Return every mismatch; an empty result means exact validated-lock match.""" + errors: list[str] = [] + + if lock.get("schema_version") != 1: + errors.append("lock.schema_version must be 1") + lock_status = lock.get("lock_status") + if lock_status not in ("frozen_pending_verification", "validated"): + errors.append("lock.lock_status must be 'frozen_pending_verification' or 'validated'; candidate locks cannot pass") + validation_flag = _get(lock, "validation", "validated") + if lock_status == "validated" and validation_flag is not True: + errors.append("validated lock requires lock.validation.validated=true") + if lock_status == "frozen_pending_verification" and validation_flag is not False: + errors.append("frozen_pending_verification lock requires lock.validation.validated=false") + if manifest.get("manifest_schema_version") != 1: + errors.append("manifest.manifest_schema_version must be 1") + if manifest.get("build_result") != "passed": + errors.append("manifest.build_result must be 'passed'") + if manifest.get("lock_status") != lock_status: + errors.append(f"manifest.lock_status must match lock status {lock_status!r}") + if not _nonempty_string(_get(manifest, "source", "git_commit")): + errors.append("manifest.source.git_commit is required") + + target = lock.get("target") + if not isinstance(target, dict): + errors.append("lock.target must be an object") + target = {} + runner = manifest.get("runner") + if not isinstance(runner, dict): + errors.append("manifest.runner must be an object") + runner = {} + expected_runner = target.get("runner_label") + observed_runner = runner.get("label_requested") + if not _nonempty_string(expected_runner) or not _nonempty_string(observed_runner): + errors.append("target.runner_label and runner.label_requested are required") + elif expected_runner != observed_runner: + errors.append(f"runner label mismatch: expected {expected_runner!r}, observed {observed_runner!r}") + + expected_os = target.get("os_id") + observed_os = _get(runner, "os_release", "ID") + if not _nonempty_string(expected_os) or not _nonempty_string(observed_os): + errors.append("target.os_id and runner.os_release.ID are required") + elif expected_os.lower() != observed_os.lower(): + errors.append(f"OS ID mismatch: expected {expected_os!r}, observed {observed_os!r}") + + expected_os_version = target.get("os_version_id") + observed_os_version = _get(runner, "os_release", "VERSION_ID") + if not _nonempty_string(expected_os_version) or not _nonempty_string(observed_os_version): + errors.append("target.os_version_id and runner.os_release.VERSION_ID are required") + elif expected_os_version != observed_os_version: + errors.append(f"OS version mismatch: expected {expected_os_version!r}, observed {observed_os_version!r}") + + expected_arch = target.get("architecture") + observed_arch = runner.get("machine") + if not _nonempty_string(expected_arch) or not _nonempty_string(observed_arch): + errors.append("target.architecture and runner.machine are required") + elif expected_arch != observed_arch: + errors.append(f"architecture mismatch: expected {expected_arch!r}, observed {observed_arch!r}") + + expected_standard = target.get("language_standard") + observed_build = manifest.get("build_configuration") + if not isinstance(observed_build, dict): + errors.append("manifest.build_configuration must be an object") + observed_build = {} + observed_standard = observed_build.get("cxx_standard") + if expected_standard != "C++20" or observed_standard != "C++20": + errors.append("lock.target.language_standard and manifest.build_configuration.cxx_standard must both be 'C++20'") + compile_count = observed_build.get("project_compile_commands_count") + if not isinstance(compile_count, int) or isinstance(compile_count, bool) or compile_count <= 0: + errors.append("manifest.build_configuration.project_compile_commands_count must be a positive integer") + + # Exact tool versions have one canonical location; legacy target fallback + # must not hide an absent or malformed lock.tools object. + tools = lock.get("tools") + observed_tools = manifest.get("tools") + if not isinstance(tools, dict): + errors.append("lock.tools must contain exact cmake, ninja, cxx_compiler and protoc values") + tools = {} + if not isinstance(observed_tools, dict): + errors.append("manifest.tools must be an object") + observed_tools = {} + for name in ("cmake", "ninja", "cxx_compiler", "protoc"): + expected = tools.get(name) + observed = observed_tools.get(name) + if not _nonempty_string(expected) or not _nonempty_string(observed): + errors.append(f"tool version {name} is missing from lock or manifest") + continue + if name == "cmake": + expected_value = _cmake_version(expected) + observed_value = _cmake_version(observed) + if not expected_value or not observed_value: + errors.append("cmake version could not be parsed") + elif expected_value != observed_value: + errors.append(f"cmake version mismatch: expected {expected_value!r}, observed {observed_value!r}") + elif expected != observed: + errors.append(f"{name} version mismatch: expected {expected!r}, observed {observed!r}") + + dependencies = lock.get("dependencies") + if not isinstance(dependencies, dict): + errors.append("lock.dependencies must be an object") + dependencies = {} + expected_packages = dependencies.get("package_versions") + observed_packages = manifest.get("system_packages") + if not isinstance(expected_packages, dict) or not expected_packages: + errors.append("lock.dependencies.package_versions must be populated; an empty candidate cannot pass") + expected_packages = {} + if set(expected_packages) != set(PACKAGE_FIELDS): + missing = sorted(set(PACKAGE_FIELDS) - set(expected_packages)) + extra = sorted(set(expected_packages) - set(PACKAGE_FIELDS)) + if missing: + errors.append("lock package_versions missing: " + ", ".join(missing)) + if extra: + errors.append("lock package_versions has unsupported keys: " + ", ".join(extra)) + if not isinstance(observed_packages, dict): + errors.append("manifest.system_packages must be an object") + observed_packages = {} + for package, field in PACKAGE_FIELDS.items(): + expected = expected_packages.get(package) + observed = observed_packages.get(field) + if not _nonempty_string(expected) or not _nonempty_string(observed): + errors.append(f"package version {package} is missing from lock or manifest") + elif expected != observed: + errors.append(f"package version mismatch for {package}: expected {expected!r}, observed {observed!r}") + + if _get(lock, "target", "dependency_mode") != "ubuntu-packages": + errors.append("lock.target.dependency_mode must be 'ubuntu-packages'") + if manifest.get("dependency_mode") != "system_packages": + errors.append("manifest.dependency_mode must be 'system_packages'") + return errors + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--lock", required=True, type=Path) + parser.add_argument("--manifest", required=True, type=Path) + args = parser.parse_args(argv) + try: + lock = json.loads(args.lock.read_text(encoding="utf-8")) + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + print(f"ERROR: unable to read JSON input: {exc}", file=sys.stderr) + return 2 + if not isinstance(lock, dict) or not isinstance(manifest, dict): + print("ERROR: lock and manifest roots must be JSON objects", file=sys.stderr) + return 2 + errors = verify(lock, manifest) + if errors: + for error in errors: + print(f"ERROR: {error}", file=sys.stderr) + return 1 + print(f"Build manifest exactly matches the {lock['lock_status']} build lock.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())