From 2b8b08a795bce65da5a7cea2b49ca76a4ba10112 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Fri, 2 Oct 2026 01:57:26 +0100 Subject: [PATCH 01/22] Forbid live signature-table access in CCF 8.0 Exclude deferred signature state from ordinary KV transactions, constrain reserved writes, and migrate framework metadata readers to pinned materialised prefixes. Preserve historical access and add policy, rollback, binding, and end-to-end regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 13 + doc/audit/read_write_restrictions.rst | 19 +- doc/build_apps/kv/kv_how_to.rst | 11 + doc/governance/adding_member.rst | 6 + doc/operations/recovery.rst | 4 + include/ccf/kv/map_access.h | 14 + include/ccf/rust_ffi.h | 4 +- include/ccf/tx.h | 65 +- python/pyproject.toml | 2 +- samples/apps/basic_rust/src/lib.rs | 74 ++ .../aft/test/view_straddling_common.h | 45 +- .../aft/test/view_straddling_history.cpp | 32 +- .../aft/test/view_straddling_rollback.cpp | 55 +- src/js/extensions/ccf/historical.cpp | 6 +- src/js/extensions/ccf/kv.cpp | 4 +- src/js/permissions_checks.h | 14 +- src/js/test/js.cpp | 324 ++++++- src/kv/committable_tx.h | 24 + src/kv/internal_table_names.h | 12 + src/kv/store.h | 26 + src/kv/test/kv_contention.cpp | 6 +- src/kv/test/kv_serialisation.cpp | 22 +- src/kv/test/kv_test.cpp | 912 ++++++++++++++++-- src/kv/test/null_tx_history.h | 4 +- src/kv/tx.cpp | 92 +- src/kv/tx_pimpl.h | 9 + src/node/gov/handlers/acks.h | 12 +- src/node/history.h | 4 +- src/node/internal_tables_access.h | 26 +- src/node/node_state.h | 7 +- src/node/rpc/node_frontend.h | 91 +- .../rpc/test/internal_tables_access_test.cpp | 22 +- src/node/rpc/test/node_frontend_test.cpp | 22 + src/node/test/historical_queries.cpp | 21 +- src/node/test/history.cpp | 81 +- src/node/test/snapshot.cpp | 2 +- src/node/test/snapshotter.cpp | 19 +- src/rust/app_bridge.cpp | 5 + src/rust/ccf-app/src/lib.rs | 21 + tests/basic_rust.py | 34 + tests/e2e_operations.py | 2 + tests/governance.py | 7 + tests/infra/network.py | 2 +- tests/programmability.py | 154 +++ tests/programmability/restrictions.js | 147 ++- 45 files changed, 2214 insertions(+), 264 deletions(-) create mode 100644 include/ccf/kv/map_access.h diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f17abfeaca1..c89f8949a760 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [8.0.0] + +[8.0.0]: https://github.com/microsoft/CCF/releases/tag/ccf-8.0.0 + +### Changed + +- `GET /node/state` is now a non-transactional command endpoint. Its response body schema is unchanged, but it no longer returns `x-ms-ccf-transaction-id`; `last_signed_seqno` reports progress from a coherent materialised ledger prefix, not an application KV snapshot. + +### Removed + +- Removed ordinary live KV access to `public:ccf.internal.signatures`, `public:ccf.internal.cose_signatures` and `public:ccf.internal.tree` in native C++/Rust and current-KV JavaScript application/governance contexts. `Tx`, `ReadOnlyTx` and `TxDiff` reject all typed and untyped handles to these tables. Use historical state or receipt APIs instead; historical read-only access and offline ledger parsing remain supported. All other table permissions are unchanged. + - Copied older constitutions must remove eager raw-signature reads which initialise `ack.state_digest` when adding or resetting members, and use the existing [state-digest update and acknowledgement workflow](doc/governance/adding_member.rst#activating-a-new-member). Default constitutions from 7.0.17 onward already use this workflow. + ## [7.0.18] [7.0.18]: https://github.com/microsoft/CCF/releases/tag/ccf-7.0.18 diff --git a/doc/audit/read_write_restrictions.rst b/doc/audit/read_write_restrictions.rst index 965360eed8fe..1c0195c7eec6 100644 --- a/doc/audit/read_write_restrictions.rst +++ b/doc/audit/read_write_restrictions.rst @@ -60,7 +60,7 @@ CCF ensures that governance audit is possible offline from a ledger, by consider If this table is moved, make sure the source is updated in-sync. (Ctrl+Shift+F: read_write_restrictions) -The possible access permissions are elaborated in the table below: +The possible access permissions are elaborated in the table below. The public internal column excludes the :ref:`signature-transaction tables ` described below. .. table:: KV permissions in different execution contexts :widths: auto @@ -79,4 +79,19 @@ The possible access permissions are elaborated in the table below: | Application | Read-only | None | Read-only | None | Read/Write | Read/Write | +--------------------------+------------+------------+------------+------------+------------+------------+ -Any violation of these restrictions (eg - calling ``set`` on a `Read-only` table, or ``has`` on a `None` table) results in an exception being thrown. \ No newline at end of file +Any violation of these restrictions (eg - calling ``set`` on a `Read-only` table, or ``has`` on a `None` table) results in an exception being thrown. + +Signature-Transaction Tables +---------------------------- + +From CCF 8.0, the following public internal tables have no current-KV access in any application or governance context, including read-only endpoints, ballots and all constitution functions: + +- ``public:ccf.internal.signatures`` +- ``public:ccf.internal.cose_signatures`` +- ``public:ccf.internal.tree`` + +These tables are maintained by framework signature transactions and must not be treated as part of an ordinary live transaction's KV snapshot. This restriction applies to exactly these names, not the entire ``public:ccf.internal`` namespace. Other public internal tables retain the read-only permissions shown above. + +The restriction is enforced by the native KV API as well as JavaScript permissions, so also applies to C++ and Rust applications. See :doc:`/build_apps/kv/kv_how_to` for the native transaction restrictions. Historical read-only access to these tables remains supported, including JavaScript historical KV views and native historical read-only stores. :doc:`Receipt APIs ` and :doc:`offline ledger parsing ` are unaffected. + +Applications needing signature data should use historical state or receipt APIs instead of the current KV. For non-transactional progress metadata, use :http:GET:`/node/state`; this metadata is independent of an application's KV snapshot. Older copied constitutions which eagerly initialise member acknowledgement state digests from raw signatures must migrate to the :ref:`state-digest update and acknowledgement workflow `. \ No newline at end of file diff --git a/doc/build_apps/kv/kv_how_to.rst b/doc/build_apps/kv/kv_how_to.rst index bc945ebc2b5f..c4655f580375 100644 --- a/doc/build_apps/kv/kv_how_to.rst +++ b/doc/build_apps/kv/kv_how_to.rst @@ -119,6 +119,17 @@ If you are only reading from or only writing to a given :cpp:type:`ccf::kv::Map` Note that, as in the sample above, it is possible to acquire different kinds of handles at different points within your transaction's execution. So if you need to read in one location and write in another you can retrieve multiple distinct handles and get local type-safety, while the resulting transaction correctly handles all reads and writes made. +Signature Metadata +------------------ + +From CCF 8.0, ordinary live ``Tx``, ``ReadOnlyTx`` and ``TxDiff`` cannot acquire any handle to ``public:ccf.internal.signatures``, ``public:ccf.internal.cose_signatures`` or ``public:ccf.internal.tree``. This includes typed and untyped handles, whether read-only, read/write, write-only or diff handles. The restriction is enforced centrally by the KV API, including for native C++ and Rust applications; read-only endpoints are not exempt. See :ref:`audit/read_write_restrictions:Signature-Transaction Tables` for the corresponding JavaScript permissions and the unchanged permissions for other public internal tables. + +For signature data and proofs, use :ref:`historical state ` or :doc:`receipt APIs ` instead. Historical JavaScript KV views and native historical read-only stores retain read-only access to these tables, and offline ledger parsing remains supported. For progress metadata, use :http:GET:`/node/state`, whose response is non-transactional and must not be interpreted as part of your KV snapshot. + +.. note:: + + Framework signature production uses ``ReservedTx``, which is limited to write-only handles on these three tables. It cannot read them or backfill ordinary readable maps. Framework verification, recovery, restore and metadata reads use an independent read-only view pinned to a materialised ledger prefix, selected using existing replication and commit metadata. These internal mechanisms are not ordinary live transaction exemptions or public opt-outs. No new wait for signature publication is introduced for ordinary transactions. + Removing a key -------------- diff --git a/doc/governance/adding_member.rst b/doc/governance/adding_member.rst index b1d692ddce1c..3e3c21e6a134 100644 --- a/doc/governance/adding_member.rst +++ b/doc/governance/adding_member.rst @@ -57,6 +57,12 @@ First, the new member should update and retrieve the latest state digest via the No state digest is recorded when a member is added. Until the member calls this ``:update`` endpoint, :http:GET:`/gov/members/state-digests/{memberId}` returns ``404 Not Found`` and the member cannot acknowledge a state digest. +The signed root used by ``:update`` is obtained from an independent read-only view pinned to a materialised ledger prefix, rather than by reading signature metadata through its governance write transaction. The request and response schemas of the ``:update`` and ``:ack`` endpoints are unchanged. + +.. note:: + + The default constitution has used this workflow since CCF 7.0.17. Copied older constitutions may still eagerly read ``public:ccf.internal.signatures`` or ``public:ccf.internal.cose_signatures`` to initialise ``ack.state_digest`` when adding or resetting a member. From CCF 8.0, these reads fail under the :doc:`current-KV access restrictions `. Remove that eager initialisation and follow the existing ``:update`` and ``:ack`` workflow described here instead. + .. code-block:: bash $ touch empty_file diff --git a/doc/operations/recovery.rst b/doc/operations/recovery.rst index 763039974255..fa3e58168e68 100644 --- a/doc/operations/recovery.rst +++ b/doc/operations/recovery.rst @@ -40,6 +40,10 @@ To initiate the first phase of the recovery procedure, one or several nodes shou Each node will then immediately restore the public entries of its ledger (``ledger.directory`` and ``ledger.read_only_directories`` configuration entries). Because deserialising the public entries present in the ledger may take some time, operators can query the progress of the public recovery by calling :http:GET:`/node/state` which returns the version of the last signed recovered ledger entry. Once the public ledger is fully recovered, the recovered node automatically becomes part of the public network, allowing other nodes to join the network. +.. note:: + + From CCF 8.0, :http:GET:`/node/state` is a non-transactional command endpoint and no longer returns the ``x-ms-ccf-transaction-id`` response header. Its response body schema is unchanged. The ``last_signed_seqno`` field is read from a coherent, locally materialised ledger prefix. It is progress metadata, independent of application KV snapshots, not a transaction ID for this request. + Public-ledger replay temporarily reconstructs the previous service's node entries and consensus configuration. When the recovery service is created, the recovery transaction deletes all previous-service node entries and their associated endorsed certificates and local-sealing records. These nodes do not pass through the normal ``Retired`` and ``retired_committed`` states because the previous service does not participate in the new service's consensus. Consequently, previous-service nodes are absent from both :http:GET:`/node/network/nodes` and :http:GET:`/node/network/removable_nodes` after recovery. See :ref:`architecture/consensus/index:Retirement details` for the normal live-service retirement sequence. The recovery procedure can be accelerated by specifying a valid snapshot file created by the previous service in the directory specified via the ``snapshots.directory`` configuration entry. If specified, the ``recover`` node will automatically recover the snapshot and the ledger entries following that snapshot, which in practice should be a fraction of the total time required to recover the entire historical ledger. diff --git a/include/ccf/kv/map_access.h b/include/ccf/kv/map_access.h new file mode 100644 index 000000000000..3f60d75c4876 --- /dev/null +++ b/include/ccf/kv/map_access.h @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the Apache 2.0 License. +#pragma once + +#include + +namespace ccf::kv +{ + class MapAccessDenied : public std::logic_error + { + public: + using std::logic_error::logic_error; + }; +} diff --git a/include/ccf/rust_ffi.h b/include/ccf/rust_ffi.h index 18aa7e9d1a3e..fe1fd47ac0a2 100644 --- a/include/ccf/rust_ffi.h +++ b/include/ccf/rust_ffi.h @@ -43,6 +43,7 @@ typedef void (*ccf_rust_drop_callback)(void* user_data); inline constexpr ccf_rust_result CCF_RUST_INVALID_ARGUMENT = 2; inline constexpr ccf_rust_result CCF_RUST_READ_ONLY = 3; inline constexpr ccf_rust_result CCF_RUST_INTERNAL_ERROR = 4; + inline constexpr ccf_rust_result CCF_RUST_ACCESS_DENIED = 5; inline constexpr ccf_rust_auth CCF_RUST_AUTH_NONE = 0; inline constexpr ccf_rust_auth CCF_RUST_AUTH_USER_CERT = 1; @@ -53,7 +54,8 @@ enum CCF_RUST_NOT_FOUND = 1, CCF_RUST_INVALID_ARGUMENT = 2, CCF_RUST_READ_ONLY = 3, - CCF_RUST_INTERNAL_ERROR = 4 + CCF_RUST_INTERNAL_ERROR = 4, + CCF_RUST_ACCESS_DENIED = 5 }; enum diff --git a/include/ccf/tx.h b/include/ccf/tx.h index a2851271e2d9..2c9ce4444cf6 100644 --- a/include/ccf/tx.h +++ b/include/ccf/tx.h @@ -3,6 +3,8 @@ #pragma once #include "ccf/crypto/sha256_hash.h" +#include "ccf/kv/map_access.h" +#include "ccf/kv/version.h" #include "ccf/tx_id.h" #include @@ -16,6 +18,7 @@ namespace ccf::kv class AbstractHandle; class AbstractMap; class AbstractStore; + class Store; namespace untyped { @@ -45,6 +48,14 @@ namespace ccf::kv class BaseTx { protected: + enum class AccessMode + { + ReadOnly, + ReadWrite, + WriteOnly, + Diff + }; + struct PrivateImpl; std::unique_ptr pimpl; @@ -60,17 +71,25 @@ namespace ccf::kv const std::string& map_name, std::unique_ptr&& handle); MapChanges get_map_and_change_set_by_name( - const std::string& map_name, bool track_deletes_on_missing_keys); + const std::string& map_name, + bool track_deletes_on_missing_keys, + AccessMode access); std::list get_possible_handles( const std::string& map_name); void compacted_version_conflict(const std::string& map_name); + void check_map_access(const std::string& map_name, AccessMode access); + template THandle* get_handle_by_name( - const std::string& map_name, bool track_deletes_on_missing_keys) + const std::string& map_name, + bool track_deletes_on_missing_keys, + AccessMode access) { + check_map_access(map_name, access); + auto possible_handles = get_possible_handles(map_name); for (auto* handle : possible_handles) { @@ -92,8 +111,8 @@ namespace ccf::kv retain_handle(map_name, std::move(abstract_handle)); return typed_handle; } - auto [abstract_map, change_set] = - get_map_and_change_set_by_name(map_name, track_deletes_on_missing_keys); + auto [abstract_map, change_set] = get_map_and_change_set_by_name( + map_name, track_deletes_on_missing_keys, access); if (change_set == nullptr) { @@ -128,13 +147,21 @@ namespace ccf::kv class TxDiff : public BaseTx { + private: + friend class Store; + TxDiff( + AbstractStore* store_, + ccf::SeqNo read_version, + Version read_rollback_count); + public: using BaseTx::BaseTx; template typename M::Diff* diff(M& m) { - return get_handle_by_name(m.get_name(), true); + return get_handle_by_name( + m.get_name(), true, AccessMode::Diff); } /** Get a diff by map name. Map type must be specified @@ -145,7 +172,8 @@ namespace ccf::kv template typename M::Diff* diff(const std::string& map_name) { - return get_handle_by_name(map_name, true); + return get_handle_by_name( + map_name, true, AccessMode::Diff); } }; @@ -157,6 +185,13 @@ namespace ccf::kv */ class ReadOnlyTx : public BaseTx { + private: + friend class Store; + ReadOnlyTx( + AbstractStore* store_, + ccf::SeqNo read_version, + Version read_rollback_count); + public: using BaseTx::BaseTx; @@ -170,7 +205,8 @@ namespace ccf::kv // NB: Always creates a (writeable) MapHandle, which is cast to // ReadOnlyHandle on return. This is so that other calls (before or // after) can retrieve writeable handles over the same map. - return get_handle_by_name(m.get_name(), false); + return get_handle_by_name( + m.get_name(), false, AccessMode::ReadOnly); } /** Get a read-only handle by map name. Map type must be specified @@ -181,7 +217,8 @@ namespace ccf::kv template typename M::ReadOnlyHandle* ro(const std::string& map_name) { - return get_handle_by_name(map_name, false); + return get_handle_by_name( + map_name, false, AccessMode::ReadOnly); } }; @@ -210,7 +247,8 @@ namespace ccf::kv template typename M::Handle* rw(M& m) { - return get_handle_by_name(m.get_name(), false); + return get_handle_by_name( + m.get_name(), false, AccessMode::ReadWrite); } /** Get a read-write handle by map name. Map type must be specified @@ -221,7 +259,8 @@ namespace ccf::kv template typename M::Handle* rw(const std::string& map_name) { - return get_handle_by_name(map_name, false); + return get_handle_by_name( + map_name, false, AccessMode::ReadWrite); } /** Get a write-only handle from a map instance. @@ -233,7 +272,8 @@ namespace ccf::kv { // As with ro, this returns a full-featured Handle // which is cast to only show its writeable facet. - return get_handle_by_name(m.get_name(), false); + return get_handle_by_name( + m.get_name(), false, AccessMode::WriteOnly); } /** Get a write-only handle by map name. Map type must be specified @@ -244,7 +284,8 @@ namespace ccf::kv template typename M::WriteOnlyHandle* wo(const std::string& map_name) { - return get_handle_by_name(map_name, false); + return get_handle_by_name( + map_name, false, AccessMode::WriteOnly); } }; } diff --git a/python/pyproject.toml b/python/pyproject.toml index 9c5b2e3da284..2202af93443f 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "ccf" -version = "7.0.18" +version = "8.0.0" authors = [ { name="CCF Team", email="CCF-Sec@microsoft.com" }, ] diff --git a/samples/apps/basic_rust/src/lib.rs b/samples/apps/basic_rust/src/lib.rs index a84b81b00ec8..b5263d6fe4f6 100644 --- a/samples/apps/basic_rust/src/lib.rs +++ b/samples/apps/basic_rust/src/lib.rs @@ -10,12 +10,28 @@ const COMPACTION_DELAY_MS: u64 = 2_000; const COMPACTION_MARKER: &str = "compaction_marker"; const COMPACTION_RECORDS: &str = "compaction_records"; const RECORDS: &str = "records"; +const SIGNATURE_TABLE_KEY: &[u8] = &[0; 8]; static COMPACTION_READY: AtomicBool = AtomicBool::new(false); fn required_key(value: Result, BridgeError>) -> Result { value?.ok_or_else(|| EndpointError::new(400, "InvalidResourceName", "Missing key")) } +fn signature_table_name( + value: Result, BridgeError>, +) -> Result<&'static str, EndpointError> { + match value?.as_deref() { + Some("signatures") => Ok("public:ccf.internal.signatures"), + Some("cose_signatures") => Ok("public:ccf.internal.cose_signatures"), + Some("tree") => Ok("public:ccf.internal.tree"), + _ => Err(EndpointError::new( + 400, + "InvalidResourceName", + "Unknown signature table", + )), + } +} + fn register(registry: &mut Registry) -> Result<(), BridgeError> { // SNIPPET_START: rust_put_record registry.read_write( @@ -52,6 +68,64 @@ fn register(registry: &mut Registry) -> Result<(), BridgeError> { )?; // SNIPPET_END: rust_get_record + registry.read_only( + "/signature-table-access/{table}/{operation}", + "GET", + Auth::None, + |context| -> EndpointResult { + let table = signature_table_name(context.path_param("table"))?; + let operation = required_key(context.path_param("operation"))?; + match operation.as_str() { + "get" => { + let _ = context.map(table).get(SIGNATURE_TABLE_KEY)?; + } + "has" => { + let _ = context.map(table).has(SIGNATURE_TABLE_KEY)?; + } + _ => { + return Err(EndpointError::new( + 400, + "InvalidOperation", + "Unknown read operation", + )); + } + } + Err(EndpointError::internal( + "Signature table access was permitted", + )) + }, + )?; + + registry.read_write( + "/signature-table-access/{table}/{operation}", + "POST", + Auth::None, + |context| -> EndpointResult { + let table = signature_table_name(context.path_param("table"))?; + let operation = required_key(context.path_param("operation"))?; + match operation.as_str() { + "get" => { + let _ = context.map(table).get(SIGNATURE_TABLE_KEY)?; + } + "has" => { + let _ = context.map(table).has(SIGNATURE_TABLE_KEY)?; + } + "put" => context.map(table).put(SIGNATURE_TABLE_KEY, b"probe")?, + "remove" => context.map(table).remove(SIGNATURE_TABLE_KEY)?, + _ => { + return Err(EndpointError::new( + 400, + "InvalidOperation", + "Unknown KV operation", + )); + } + } + Err(EndpointError::internal( + "Signature table access was permitted", + )) + }, + )?; + registry.read_write("/compaction/marker", "POST", Auth::None, |context| { COMPACTION_READY.store(false, Ordering::Release); context.map(COMPACTION_MARKER).put(b"init", b"init")?; diff --git a/src/consensus/aft/test/view_straddling_common.h b/src/consensus/aft/test/view_straddling_common.h index f626551a68e0..8e2512f11520 100644 --- a/src/consensus/aft/test/view_straddling_common.h +++ b/src/consensus/aft/test/view_straddling_common.h @@ -8,6 +8,7 @@ #include "kv/null_encryptor.h" #include "kv/store.h" +#include "service/tables/signatures.h" #include "test_common.h" #include @@ -23,24 +24,29 @@ namespace straddling using TestMap = ccf::kv::Map; using Raft = aft::Aft; - class BaselinePendingTx : public ccf::kv::PendingTx + class SignaturePendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; - TestMap& table; + uint8_t marker; public: - BaselinePendingTx( - ccf::TxID txid_, ccf::kv::Store& store_, TestMap& table_) : + SignaturePendingTx( + ccf::TxID txid_, ccf::kv::Store& store_, uint8_t marker_) : txid(txid_), store(store_), - table(table_) + marker(marker_) {} ccf::kv::PendingTxInfo call() override { auto tx = store.create_reserved_tx(txid); - tx.rw(table)->put(0, 1); + tx.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); + tx.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {marker}); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({marker}); return tx.commit_reserved(); } }; @@ -159,6 +165,18 @@ namespace straddling return tx.ro(table)->get(key); } + static std::optional read_signature_seqno(ccf::kv::Store& store) + { + auto tx = store.create_read_only_tx_at_replicated_state(); + const auto signature = + tx.ro(ccf::Tables::SIGNATURES)->get(); + if (!signature.has_value()) + { + return std::nullopt; + } + return signature->seqno; + } + struct Fixture { const ccf::NodeId node_id = ccf::kv::test::PrimaryNodeId; @@ -191,19 +209,24 @@ namespace straddling raft->force_become_primary(); initial_view = raft->get_view(); + { + auto tx = store->create_tx(); + tx.rw(table)->put(0, 1); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } const auto baseline_txid = store->next_txid(); REQUIRE( store->commit( baseline_txid, - std::make_unique(baseline_txid, *store, table), + std::make_unique(baseline_txid, *store, 1), true) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(store->current_txid() == ccf::TxID(initial_view, 1)); - REQUIRE(raft->get_committed_seqno() == 1); - REQUIRE(raft->ledger->ledger.size() == 1); + REQUIRE(store->current_txid() == ccf::TxID(initial_view, 2)); + REQUIRE(raft->get_committed_seqno() == 2); + REQUIRE(raft->ledger->ledger.size() == 2); } // Lose leadership, then win a later election. become_leader() rolls the - // Store back to the last committable index (1) under the new view. + // Store back to the last committable index (2) under the new view. ccf::View reelect() { raft->become_aware_of_new_term(raft->get_view() + 1); diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index c87161b6e610..f3e4b6a7cc57 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -16,7 +16,7 @@ // // - Tx A passes Store::commit()'s view check under version_lock, which is // then released. -// - An election rolls the Store and the ledger history back to seqno 1. +// - An election rolls the Store and the ledger history back to seqno 2. // - A appends its digest to the history, then consensus rejects it. #include "node/history.h" @@ -82,16 +82,14 @@ TEST_CASE( const auto [baseline_txid, baseline_root, _] = fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(baseline_txid.seqno == 1); + REQUIRE(baseline_txid.seqno == 2); + REQUIRE(read_value(*fixture.store, fixture.table, 0) == 1); + REQUIRE(read_signature_seqno(*fixture.store) == baseline_txid.seqno); - INFO("Apply and serialise A at seqno 2 in the initial view"); + INFO("Apply and serialise A at seqno 3 in the initial view"); const auto stale_txid = fixture.store->next_txid(); - REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 2)); - auto stale_info = [&]() { - auto tx = fixture.store->create_reserved_tx(stale_txid); - tx.rw(fixture.table)->put(1, 2); - return tx.commit_reserved(); - }(); + REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); + auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); INFO("A enters Store::commit, passes its view check, then is descheduled"); @@ -106,12 +104,12 @@ TEST_CASE( }); REQUIRE(commit_pause.wait_until_paused()); - INFO("Lose leadership and win a later election, rolling back to seqno 1"); + INFO("Lose leadership and win a later election, rolling back to seqno 2"); fixture.reelect(); { const auto [rolled_back_txid, rolled_back_root, rolled_back_term] = fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(rolled_back_txid.seqno == 1); + REQUIRE(rolled_back_txid.seqno == 2); REQUIRE(rolled_back_root == baseline_root); } @@ -122,7 +120,7 @@ TEST_CASE( { const auto [observed_txid, observed_root, observed_term] = fixture.history->get_replicated_state_txid_and_root(); - CHECK(observed_txid.seqno == 1); + CHECK(observed_txid.seqno == 2); CHECK(observed_root == baseline_root); } fixture.history->pause.release(); @@ -134,10 +132,12 @@ TEST_CASE( { const auto [final_txid, final_root, final_term] = fixture.history->get_replicated_state_txid_and_root(); - CHECK(final_txid.seqno == 1); + CHECK(final_txid.seqno == 2); CHECK(final_root == baseline_root); } - CHECK(fixture.store->current_txid().seqno == 1); - CHECK(fixture.raft->get_last_idx() == 1); - CHECK(fixture.raft->ledger->ledger.size() == 1); + CHECK(fixture.store->current_txid().seqno == 2); + CHECK(read_value(*fixture.store, fixture.table, 0) == 1); + CHECK(read_signature_seqno(*fixture.store) == baseline_txid.seqno); + CHECK(fixture.raft->get_last_idx() == 2); + CHECK(fixture.raft->ledger->ledger.size() == 2); } diff --git a/src/consensus/aft/test/view_straddling_rollback.cpp b/src/consensus/aft/test/view_straddling_rollback.cpp index e0998ef9393f..eae51e11919b 100644 --- a/src/consensus/aft/test/view_straddling_rollback.cpp +++ b/src/consensus/aft/test/view_straddling_rollback.cpp @@ -14,15 +14,15 @@ // // Interleaving, from review of PR #8209 (cjen1-msft, src/consensus/aft/raft.h): // -// - Tx A is applied locally in view V and given TxID V.2. It enters +// - Tx A is applied locally in view V and given TxID V.3. It enters // Store::commit(), passes the view check, and is descheduled before it // reaches consensus. // - An election happens. The node wins in view W > V, and become_leader() -// rolls the Store back past A, to seqno 1. -// - Tx B is applied locally in view W and given TxID W.2. It has not yet +// rolls the Store back past A, to seqno 2. +// - Tx B is applied locally in view W and given TxID W.3. It has not yet // entered Store::commit(). // - A continues. Consensus rejects it. If that rejection rolls the Store -// back to Raft's last_idx (1), it discards B's local application as well. +// back to Raft's last_idx (2), it discards B's local application as well. // - B enters Store::commit(), passes the view check (W == W), and is // replicated. It is in the ledger, but no longer in the KV. @@ -52,16 +52,12 @@ TEST_CASE( Fixture fixture; fixture.start(); - INFO("Apply and serialise A at seqno 2 in the initial view"); + INFO("Apply and serialise A at seqno 3 in the initial view"); const auto stale_txid = fixture.store->next_txid(); - REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 2)); - auto stale_info = [&]() { - auto tx = fixture.store->create_reserved_tx(stale_txid); - tx.rw(fixture.table)->put(1, 2); - return tx.commit_reserved(); - }(); + REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); + auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); - REQUIRE(read_value(*fixture.store, fixture.table, 1) == 2); + REQUIRE(read_signature_seqno(*fixture.store) == 2); INFO("A enters Store::commit, passes its view check, then is descheduled"); CommitPause stale_pause; @@ -75,14 +71,15 @@ TEST_CASE( }); REQUIRE(stale_pause.wait_until_paused()); - INFO("Lose leadership and win a later election, rolling back to seqno 1"); + INFO("Lose leadership and win a later election, rolling back to seqno 2"); const auto reelection_view = fixture.reelect(); - REQUIRE(fixture.store->current_txid() == ccf::TxID(fixture.initial_view, 1)); - REQUIRE_FALSE(read_value(*fixture.store, fixture.table, 1).has_value()); - REQUIRE(fixture.raft->get_last_idx() == 1); + REQUIRE(fixture.store->current_txid() == ccf::TxID(fixture.initial_view, 2)); + REQUIRE(read_value(*fixture.store, fixture.table, 0) == 1); + REQUIRE(read_signature_seqno(*fixture.store) == 2); + REQUIRE(fixture.raft->get_last_idx() == 2); INFO( - "B is applied at seqno 2 in the new view, then pauses before " + "B is applied at seqno 3 in the new view, then pauses before " "Store::commit"); auto current_tx = fixture.store->create_tx(); current_tx.rw(fixture.table)->put(2, 3); @@ -94,8 +91,8 @@ TEST_CASE( [¤t_pause](const auto&, const auto&) { current_pause.pause(); }); }); REQUIRE(current_pause.wait_until_paused()); - REQUIRE(current_tx.get_txid() == ccf::TxID(reelection_view, 2)); - REQUIRE(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); + REQUIRE(current_tx.get_txid() == ccf::TxID(reelection_view, 3)); + REQUIRE(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); REQUIRE(read_value(*fixture.store, fixture.table, 2) == 3); INFO( @@ -106,9 +103,9 @@ TEST_CASE( REQUIRE(stale_result.has_value()); CHECK(stale_result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); MESSAGE("After A is rejected: " << describe(fixture)); - CHECK(fixture.raft->get_last_idx() == 1); - CHECK(fixture.raft->ledger->ledger.size() == 1); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); + CHECK(fixture.raft->get_last_idx() == 2); + CHECK(fixture.raft->ledger->ledger.size() == 2); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); CHECK(read_value(*fixture.store, fixture.table, 2) == 3); INFO("Resume B: whatever consensus decides, KV and ledger must agree"); @@ -117,9 +114,9 @@ TEST_CASE( REQUIRE(current_result.has_value()); CHECK(current_result.value() == ccf::kv::CommitResult::SUCCESS); MESSAGE("After B is replicated: " << describe(fixture)); - CHECK(fixture.raft->get_last_idx() == 2); - CHECK(fixture.raft->ledger->ledger.size() == 2); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); + CHECK(fixture.raft->get_last_idx() == 3); + CHECK(fixture.raft->ledger->ledger.size() == 3); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); CHECK(read_value(*fixture.store, fixture.table, 2) == 3); INFO("The next transaction gets a fresh seqno and replicates normally"); @@ -131,9 +128,9 @@ TEST_CASE( "After next tx " << (next_txid.has_value() ? next_txid->to_str() : std::string("none")) << ": " << describe(fixture)); - CHECK(next_txid == ccf::TxID(reelection_view, 3)); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); + CHECK(next_txid == ccf::TxID(reelection_view, 4)); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 4)); CHECK(read_value(*fixture.store, fixture.table, 3) == 4); - CHECK(fixture.raft->get_last_idx() == 3); - CHECK(fixture.raft->ledger->ledger.size() == 3); + CHECK(fixture.raft->get_last_idx() == 4); + CHECK(fixture.raft->ledger->ledger.size() == 4); } diff --git a/src/js/extensions/ccf/historical.cpp b/src/js/extensions/ccf/historical.cpp index d67792e07565..f3dc50a6a4cf 100644 --- a/src/js/extensions/ccf/historical.cpp +++ b/src/js/extensions/ccf/historical.cpp @@ -336,12 +336,12 @@ namespace ccf::js::extensions LOG_TRACE_FMT( "Looking for historical kv map '{}' at seqno {}", map_name, seqno); - auto access_permission = - ccf::js::check_kv_map_access(jsctx.access, map_name); + auto access_permission = ccf::js::check_kv_map_access( + jsctx.access, map_name, kvhelpers::KVSource::Historical); std::string explanation = ccf::js::explain_kv_map_access(access_permission, jsctx.access); - // Historical KV access can never exceed current-KV access. + // Historical KV retains namespace restrictions and is always read-only. access_permission = ccf::js::intersect_access_permissions( access_permission, KVAccessPermissions::READ_ONLY); if (access_permission != KVAccessPermissions::ILLEGAL) diff --git a/src/js/extensions/ccf/kv.cpp b/src/js/extensions/ccf/kv.cpp index bf4231c83d10..deac1ba85aef 100644 --- a/src/js/extensions/ccf/kv.cpp +++ b/src/js/extensions/ccf/kv.cpp @@ -116,8 +116,8 @@ namespace ccf::js::extensions return -1; } - auto access_permission = - ccf::js::check_kv_map_access(jsctx.access, map_name); + auto access_permission = ccf::js::check_kv_map_access( + jsctx.access, map_name, kvhelpers::KVSource::CurrentTx); std::string explanation = ccf::js::explain_kv_map_access(access_permission, jsctx.access); diff --git a/src/js/permissions_checks.h b/src/js/permissions_checks.h index 95aa645887ce..4b15b6aa3dde 100644 --- a/src/js/permissions_checks.h +++ b/src/js/permissions_checks.h @@ -5,12 +5,17 @@ #include "ccf/js/kv_access_permissions.h" #include "ccf/js/namespace_restrictions.h" #include "ccf/js/tx_access.h" +#include "js/extensions/ccf/kv_map_handle_state.h" +#include "kv/internal_table_names.h" #include "kv/kv_types.h" namespace ccf::js { static KVAccessPermissions check_kv_map_access( - TxAccess execution_context, const std::string& table_name) + TxAccess execution_context, + const std::string& table_name, + extensions::kvhelpers::KVSource source = + extensions::kvhelpers::KVSource::CurrentTx) { // Enforce the restrictions described in the read_write_restrictions page in // the docs. Note that table is more readable, so should be considered the @@ -50,6 +55,13 @@ namespace ccf::js { case ccf::kv::AccessCategory::INTERNAL: { + if ( + source == extensions::kvhelpers::KVSource::CurrentTx && + ccf::kv::is_signature_table(table_name)) + { + return KVAccessPermissions::ILLEGAL; + } + return KVAccessPermissions::READ_ONLY; } diff --git a/src/js/test/js.cpp b/src/js/test/js.cpp index 19493317a674..b2719efd6aa3 100644 --- a/src/js/test/js.cpp +++ b/src/js/test/js.cpp @@ -25,6 +25,7 @@ #include "node/rpc/http_rpc_context.h" #include "node/rpc/test/node_stub.h" #include "node/tx_receipt_impl.h" +#include "service/tables/signatures.h" #define DOCTEST_CONFIG_IMPLEMENT #include @@ -507,6 +508,44 @@ TEST_CASE("Check KV Map access") } } + for (const auto access : + {TxAccess::APP_RO, TxAccess::APP_RW, TxAccess::GOV_RO, TxAccess::GOV_RW}) + { + CAPTURE(access); + for (const auto* table : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + CAPTURE(table); + CHECK(check_kv_map_access(access, table) == KVAccessPermissions::ILLEGAL); + CHECK( + check_kv_map_access( + access, table, extensions::kvhelpers::KVSource::CurrentTx) == + KVAccessPermissions::ILLEGAL); + CHECK( + check_kv_map_access( + access, table, extensions::kvhelpers::KVSource::Historical) == + KVAccessPermissions::READ_ONLY); + } + + for (const auto* table : + {"public:ccf.internal.table", + "public:ccf.internal.signatures_other", + "public:ccf.internal.signatures.nested", + "public:ccf.internal.cose_signatures_other", + "public:ccf.internal.tree_other"}) + { + CAPTURE(table); + CHECK( + check_kv_map_access(access, table) == KVAccessPermissions::READ_ONLY); + CHECK( + check_kv_map_access( + access, table, extensions::kvhelpers::KVSource::Historical) == + KVAccessPermissions::READ_ONLY); + } + } + { INFO("Every permission is described accurately"); REQUIRE( @@ -573,10 +612,14 @@ using KVMap = ccf::kv::untyped::Map; // Returns an error message if the JS script throws. std::optional run_kv_script( - ccf::kv::Tx& tx, TxAccess access, const std::string& body) + ccf::kv::Tx& tx, + TxAccess access, + const std::string& body, + ccf::js::NamespaceRestriction namespace_restriction = {}) { ccf::js::core::Context ctx(access); - ctx.add_extension(std::make_shared(&tx)); + ctx.add_extension(std::make_shared( + &tx, std::move(namespace_restriction))); const auto module = fmt::format("export function run() {{\n{}\n}}", body); auto func = ctx.get_exported_function(module, "run", "/test/kv_script"); @@ -2207,6 +2250,8 @@ namespace public: size_t tx_creations = 0; + CountingStore() : ccf::kv::Store(true) {} + std::unique_ptr create_read_only_tx_ptr() override { ++tx_creations; @@ -2224,6 +2269,281 @@ namespace ccf::NodeId("test-node"), std::nullopt); } + + std::vector make_test_signature_transaction(ccf::kv::Store& store) + { + const auto txid = store.next_txid(); + auto tx = store.create_reserved_tx(txid); + tx.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature(ccf::NodeId("test-node"), txid.seqno)); + tx.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {1, 2, 3}); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({4, 5, 6}); + auto info = tx.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + return std::move(info.data); + } + + constexpr auto signature_table_test_prelude = R"JS( +const signatureTables = [ + "public:ccf.internal.signatures", + "public:ccf.internal.cose_signatures", + "public:ccf.internal.tree" +]; +const key = new ArrayBuffer(8); +const value = new Uint8Array([118]).buffer; +function expectTypeError(operation, ...fragments) { + try { + operation(); + } catch (e) { + if (!(e instanceof TypeError) || + fragments.some(fragment => !e.message.includes(fragment))) { + throw new Error(`Unexpected error: ${e}`); + } + return; + } + throw new Error(`Operation was permitted: ${fragments.join(", ")}`); +} +function readOperations(donor) { + return [ + ["get", target => donor.get.call(target, key)], + ["has", target => donor.has.call(target, key)], + ["getVersionOfPreviousWrite", + target => donor.getVersionOfPreviousWrite.call(target, key)], + ["forEach", target => donor.forEach.call(target, () => {})], + ["size", target => + Object.getOwnPropertyDescriptor(donor, "size").get.call(target)] + ]; +} +function writeOperations(donor) { + return [ + ["set", target => donor.set.call(target, key, value)], + ["delete", target => donor.delete.call(target, key)], + ["clear", target => donor.clear.call(target)] + ]; +} +)JS"; +} + +TEST_CASE("Current JS signature table handles deny every operation") +{ + NamespaceRestriction namespace_restriction; + SUBCASE("Default namespace policy") {} + SUBCASE("A namespace callback cannot grant signature table access") + { + namespace_restriction = [](const std::string&, std::string&) { + return KVAccessPermissions::READ_WRITE; + }; + } + + for (const bool populated : {false, true}) + { + CAPTURE(populated); + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + if (populated) + { + make_test_signature_transaction(store); + } + + for (const auto access : + {TxAccess::APP_RO, + TxAccess::APP_RW, + TxAccess::GOV_RO, + TxAccess::GOV_RW}) + { + CAPTURE(access); + auto tx = store.create_tx(); + const auto body = std::string(signature_table_test_prelude) + R"JS( +const reader = ccf.kv["public:ccf.internal.table"]; +const writer = ccf.kv["public:signature_permission_probe"]; +for (const table of signatureTables) { + const indirectName = ["public:ccf", "internal", table.split(".").pop()].join("."); + const handle = Reflect.get(ccf.kv, indirectName); + handle._map_name = "public:ccf.internal.table"; + handle._source = "Historical"; + handle._seqno = 1; + const direct = [...readOperations(handle), ...writeOperations(handle)]; + const borrowed = [...readOperations(reader), ...writeOperations(writer)]; + for (const [name, operation] of direct) { + expectTypeError(() => operation(handle), table, "inaccessible"); + } + for (const [name, operation] of borrowed) { + expectTypeError(() => operation(handle), table, "inaccessible"); + for (const forged of [ + {_map_name: table}, + Object.create(handle), + new Proxy(handle, {}) + ]) { + expectTypeError(() => operation(forged), "KV Map Handle object expected"); + } + } +} +for (const table of [ + "public:ccf.internal.table", + "public:ccf.internal.signatures_other", + "public:ccf.internal.cose_signatures.nested", + "public:ccf.internal.tree_other" +]) { + const handle = ccf.kv[table]; + for (const [name, operation] of readOperations(handle)) { + operation(handle); + } + for (const [name, operation] of writeOperations(handle)) { + expectTypeError(() => operation(handle), table, "read-only"); + } +} +)JS"; + const auto error = run_kv_script(tx, access, body, namespace_restriction); + CHECK_MESSAGE(!error.has_value(), error.value_or("")); + for (const auto* table : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + CHECK( + (store.get_map(store.current_version(), table) != nullptr) == + populated); + } + } + } +} + +TEST_CASE("Historical JS signature table handles retain read-only access") +{ + bool restricted = false; + SUBCASE("Permitted historical reads") {} + SUBCASE("Namespace restrictions can deny historical signature reads") + { + restricted = true; + } + + for (const bool populated : {false, true}) + { + CAPTURE(populated); + ccf::kv::Store source; + source.set_encryptor(std::make_shared()); + auto historical_store = std::make_shared(true); + historical_store->set_encryptor( + std::make_shared()); + if (populated) + { + const auto data = make_test_signature_transaction(source); + REQUIRE( + historical_store->deserialize(data)->apply() == + ccf::kv::ApplyResult::PASS_SIGNATURE); + } + + auto state = std::make_shared( + historical_store, make_test_receipt(), ccf::TxID{1, 1}); + for (const auto access : + {TxAccess::APP_RO, + TxAccess::APP_RW, + TxAccess::GOV_RO, + TxAccess::GOV_RW}) + { + CAPTURE(access); + ccf::js::core::Context ctx(access); + auto tx = source.create_tx(); + ctx.add_extension(std::make_shared( + &tx, [restricted](const std::string& name, std::string& explanation) { + if (restricted && ccf::kv::is_signature_table(name)) + { + explanation = "Restricted test signature table"; + return KVAccessPermissions::ILLEGAL; + } + return KVAccessPermissions::READ_WRITE; + })); + auto historical = + std::make_shared(nullptr); + ctx.add_extension(historical); + auto js_state = historical->create_historical_state_object(ctx, state); + REQUIRE_FALSE(js_state.is_exception()); + REQUIRE(ctx.get_global_obj().set("testState", std::move(js_state)) == 1); + + const auto script = fmt::format( + "const populated = {};\nconst restricted = {};\n", + populated, + restricted) + + signature_table_test_prelude + R"JS( +export function run() { + const currentReader = ccf.kv["public:ccf.internal.table"]; + for (const table of signatureTables) { + const handle = testState.kv[table]; + if (restricted) { + for (const [name, operation] of [ + ...readOperations(handle), ...writeOperations(handle) + ]) { + expectTypeError( + () => operation(handle), table, "Restricted test signature table"); + } + continue; + } + if (handle.size !== (populated ? 1 : 0)) { + throw new Error(`Unexpected size for ${table}`); + } + if (handle.has(key) !== populated || + (handle.get(key) !== undefined) !== populated || + (handle.getVersionOfPreviousWrite(key) !== undefined) !== populated) { + throw new Error(`Unexpected singleton lookup for ${table}`); + } + let seen = 0; + handle.forEach((value, entryKey) => { + const storedValue = handle.get(entryKey); + if (!handle.has(entryKey) || value.byteLength === 0 || + storedValue === undefined || + handle.getVersionOfPreviousWrite(entryKey) !== 1) { + throw new Error(`Unreadable historical entry for ${table}`); + } + const bytes = new Uint8Array(value); + const storedBytes = new Uint8Array(storedValue); + if (bytes.length !== storedBytes.length || + !bytes.every((byte, i) => byte === storedBytes[i])) { + throw new Error(`Mismatched historical value for ${table}`); + } + seen++; + }); + if (seen !== handle.size) { + throw new Error(`Unexpected iteration count for ${table}`); + } + for (const [name, operation] of writeOperations(handle)) { + expectTypeError(() => operation(handle), table, "read-only"); + } + + const current = ccf.kv[table]; + for (const [name, operation] of readOperations(currentReader)) { + expectTypeError(() => operation(handle), "different key-value store"); + } + for (const [name, operation] of readOperations(handle)) { + expectTypeError(() => operation(current), "different key-value store"); + expectTypeError( + () => operation({_map_name: table, _seqno: 1}), + "KV Map Handle object expected"); + } + handle._map_name = "public:ccf.internal.table"; + handle._source = "CurrentTx"; + if (handle.size !== (populated ? 1 : 0)) { + throw new Error(`Historical handle identity changed for ${table}`); + } + for (const [name, operation] of readOperations(currentReader)) { + expectTypeError(() => operation(handle), "different key-value store"); + } + } +} +)JS"; + auto func = ctx.get_exported_function( + script, "run", "/test/historical-signature-tables.js"); + const auto result = ctx.call_with_rt_options( + func, {}, std::nullopt, ccf::js::core::RuntimeLimitsPolicy::NONE); + if (result.is_exception()) + { + const auto [reason, trace] = ctx.error_message(); + FAIL_CHECK(reason); + } + CHECK(JS_HasException(ctx) == 0); + } + } } TEST_CASE("Historical state") diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 190e1a31425a..6ea71b4ca0ca 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -6,6 +6,7 @@ #include "ccf/ds/hex.h" #include "ccf/tx.h" #include "ds/internal_logger.h" +#include "kv/internal_table_names.h" #include "kv/tx_pimpl.h" #include "kv_serialiser.h" #include "kv_types.h" @@ -491,6 +492,7 @@ namespace ccf::kv rollback_count(rollback_count_) { version = reserved_tx_id.seqno; + pimpl->role = PrivateImpl::Role::Reserved; pimpl->commit_view = reserved_tx_id.view; pimpl->read_txid = TxID(read_term, reserved_tx_id.seqno - 1); } @@ -503,6 +505,28 @@ namespace ccf::kv throw std::logic_error("Transaction already committed"); } + for (const auto& [map_name, changes] : all_changes) + { + if (!is_signature_table(map_name)) + { + const auto message = fmt::format( + "Reserved transaction cannot write to map '{}'", map_name); + LOG_FAIL_FMT("{}", message); + throw MapAccessDenied(message); + } + + if ( + changes.changeset->read_version.has_value() || + !changes.changeset->reads.empty()) + { + const auto message = fmt::format( + "Reserved transaction cannot depend on reads from map '{}'", + map_name); + LOG_FAIL_FMT("{}", message); + throw MapAccessDenied(message); + } + } + // A reserved transaction must fill its version with a ledger entry, so // one which only reads would leave a hole at that version. if (!has_writes()) diff --git a/src/kv/internal_table_names.h b/src/kv/internal_table_names.h index 72d9bdca598c..d32e2d02080d 100644 --- a/src/kv/internal_table_names.h +++ b/src/kv/internal_table_names.h @@ -2,6 +2,8 @@ // Licensed under the Apache 2.0 License. #pragma once +#include + namespace ccf::Tables { // Names of the internal tables which the KV inspects when applying a ledger @@ -13,4 +15,14 @@ namespace ccf::Tables static constexpr auto SERIALISED_MERKLE_TREE = "public:ccf.internal.tree"; static constexpr auto ENCRYPTED_PAST_LEDGER_SECRET = "public:ccf.internal.historical_encrypted_ledger_secret"; +} + +namespace ccf::kv +{ + inline constexpr bool is_signature_table(std::string_view name) + { + return name == ccf::Tables::SIGNATURES || + name == ccf::Tables::COSE_SIGNATURES || + name == ccf::Tables::SERIALISED_MERKLE_TREE; + } } \ No newline at end of file diff --git a/src/kv/store.h b/src/kv/store.h index 62e2ecf969c0..816028e1356c 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1328,19 +1328,45 @@ namespace ccf::kv ReadOnlyTx create_read_only_tx() override { + if (is_historical) + { + return create_read_only_tx_at_replicated_state(); + } return {this}; } std::unique_ptr create_read_only_tx_ptr() override { + if (is_historical) + { + std::lock_guard vguard(version_lock); + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) + return std::unique_ptr(new ReadOnlyTx( + this, std::max(last_replicated, compacted.load()), rollback_count)); + } return std::make_unique(this); } TxDiff create_tx_diff() override { + if (is_historical) + { + std::lock_guard vguard(version_lock); + return TxDiff( + this, std::max(last_replicated, compacted.load()), rollback_count); + } return {this}; } + ReadOnlyTx create_read_only_tx_at_replicated_state() + { + std::lock_guard vguard(version_lock); + // Consensus may compact synchronously in replicate(), before + // last_replicated is advanced. Both versions are complete prefixes. + return ReadOnlyTx( + this, std::max(last_replicated, compacted.load()), rollback_count); + } + CommittableTx create_tx() { return {this}; diff --git a/src/kv/test/kv_contention.cpp b/src/kv/test/kv_contention.cpp index 4ec616924131..3c1f26ae84c4 100644 --- a/src/kv/test/kv_contention.cpp +++ b/src/kv/test/kv_contention.cpp @@ -384,11 +384,11 @@ DOCTEST_TEST_CASE( { DOCTEST_INFO("Read full chain of writes"); - // Use ReservedTx as a hack to read historic entries, rather than via - // deserialisation + // Pin ordinary transactions to each earlier revision of this map. for (size_t read_at = 1; read_at < last_write_version; ++read_at) { - auto tx = kv_store.create_reserved_tx({store_commit_term, read_at + 1}); + auto tx = kv_store.create_tx(); + tx.set_read_txid({store_commit_term, read_at}, store_commit_term); auto h = tx.ro(map); auto v = h->get(k); diff --git a/src/kv/test/kv_serialisation.cpp b/src/kv/test/kv_serialisation.cpp index c51663731a17..857f733eefc1 100644 --- a/src/kv/test/kv_serialisation.cpp +++ b/src/kv/test/kv_serialisation.cpp @@ -1,5 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. +#include "ccf/kv/value.h" #include "ds/internal_logger.h" #include "kv/kv_serialiser.h" #include "kv/null_encryptor.h" @@ -531,9 +532,10 @@ TEST_CASE( kv_store.set_encryptor(encryptor); kv_store.set_max_transaction_size(1); - MapTypes::StringString map("public:signature"); + ccf::kv::RawCopySerialisedValue> tree( + ccf::Tables::SERIALISED_MERKLE_TREE); auto tx = kv_store.create_reserved_tx(kv_store.next_txid()); - tx.rw(map)->put("signature", std::string(512, 'A')); + tx.wo(tree)->put(std::vector(512, 'A')); const auto [result, data, claims, commit_evidence, hooks] = tx.commit_reserved(); @@ -895,6 +897,8 @@ TEST_CASE_TEMPLATE( ccf::kv::Store kv_store; auto encryptor = std::make_shared(); kv_store.set_encryptor(encryptor); + auto consensus = std::make_shared(); + kv_store.set_consensus(consensus); MapType map("public:map"); @@ -911,19 +915,19 @@ TEST_CASE_TEMPLATE( MapType map2("public:map"); - auto tx = kv_store.create_reserved_tx(kv_store.next_txid()); + auto tx = kv_store.create_tx(); auto handle = tx.rw(map); handle->put(k1, v1); handle->put(k2, v2); - auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = - tx.commit_reserved(); - auto& success = success_; - auto& data = data_; - REQUIRE(success == ccf::kv::CommitResult::SUCCESS); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto data = consensus->get_latest_data(); + REQUIRE(data.has_value()); kv_store.compact(kv_store.current_version()); - REQUIRE(kv_store2.deserialize(data)->apply() == ccf::kv::ApplyResult::PASS); + REQUIRE( + kv_store2.deserialize(data.value())->apply() == + ccf::kv::ApplyResult::PASS); auto tx2 = kv_store2.create_tx(); auto handle2 = tx2.rw(map2); diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index 81a6869d5e49..715548661369 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -40,6 +40,37 @@ struct MapTypes using UntypedMap = ccf::kv::untyped::Map; }; +static ccf::kv::PendingTxInfo make_signature_entry( + ccf::kv::Store& store, const ccf::TxID& txid, uint8_t marker) +{ + auto signature = store.create_reserved_tx(txid); + signature.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); + signature.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {marker}); + signature.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({marker}); + return signature.commit_reserved(); +} + +static ccf::kv::CommitResult publish_signature_entry( + ccf::kv::Store& store, const ccf::TxID& txid, uint8_t marker) +{ + auto info = make_signature_entry(store, txid, marker); + if (info.success != ccf::kv::CommitResult::SUCCESS) + { + return info.success; + } + return store.commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true); +} + TEST_CASE("Map name parsing") { using SD = ccf::kv::SecurityDomain; @@ -66,6 +97,735 @@ TEST_CASE("Map name parsing") REQUIRE(parse("public:ccf_foo") == mp(SD::PUBLIC, AC::APPLICATION)); } +TEST_CASE("Live transactions cannot acquire signature table handles") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Restricted table: ", std::string_view(name)); + MapTypes::StringString typed_map(name); + + auto tx = store.create_tx(); + CHECK_THROWS_AS(tx.ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx.rw(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx.wo(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.rw(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.wo(name), ccf::kv::MapAccessDenied); + + auto tx_ptr = store.create_tx_ptr(); + CHECK_THROWS_AS(tx_ptr->ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx_ptr->rw(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx_ptr->wo(typed_map), ccf::kv::MapAccessDenied); + ccf::kv::Tx direct_tx(&store); + CHECK_THROWS_AS(direct_tx.ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(direct_tx.rw(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(direct_tx.wo(typed_map), ccf::kv::MapAccessDenied); + + auto ro = store.create_read_only_tx(); + CHECK_THROWS_AS(ro.ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + ro.ro(name), ccf::kv::MapAccessDenied); + auto ro_ptr = store.create_read_only_tx_ptr(); + CHECK_THROWS_AS(ro_ptr->ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + ro_ptr->ro(name), ccf::kv::MapAccessDenied); + ccf::kv::ReadOnlyTx direct_ro(&store); + CHECK_THROWS_AS(direct_ro.ro(typed_map), ccf::kv::MapAccessDenied); + + auto diff = store.create_tx_diff(); + CHECK_THROWS_AS(diff.diff(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + diff.diff(name), ccf::kv::MapAccessDenied); + ccf::kv::TxDiff direct_diff(&store); + CHECK_THROWS_AS(direct_diff.diff(typed_map), ccf::kv::MapAccessDenied); + CHECK(store.get_map(store.current_version(), name) == nullptr); + } + CHECK(store.current_version() == 0); +} + +TEST_CASE("Signature read denial is independent of a pending signature") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + + const auto signature_txid = store.next_txid(); + { + auto tx = store.create_tx(); + CHECK_THROWS_AS( + tx.ro(ccf::Tables::SIGNATURES), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.ro(ccf::Tables::COSE_SIGNATURES), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE), + ccf::kv::MapAccessDenied); + + MapTypes::StringString ordinary("public:ordinary"); + tx.rw(ordinary)->put("key", "value"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + auto read = store.create_read_only_tx(); + CHECK(read.ro(ordinary)->get("key") == "value"); + } + + auto signature = store.create_reserved_tx(signature_txid); + signature.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature( + ccf::kv::test::PrimaryNodeId, signature_txid.seqno)); + signature.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {42}); + signature.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({43}); + auto info = signature.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + store.commit( + signature_txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true) == ccf::kv::CommitResult::SUCCESS); + + auto tx = store.create_tx(); + CHECK_THROWS_AS( + tx.ro(ccf::Tables::SIGNATURES), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.ro(ccf::Tables::COSE_SIGNATURES), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE), + ccf::kv::MapAccessDenied); +} + +TEST_CASE("Historical signature entries remain readable") +{ + ccf::kv::Store source; + source.set_encryptor(std::make_shared()); + const auto txid = source.next_txid(); + auto signature = source.create_reserved_tx(txid); + signature.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); + signature.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {42}); + signature.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({43}); + auto info = signature.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + + ccf::kv::Store historical(true); + historical.set_encryptor(std::make_shared()); + REQUIRE( + historical.deserialize(info.data)->apply() == + ccf::kv::ApplyResult::PASS_SIGNATURE); + + auto tx = historical.create_read_only_tx(); + REQUIRE( + tx.ro(ccf::Tables::SIGNATURES)->get()->seqno == + txid.seqno); + REQUIRE( + tx.ro(ccf::Tables::COSE_SIGNATURES) + ->get(ccf::IdentityType::CLASSICAL) == std::vector{42}); + REQUIRE( + tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE) + ->get() == std::vector{43}); + + ccf::Signatures signatures(ccf::Tables::SIGNATURES); + ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); + ccf::SerialisedMerkleTree tree(ccf::Tables::SERIALISED_MERKLE_TREE); + auto ptr = historical.create_read_only_tx_ptr(); + REQUIRE(ptr->ro(signatures)->get()->seqno == txid.seqno); + REQUIRE( + ptr->ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == + std::vector{42}); + REQUIRE(ptr->ro(tree)->get() == std::vector{43}); + + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Historical table: ", std::string_view(name)); + auto untyped_read = historical.create_read_only_tx(); + REQUIRE(untyped_read.ro(name)->size() == 1); + auto untyped_ptr = historical.create_read_only_tx_ptr(); + REQUIRE(untyped_ptr->ro(name)->size() == 1); + auto diff = historical.create_tx_diff(); + REQUIRE(diff.diff(name)->size() == 1); + + ccf::kv::ReadOnlyTx direct_ro(&historical); + CHECK_THROWS_AS( + direct_ro.ro(name), ccf::kv::MapAccessDenied); + auto ordinary = historical.create_tx(); + CHECK_THROWS_AS( + ordinary.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + ordinary.wo(name), ccf::kv::MapAccessDenied); + auto ordinary_ptr = historical.create_tx_ptr(); + CHECK_THROWS_AS( + ordinary_ptr->rw(name), ccf::kv::MapAccessDenied); + } + auto typed_diff = historical.create_tx_diff(); + REQUIRE(typed_diff.diff(cose_signatures)->size() == 1); +} + +TEST_CASE("Reserved transactions cannot backfill readable maps") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto reserved = store.create_reserved_tx(store.next_txid()); + CHECK_THROWS_AS( + reserved.wo("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.rw("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.ro("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.ro(ccf::Tables::SIGNATURES), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.rw(ccf::Tables::SIGNATURES), + ccf::kv::MapAccessDenied); + CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); +} + +TEST_CASE("Native direct map lookups enforce transaction access policy") +{ + class DirectLookupTx : public ccf::kv::BaseTx + { + public: + using ccf::kv::BaseTx::AccessMode; + using ccf::kv::BaseTx::BaseTx; + + ccf::kv::MapChanges lookup(const std::string& name, AccessMode access) + { + return get_map_and_change_set_by_name(name, false, access); + } + }; + + using Access = DirectLookupTx::AccessMode; + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + DirectLookupTx ordinary(&store); + DirectLookupTx reserved(&store); + auto reserved_role = store.create_reserved_tx(store.next_txid()); + static_cast(reserved) = std::move(reserved_role); + + for (const auto access : + {Access::ReadOnly, Access::ReadWrite, Access::WriteOnly, Access::Diff}) + { + CHECK_THROWS_AS( + reserved.lookup("public:ordinary", access), ccf::kv::MapAccessDenied); + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Direct lookup table: ", std::string_view(name)); + CHECK_THROWS_AS(ordinary.lookup(name, access), ccf::kv::MapAccessDenied); + if (access != Access::WriteOnly) + { + CHECK_THROWS_AS( + reserved.lookup(name, access), ccf::kv::MapAccessDenied); + } + CHECK(store.get_map(store.current_version(), name) == nullptr); + } + } + CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); + + auto normal = ordinary.lookup("public:ordinary", Access::ReadOnly); + REQUIRE(normal.map != nullptr); + REQUIRE(normal.changeset != nullptr); + auto signature = reserved.lookup(ccf::Tables::SIGNATURES, Access::WriteOnly); + REQUIRE(signature.map != nullptr); + REQUIRE(signature.changeset != nullptr); +} + +TEST_CASE("Signature restrictions apply only to the exact table family") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + for (const auto* name : + {"public:ccf.internal.signatures_extra", + "public:ccf.internal.cose_signatures.extra", + "public:ccf.internal.tree_extra", + "ccf.internal.signatures", + "ccf.internal.tree", + ccf::Tables::ENCRYPTED_PAST_LEDGER_SECRET}) + { + INFO("Allowed table: ", std::string_view(name)); + MapTypes::StringString map(name); + auto tx = store.create_tx(); + tx.wo(map)->put("key", "first"); + REQUIRE(tx.ro(map)->get("key") == "first"); + tx.rw(map)->put("key", "second"); + REQUIRE(tx.ro(map)->get("key") == "second"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + auto read = store.create_read_only_tx(); + REQUIRE(read.ro(map)->get("key") == "second"); + auto diff = store.create_tx_diff(); + REQUIRE(diff.diff(map)->size() == 1); + auto reserved = store.create_reserved_tx(store.next_txid()); + CHECK_THROWS_AS(reserved.wo(map), ccf::kv::MapAccessDenied); + } +} + +TEST_CASE("Denied signature handles do not acquire a snapshot") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto tx = store.create_tx(); + auto ro = store.create_read_only_tx(); + CHECK_THROWS_AS( + tx.ro(ccf::Tables::SIGNATURES), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + ro.ro(ccf::Tables::SIGNATURES), ccf::kv::MapAccessDenied); + MapTypes::StringString map("public:ordinary"); + auto writer = store.create_tx(); + writer.rw(map)->put("key", "new"); + REQUIRE(writer.commit() == ccf::kv::CommitResult::SUCCESS); + REQUIRE(tx.ro(map)->get("key") == "new"); + REQUIRE(ro.ro(map)->get("key") == "new"); +} + +TEST_CASE("Reserved write-only handles cannot be upgraded to readable handles") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto reserved = store.create_reserved_tx(store.next_txid()); + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Reserved table: ", std::string_view(name)); + MapTypes::StringString map(name); + auto* typed_handle = reserved.wo(map); + CHECK(reserved.wo(map) == typed_handle); + CHECK_THROWS_AS(reserved.ro(map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(reserved.rw(map), ccf::kv::MapAccessDenied); + auto* untyped_handle = reserved.wo(name); + CHECK(reserved.wo(name) == untyped_handle); + CHECK_THROWS_AS( + reserved.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.rw(name), ccf::kv::MapAccessDenied); + } +} + +TEST_CASE("Reserved transactions reject all recorded read dependencies") +{ + for (const std::string_view observation : + {"get", "version", "foreach", "range", "size", "clear"}) + { + INFO("Reserved observation: ", observation); + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + store.set_consensus( + std::make_shared()); + const auto baseline = store.next_txid(); + REQUIRE( + publish_signature_entry(store, baseline, 1) == + ccf::kv::CommitResult::SUCCESS); + auto reserved = store.create_reserved_tx(store.next_txid()); + auto* handle = + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); + const auto key = ccf::SerialisedMerkleTree::create_unit(); + if (observation == "get") + { + REQUIRE(handle->get(key).has_value()); + } + else if (observation == "version") + { + REQUIRE(handle->get_version_of_previous_write(key) == baseline.seqno); + } + else if (observation == "foreach") + { + handle->foreach([](const auto&, const auto&) { return true; }); + } + else if (observation == "range") + { + handle->range( + [](const auto&, const auto&) {}, std::nullopt, std::nullopt); + } + else if (observation == "size") + { + REQUIRE(handle->size() == 1); + } + else + { + reserved + .wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->clear(); + } + handle->put(key, {2}); + reserved.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {2}); + CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); + auto check = store.create_read_only_tx_at_replicated_state(); + REQUIRE( + check.ro(ccf::Tables::SERIALISED_MERKLE_TREE) + ->get() == std::vector{1}); + REQUIRE( + check.ro(ccf::Tables::COSE_SIGNATURES) + ->get(ccf::IdentityType::CLASSICAL) == std::vector{1}); + } +} + +TEST_CASE("Reserved commit validates maps even after base reconstruction") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto ordinary = store.create_tx(); + ordinary.wo("public:ordinary")->put("key", "value"); + auto reserved = store.create_reserved_tx(store.next_txid()); + static_cast(reserved) = std::move(ordinary); + CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); + CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); +} + +TEST_CASE("Reserved clear cannot depend on an empty signature table") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto reserved = store.create_reserved_tx(store.next_txid()); + auto* tree = + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); + tree->clear(); + tree->put({1}); + CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); + CHECK( + store.get_map( + store.current_version(), ccf::Tables::SERIALISED_MERKLE_TREE) == nullptr); +} + +TEST_CASE("Materialised reads exclude gaps and cannot tear signature state") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + MapTypes::StringString raw("public:raw"); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "old"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto old_signature = store.next_txid(); + REQUIRE( + publish_signature_entry(store, old_signature, 1) == + ccf::kv::CommitResult::SUCCESS); + const auto pending_signature = store.next_txid(); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "new"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + REQUIRE(store.current_version() == pending_signature.seqno + 1); + REQUIRE(consensus->number_of_replicas() == old_signature.seqno); + + auto cold = store.create_read_only_tx_at_replicated_state(); + auto warm = store.create_read_only_tx_at_replicated_state(); + REQUIRE( + warm.ro(ccf::Tables::SIGNATURES)->get()->seqno == + old_signature.seqno); + REQUIRE(warm.ro(raw)->get("key") == "old"); + REQUIRE( + publish_signature_entry(store, pending_signature, 2) == + ccf::kv::CommitResult::SUCCESS); + + for (auto* read : {&cold, &warm}) + { + REQUIRE(read->ro(raw)->get("key") == "old"); + REQUIRE( + read->ro(ccf::Tables::SIGNATURES)->get()->seqno == + old_signature.seqno); + REQUIRE( + read->ro(ccf::Tables::COSE_SIGNATURES) + ->get(ccf::IdentityType::CLASSICAL) == std::vector{1}); + REQUIRE( + read->ro(ccf::Tables::SERIALISED_MERKLE_TREE) + ->get() == std::vector{1}); + REQUIRE( + read->ro(ccf::Tables::SIGNATURES)->size() == 1); + } + + auto current = store.create_read_only_tx_at_replicated_state(); + REQUIRE(current.ro(raw)->get("key") == "new"); + REQUIRE( + current.ro(ccf::Tables::SIGNATURES)->get()->seqno == + pending_signature.seqno); + REQUIRE( + current.ro(ccf::Tables::COSE_SIGNATURES) + ->get(ccf::IdentityType::CLASSICAL) == std::vector{2}); + REQUIRE( + current.ro(ccf::Tables::SERIALISED_MERKLE_TREE) + ->get() == std::vector{2}); +} + +TEST_CASE("Materialised reads reject handles after a rollback epoch changes") +{ + for (const bool is_historical : {false, true}) + { + INFO("Historical store: ", is_historical); + ccf::kv::Store store(is_historical); + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + constexpr ccf::View initial_view = 2; + constexpr ccf::View replacement_view = 3; + store.initialise_term(initial_view); + MapTypes::StringString raw("public:raw"); + ccf::Signatures signatures(ccf::Tables::SIGNATURES); + ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); + ccf::SerialisedMerkleTree tree(ccf::Tables::SERIALISED_MERKLE_TREE); + + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "old"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto initial_signature = store.next_txid(); + REQUIRE( + publish_signature_entry(store, initial_signature, 1) == + ccf::kv::CommitResult::SUCCESS); + + auto old = store.create_read_only_tx_at_replicated_state(); + REQUIRE(old.ro(raw)->get("key") == "old"); + REQUIRE(old.ro(signatures)->get()->seqno == initial_signature.seqno); + auto public_read = store.create_read_only_tx(); + auto pointer_read = store.create_read_only_tx_ptr(); + auto diff = store.create_tx_diff(); + if (is_historical) + { + REQUIRE( + public_read.ro(signatures)->get()->seqno == initial_signature.seqno); + REQUIRE( + pointer_read->ro(signatures)->get()->seqno == initial_signature.seqno); + REQUIRE(diff.diff(cose_signatures)->size() == 1); + } + + store.rollback({initial_view, 0}, replacement_view); + consensus->view_history.rollback(0); + consensus->flush(); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "replacement"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto replacement_signature = store.next_txid(); + REQUIRE(replacement_signature.view == replacement_view); + REQUIRE(replacement_signature.seqno == initial_signature.seqno); + REQUIRE( + publish_signature_entry(store, replacement_signature, 2) == + ccf::kv::CommitResult::SUCCESS); + + CHECK_THROWS_AS(old.ro(raw), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS(old.ro(signatures), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS(old.ro(cose_signatures), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS(old.ro(tree), ccf::kv::CompactedVersionConflict); + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Invalidated table: ", std::string_view(name)); + CHECK_THROWS_AS( + old.ro(name), ccf::kv::CompactedVersionConflict); + } + if (is_historical) + { + CHECK_THROWS_AS( + public_read.ro(signatures), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS(public_read.ro(tree), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS( + pointer_read->ro(signatures), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS( + pointer_read->ro(cose_signatures), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS( + diff.diff(cose_signatures), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS( + diff.diff(ccf::Tables::SERIALISED_MERKLE_TREE), + ccf::kv::CompactedVersionConflict); + } + + auto fresh = store.create_read_only_tx_at_replicated_state(); + REQUIRE(fresh.ro(raw)->get("key") == "replacement"); + REQUIRE(fresh.ro(signatures)->get()->seqno == replacement_signature.seqno); + REQUIRE( + fresh.ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == + std::vector{2}); + REQUIRE(fresh.ro(tree)->get() == std::vector{2}); + if (is_historical) + { + auto fresh_pointer = store.create_read_only_tx_ptr(); + REQUIRE(fresh_pointer->ro(tree)->get() == std::vector{2}); + auto fresh_diff = store.create_tx_diff(); + REQUIRE(fresh_diff.diff(cose_signatures)->size() == 1); + } + } +} + +TEST_CASE("Materialised reads reject rollback during snapshot acquisition") +{ + class ReplacingStore : public ccf::kv::Store + { + public: + std::function replace_during_lookup = nullptr; + bool replacement_triggered = false; + + std::shared_ptr get_map( + ccf::kv::Version version, const std::string& name) override + { + if ( + name == ccf::Tables::COSE_SIGNATURES && + replace_during_lookup != nullptr) + { + auto replace = replace_during_lookup; + replace_during_lookup = nullptr; + replacement_triggered = true; + replace(); + } + return ccf::kv::Store::get_map(version, name); + } + }; + + ReplacingStore store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + constexpr ccf::View initial_view = 2; + constexpr ccf::View replacement_view = 3; + store.initialise_term(initial_view); + MapTypes::StringString raw("public:raw"); + ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); + ccf::SerialisedMerkleTree tree(ccf::Tables::SERIALISED_MERKLE_TREE); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "old"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto initial_signature = store.next_txid(); + REQUIRE( + publish_signature_entry(store, initial_signature, 1) == + ccf::kv::CommitResult::SUCCESS); + auto old = store.create_read_only_tx_at_replicated_state(); + REQUIRE(old.ro(raw)->get("key") == "old"); + REQUIRE(old.ro(tree)->get() == std::vector{1}); + + store.replace_during_lookup = [&]() { + store.rollback({initial_view, 0}, replacement_view); + consensus->view_history.rollback(0); + consensus->flush(); + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "replacement"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto replacement_signature = store.next_txid(); + REQUIRE(replacement_signature.view == replacement_view); + REQUIRE(replacement_signature.seqno == initial_signature.seqno); + REQUIRE( + publish_signature_entry(store, replacement_signature, 2) == + ccf::kv::CommitResult::SUCCESS); + }; + + CHECK_THROWS_AS(old.ro(cose_signatures), ccf::kv::CompactedVersionConflict); + REQUIRE(store.replacement_triggered); + CHECK_THROWS_AS(old.ro(tree), ccf::kv::CompactedVersionConflict); + auto fresh = store.create_read_only_tx_at_replicated_state(); + REQUIRE(fresh.ro(raw)->get("key") == "replacement"); + REQUIRE( + fresh.ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == + std::vector{2}); + REQUIRE(fresh.ro(tree)->get() == std::vector{2}); +} + +TEST_CASE("Materialised reads include a prefix compacted inside replication") +{ + class CompactingConsensus : public ccf::kv::test::PrimaryStubConsensus + { + ccf::kv::Store& store; + + public: + bool compact_before_return = false; + std::optional observed_signature; + + explicit CompactingConsensus(ccf::kv::Store& store_) : store(store_) {} + + bool replicate(const ccf::kv::BatchVector& entries, ccf::View view) override + { + const auto result = PrimaryStubConsensus::replicate(entries, view); + if (compact_before_return) + { + store.compact(std::get<0>(entries.back())); + auto read = store.create_read_only_tx_at_replicated_state(); + auto signature = + read.ro(ccf::Tables::SIGNATURES)->get(); + if (signature.has_value()) + { + observed_signature = signature->seqno; + } + } + return result; + } + }; + + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(store); + store.set_consensus(consensus); + const auto txid = store.next_txid(); + consensus->compact_before_return = true; + REQUIRE( + publish_signature_entry(store, txid, 1) == ccf::kv::CommitResult::SUCCESS); + REQUIRE(store.compacted_version() == txid.seqno); + REQUIRE(consensus->observed_signature == txid.seqno); +} + +TEST_CASE("Materialised read contexts cannot acquire a writable commit view") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + store.set_consensus(std::make_shared()); + store.initialise_term(2); + MapTypes::StringString map("public:ordinary"); + { + auto tx = store.create_tx(); + tx.rw(map)->put("key", "baseline"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + auto read = store.create_read_only_tx_at_replicated_state(); + auto* untyped = read.ro(map.get_name()); + using Serialiser = MapTypes::StringString::ValueSerialiser; + untyped->put( + Serialiser::to_serialised("key"), Serialiser::to_serialised("pending")); + + auto tx = store.create_tx(); + static_cast(tx) = std::move(read); + CHECK_THROWS_AS(tx.rw(map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx.wo(map), ccf::kv::MapAccessDenied); + CHECK_THROWS_WITH_AS( + tx.set_read_txid({2, 1}, 2), "Read TxID already set", std::logic_error); + CHECK(tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(store.current_version() == 1); + auto check = store.create_read_only_tx(); + CHECK(check.ro(map)->get("key") == "baseline"); +} + TEST_CASE("Zero-revision whole-map dependencies") { using Result = ccf::kv::CommitResult; @@ -2589,24 +3349,25 @@ TEST_CASE("Deserialising from other Store") auto encryptor = std::make_shared(); ccf::kv::Store store; store.set_encryptor(encryptor); + auto consensus = std::make_shared(); + store.set_consensus(consensus); MapTypes::NumString public_map("public:public"); MapTypes::NumString private_map("private"); - auto tx1 = store.create_reserved_tx(store.next_txid()); + auto tx1 = store.create_tx(); auto handle1 = tx1.rw(public_map); auto handle2 = tx1.rw(private_map); handle1->put(42, "aardvark"); handle2->put(14, "alligator"); - auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = - tx1.commit_reserved(); - auto& success = success_; - auto& data = data_; - REQUIRE(success == ccf::kv::CommitResult::SUCCESS); + REQUIRE(tx1.commit() == ccf::kv::CommitResult::SUCCESS); + const auto data = consensus->get_latest_data(); + REQUIRE(data.has_value()); ccf::kv::Store clone; clone.set_encryptor(encryptor); - REQUIRE(clone.deserialize(data)->apply() == ccf::kv::ApplyResult::PASS); + REQUIRE( + clone.deserialize(data.value())->apply() == ccf::kv::ApplyResult::PASS); } TEST_CASE("Transaction diffs") @@ -2780,6 +3541,8 @@ TEST_CASE("Deserialise return status") ccf::kv::Store store; auto encryptor = std::make_shared(); store.set_encryptor(encryptor); + auto consensus = std::make_shared(); + store.set_consensus(consensus); ccf::Signatures signatures(ccf::Tables::SIGNATURES); ccf::SerialisedMerkleTree serialised_tree( @@ -2796,24 +3559,22 @@ TEST_CASE("Deserialise return status") store.set_history(history); { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_tx(); auto data_handle = tx.rw(data); data_handle->put(42, 42); - auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = - tx.commit_reserved(); - auto& success = success_; - auto& serialised_data = data_; - REQUIRE(success == ccf::kv::CommitResult::SUCCESS); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto serialised_data = consensus->get_latest_data(); + REQUIRE(serialised_data.has_value()); REQUIRE( - store.deserialize(serialised_data)->apply() == + store.deserialize(serialised_data.value())->apply() == ccf::kv::ApplyResult::PASS); } { auto tx = store.create_reserved_tx(store.next_txid()); - auto sig_handle = tx.rw(signatures); - auto tree_handle = tx.rw(serialised_tree); + auto sig_handle = tx.wo(signatures); + auto tree_handle = tx.wo(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); sig_handle->put(sigv); tree_handle->put({}); @@ -2830,17 +3591,35 @@ TEST_CASE("Deserialise return status") INFO("Signature transactions with additional contents should fail"); { - auto tx = store.create_reserved_tx(store.next_txid()); - auto sig_handle = tx.rw(signatures); - auto data_handle = tx.rw(data); + // The transaction API rejects this mixture, so exercise ledger admission + // with an explicitly malformed serialised entry. + ccf::kv::RawKvStoreSerialiser serialiser( + encryptor, + ccf::TxID{store.commit_view(), store.current_version() + 1}, + ccf::kv::EntryType::WriteSet, + 0); + const auto serialise_single_write = + [&serialiser]( + const std::string& name, + const ccf::kv::serialisers::SerialisedEntry& key, + const ccf::kv::serialisers::SerialisedEntry& value) { + serialiser.start_map(name, ccf::kv::SecurityDomain::PUBLIC); + serialiser.serialise_entry_version(ccf::kv::NoVersion); + serialiser.serialise_count_header(0); + serialiser.serialise_count_header(1); + serialiser.serialise_write(key, value); + serialiser.serialise_count_header(0); + }; ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); - sig_handle->put(sigv); - data_handle->put(43, 43); - auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = - tx.commit_reserved(); - auto& success = success_; - auto& serialised_data = data_; - REQUIRE(success == ccf::kv::CommitResult::SUCCESS); + serialise_single_write( + signatures.get_name(), + ccf::Signatures::create_unit(), + ccf::Signatures::ValueSerialiser::to_serialised(sigv)); + serialise_single_write( + data.get_name(), + MapTypes::NumNum::KeySerialiser::to_serialised(43), + MapTypes::NumNum::ValueSerialiser::to_serialised(43)); + const auto serialised_data = serialiser.get_raw_data(); REQUIRE( store.deserialize(serialised_data)->apply() == @@ -3880,7 +4659,8 @@ TEST_CASE("CommittableTx guards") const auto baseline_txid = kv_store.current_txid(); auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); - reserved.rw(map)->put("k", "from_reserved"); + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({42}); // Roll the store back, invalidating the rollback_count that `reserved` // captured when it was created. @@ -3915,7 +4695,8 @@ TEST_CASE("CommittableTx guards") kv_store.set_encryptor(std::make_shared()); auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); - reserved.rw(map)->put("k", "v"); + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({42}); REQUIRE( reserved.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); @@ -3954,22 +4735,22 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - { - // Establish the map, so the reserved tx below can read from it without - // creating it - auto tx = kv_store.create_tx(); - tx.rw(map)->put("k", "v"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } + const auto baseline = kv_store.next_txid(); + REQUIRE( + make_signature_entry(kv_store, baseline, 42).success == + ccf::kv::CommitResult::SUCCESS); // Such a transaction would otherwise succeed with an empty ledger entry, // leaving nothing at its reserved version auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); - REQUIRE(reserved.rw(map)->get("k") == "v"); + auto* handle = + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); + REQUIRE(handle->get(ccf::SerialisedMerkleTree::create_unit()).has_value()); REQUIRE_THROWS_WITH_AS( reserved.commit_reserved(), - "Reserved transaction cannot be empty", - std::logic_error); + "Reserved transaction cannot depend on reads from map " + "'public:ccf.internal.tree'", + ccf::kv::MapAccessDenied); REQUIRE_THROWS_WITH_AS( auto _ = reserved.commit_version(), "Transaction not yet committed", @@ -4619,11 +5400,11 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") size_t n = 0; while (!stop_token.stop_requested()) { - // Takes maps_lock and searches the map set. Looks up names in the - // range being inserted, so the search path traverses the nodes - // add_dynamic_map is writing. Deliberately avoids current_version(), - // so this contends only on maps_lock. - (void)store.get_map(1, fmt::format("public:reserved_{}", n % 2000)); + // These names are repeatedly created and removed. The lookup holds + // maps_lock, and avoids any additional ordering with the writer. + const auto* name = (n % 2 == 0) ? ccf::Tables::SIGNATURES : + ccf::Tables::SERIALISED_MERKLE_TREE; + (void)store.get_map(2, name); n++; } }); @@ -4632,16 +5413,16 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") constexpr size_t reserved_txs = 2000; for (size_t i = 0; i < reserved_txs; ++i) { - // Each reserved transaction writes to a map that does not exist yet, so - // committing it adds to the Store's map set. Nothing else here may take - // maps_lock, or it would order the write against the readers and hide the - // race being reproduced. - auto tx = store.create_reserved_tx(store.next_txid()); - tx.rw(fmt::format("public:reserved_{}", i)) - ->put("k", "v"); - const auto [result, data, claims, commit_evidence, hooks] = - tx.commit_reserved(); - REQUIRE(result == ccf::kv::CommitResult::SUCCESS); + // Rollback removes the signature tables so the next reservation creates + // them again, exercising add_dynamic_map on every iteration. + const auto txid = store.next_txid(); + REQUIRE( + make_signature_entry(store, txid, 42).success == + ccf::kv::CommitResult::SUCCESS); + if (i + 1 < reserved_txs) + { + store.rollback({txid.view, 1}, txid.view); + } } for (auto& reader : readers) @@ -4650,14 +5431,12 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") } readers.clear(); - // Confirm the writes really did extend the map set, so this exercises - // Store::add_dynamic_map rather than silently doing nothing. + // Confirm the final reservation really recreated the signature tables. REQUIRE( - store.get_map(store.current_version(), "public:reserved_0") != nullptr); + store.get_map(store.current_version(), ccf::Tables::SIGNATURES) != nullptr); REQUIRE( store.get_map( - store.current_version(), - fmt::format("public:reserved_{}", reserved_txs - 1)) != nullptr); + store.current_version(), ccf::Tables::SERIALISED_MERKLE_TREE) != nullptr); } // Exposes the version the chunker has recorded entries up to, which is the @@ -4686,7 +5465,6 @@ class RollingBackPendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; - MapTypes::StringString& table; ccf::TxID rollback_to; ccf::kv::Term rollback_term; @@ -4694,21 +5472,17 @@ class RollingBackPendingTx : public ccf::kv::PendingTx RollingBackPendingTx( ccf::TxID txid_, ccf::kv::Store& store_, - MapTypes::StringString& table_, ccf::TxID rollback_to_, ccf::kv::Term rollback_term_) : txid(txid_), store(store_), - table(table_), rollback_to(rollback_to_), rollback_term(rollback_term_) {} ccf::kv::PendingTxInfo call() override { - auto tx = store.create_reserved_tx(txid); - tx.rw(table)->put("key", "value"); - auto info = tx.commit_reserved(); + auto info = make_signature_entry(store, txid, 42); store.rollback(rollback_to, rollback_term); return info; } @@ -4749,7 +5523,7 @@ TEST_CASE("Chunk metadata is not restored by a batch a rollback discarded") store.commit( reserved, std::make_unique( - reserved, store, map, baseline_txid, initial_term + 1), + reserved, store, baseline_txid, initial_term + 1), false); } @@ -5055,8 +5829,8 @@ TEST_CASE("Ledger entry chunk request") { auto txid = store.next_txid(); auto tx = store.create_reserved_tx(txid); - auto sig_handle = tx.rw(signatures); - auto tree_handle = tx.rw(serialised_tree); + auto sig_handle = tx.wo(signatures); + auto tree_handle = tx.wo(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, txid.seqno); sig_handle->put(sigv); tree_handle->put({}); @@ -5131,8 +5905,8 @@ TEST_CASE("Ledger entry chunk request") REQUIRE(store.should_create_ledger_chunk(txid.seqno)); // Add the signature - auto sig_handle = tx.rw(signatures); - auto tree_handle = tx.rw(serialised_tree); + auto sig_handle = tx.wo(signatures); + auto tree_handle = tx.wo(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, txid.seqno); sig_handle->put(sigv); tree_handle->put({}); diff --git a/src/kv/test/null_tx_history.h b/src/kv/test/null_tx_history.h index 83b49a456cc1..9d7866a2acce 100644 --- a/src/kv/test/null_tx_history.h +++ b/src/kv/test/null_tx_history.h @@ -19,8 +19,8 @@ namespace ccf { // Test-only TxHistory which does not build a Merkle tree or sign anything, // but still writes placeholder entries to the signature tables when a - // signature is emitted, so that transactions depending on those tables can - // be exercised without a real history. + // signature is emitted, so that materialised signature reads can be + // exercised without a real history. class NullTxHistoryPendingTx : public ccf::kv::PendingTx { ccf::TxID txid; diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index 4dfe0aa9e0dd..5db4fe8da0ee 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -4,7 +4,9 @@ #include "ccf/tx.h" #include "ds/ccf_assert.h" +#include "ds/internal_logger.h" #include "kv/compacted_version_conflict.h" +#include "kv/internal_table_names.h" #include "kv/kv_types.h" #include "kv/tx_pimpl.h" #include "kv/untyped_map.h" @@ -22,6 +24,56 @@ namespace ccf::kv // not incomplete MapChanges::~MapChanges() = default; + void BaseTx::check_map_access(const std::string& map_name, AccessMode access) + { + const char* reason = nullptr; + switch (pimpl->role) + { + case PrivateImpl::Role::Ordinary: + { + if (is_signature_table(map_name)) + { + reason = "Live transactions cannot access signature tables"; + } + break; + } + case PrivateImpl::Role::Reserved: + { + if (!is_signature_table(map_name) || access != AccessMode::WriteOnly) + { + reason = + "Reserved transactions may only acquire write-only handles " + "to signature tables"; + } + break; + } + case PrivateImpl::Role::MaterialisedReadOnly: + { + if (!pimpl->store->check_rollback_count(pimpl->read_rollback_count)) + { + throw CompactedVersionConflict(fmt::format( + "Materialised state for map '{}' was invalidated by rollback", + map_name)); + } + if (access != AccessMode::ReadOnly && access != AccessMode::Diff) + { + reason = + "Materialised read transactions may only acquire read-only " + "or diff handles"; + } + break; + } + } + + if (reason != nullptr) + { + const auto message = + fmt::format("Access to map '{}' denied: {}", map_name, reason); + LOG_FAIL_FMT("{}", message); + throw MapAccessDenied(message); + } + } + void BaseTx::retain_change_set( const std::string& map_name, std::unique_ptr&& change_set, @@ -47,8 +99,12 @@ namespace ccf::kv } MapChanges BaseTx::get_map_and_change_set_by_name( - const std::string& map_name, bool track_deletes_on_missing_keys) + const std::string& map_name, + bool track_deletes_on_missing_keys, + AccessMode access) { + check_map_access(map_name, access); + auto& read_txid = pimpl->read_txid; if (!read_txid.has_value()) @@ -92,10 +148,14 @@ namespace ccf::kv fmt::format("Map {} has unexpected type", map_name)); } - return { - abstract_map, - untyped_map->create_change_set( - read_txid->seqno, track_deletes_on_missing_keys)}; + auto change_set = untyped_map->create_change_set( + read_txid->seqno, track_deletes_on_missing_keys); + // Rollback can replace a map between the access check and snapshot capture. + if (pimpl->role == PrivateImpl::Role::MaterialisedReadOnly) + { + check_map_access(map_name, access); + } + return {abstract_map, std::move(change_set)}; } std::list BaseTx::get_possible_handles( @@ -133,6 +193,28 @@ namespace ccf::kv pimpl->store = store_; } + ReadOnlyTx::ReadOnlyTx( + AbstractStore* store_, + ccf::SeqNo read_version, + Version read_rollback_count) : + BaseTx(store_) + { + pimpl->role = PrivateImpl::Role::MaterialisedReadOnly; + pimpl->read_txid = TxID(ccf::VIEW_UNKNOWN, read_version); + pimpl->read_rollback_count = read_rollback_count; + } + + TxDiff::TxDiff( + AbstractStore* store_, + ccf::SeqNo read_version, + Version read_rollback_count) : + BaseTx(store_) + { + pimpl->role = PrivateImpl::Role::MaterialisedReadOnly; + pimpl->read_txid = TxID(ccf::VIEW_UNKNOWN, read_version); + pimpl->read_rollback_count = read_rollback_count; + } + // Use default destructor, but instantiate here where PrivateImpl is not // incomplete BaseTx::~BaseTx() = default; diff --git a/src/kv/tx_pimpl.h b/src/kv/tx_pimpl.h index 1f14e91297e4..48bb2b9cc133 100644 --- a/src/kv/tx_pimpl.h +++ b/src/kv/tx_pimpl.h @@ -8,7 +8,15 @@ namespace ccf::kv { struct BaseTx::PrivateImpl { + enum class Role + { + Ordinary, + Reserved, + MaterialisedReadOnly + }; + AbstractStore* store = nullptr; + Role role = Role::Ordinary; // NB: This exists only to maintain the old API, where this Tx stores // MapHandles and returns raw pointers to them. It could be removed entirely @@ -21,6 +29,7 @@ namespace ccf::kv // Note: read_txid version is set to NoVersion for the first transaction in // the service, before anything has been applied to the KV. std::optional read_txid = std::nullopt; + Version read_rollback_count = 0; ccf::View commit_view = ccf::VIEW_UNKNOWN; std::map> created_maps; diff --git a/src/node/gov/handlers/acks.h b/src/node/gov/handlers/acks.h index b5df903116f9..e49d9b810118 100644 --- a/src/node/gov/handlers/acks.h +++ b/src/node/gov/handlers/acks.h @@ -27,7 +27,7 @@ namespace ccf::gov::endpoints // NOLINTNEXTLINE(readability-function-cognitive-complexity) inline void init_ack_handlers( ccf::BaseEndpointRegistry& registry, - NetworkState& /*network*/, + NetworkState& network, ShareManager& share_manager) { auto get_state_digest = [&](auto& ctx, ApiVersion api_version) { @@ -138,9 +138,13 @@ namespace ccf::gov::endpoints ack = ack_opt.value(); } - // Get merkle root state digest from serialised merkle tree - auto tree_handle = ctx.tx.template ro( - Tables::SERIALISED_MERKLE_TREE); + // The acknowledged signed prefix is metadata, not this write's + // transactional snapshot. + auto signed_state = + network.tables->create_read_only_tx_at_replicated_state(); + auto tree_handle = + signed_state.template ro( + Tables::SERIALISED_MERKLE_TREE); auto tree = tree_handle->get(); if (!tree.has_value()) { diff --git a/src/node/history.h b/src/node/history.h index 644858634bc1..6ab9ef734f1f 100644 --- a/src/node/history.h +++ b/src/node/history.h @@ -537,7 +537,7 @@ namespace ccf // The history can be initialised after a snapshot has been applied by // deserialising the tree in the signatures table and then applying the // hash of the transaction at which the snapshot was taken - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); auto* tree_h = tx.template ro( ccf::Tables::SERIALISED_MERKLE_TREE); auto tree = tree_h->get(); @@ -585,7 +585,7 @@ namespace ccf bool verify_root_signatures(ccf::kv::Version version) override { - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); auto root = get_replicated_state_root(); log_hash(root, VERIFY); diff --git a/src/node/internal_tables_access.h b/src/node/internal_tables_access.h index fc8d24bdaff3..0447920e1ea8 100644 --- a/src/node/internal_tables_access.h +++ b/src/node/internal_tables_access.h @@ -356,7 +356,9 @@ namespace ccf const ccf::crypto::Pem& service_cert, ccf::TxID create_txid, nlohmann::json service_data = nullptr, - bool recovering = false) + bool recovering = false, + std::optional previous_signed_root = + std::nullopt) { auto* service = tx.rw(Tables::SERVICE); @@ -380,27 +382,19 @@ namespace ccf prev_service_created_at = prev_service_info->current_service_create_txid.value().seqno; + if (!previous_signed_root.has_value()) + { + throw std::logic_error( + "Previous service has no materialised signed root"); + } + auto* previous_service_identity = tx.wo( ccf::Tables::PREVIOUS_SERVICE_IDENTITY); previous_service_identity->put(prev_service_info->cert); auto* last_signed_root = tx.wo( ccf::Tables::PREVIOUS_SERVICE_LAST_SIGNED_ROOT); - auto* tree_handle = - tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE); - if (!tree_handle->has()) - { - throw std::logic_error( - "Previous service doesn't have a serialised merkle tree"); - } - auto tree_opt = tree_handle->get(); - if (!tree_opt.has_value()) - { - throw std::logic_error( - "Previous service doesn't have serialised merkle tree value"); - } - ccf::MerkleTreeHistory tree(tree_opt.value()); - last_signed_root->put(tree.get_root()); + last_signed_root->put(previous_signed_root.value()); // Record number of recoveries for service. If the value does // not exist in the table (i.e. pre 2.x ledger), assume it is the diff --git a/src/node/node_state.h b/src/node/node_state.h index c8f388c6bbbf..89aba600dbb5 100644 --- a/src/node/node_state.h +++ b/src/node/node_state.h @@ -1806,7 +1806,8 @@ namespace ccf hook->call(consensus.get()); } - auto tx = network.tables->create_read_only_tx(); + auto tx = + network.tables->create_read_only_tx_at_replicated_state(); view = resolve_latest_sig_view(tx); if (!resp.network_info->public_only) @@ -2071,7 +2072,7 @@ namespace ccf { // If the ledger entry is a signature, it is safe to compact the store network.tables->compact(last_recovered_idx); - auto tx = network.tables->create_read_only_tx(); + auto tx = network.tables->create_read_only_tx_at_replicated_state(); ccf::kv::Term sig_view = resolve_latest_sig_view(tx); @@ -2141,7 +2142,7 @@ namespace ccf last_recovered_term, last_recovered_signed_idx); - auto tx = network.tables->create_read_only_tx(); + auto tx = network.tables->create_read_only_tx_at_replicated_state(); network.ledger_secrets->init(last_recovered_signed_idx + 1); // Initialise snapshotter after public recovery diff --git a/src/node/rpc/node_frontend.h b/src/node/rpc/node_frontend.h index 882b39eb438d..99d2147255ff 100644 --- a/src/node/rpc/node_frontend.h +++ b/src/node/rpc/node_frontend.h @@ -819,7 +819,7 @@ namespace ccf .set_openapi_hidden(true) .install(); - auto get_state = [this](auto& args, nlohmann::json&&) { + auto get_state = [this](auto&, nlohmann::json&&) { GetState::Out result; auto [s, rts, lrs] = this->node_operation.state(); result.node_id = this->context.get_node_id(); @@ -829,34 +829,46 @@ namespace ccf result.startup_seqno = this->node_operation.get_startup_snapshot_seqno(); - // Read last signed seqno from both raw and COSE signature tables - auto signatures = args.tx.template ro(Tables::SIGNATURES); - auto sig = signatures->get(); - - ccf::kv::Version raw_seqno = 0; - if (sig.has_value()) + if (network.tables->is_ready()) { - raw_seqno = sig.value().seqno; - } + auto signed_state = + network.tables->create_read_only_tx_at_replicated_state(); + auto signatures = + signed_state.template ro(Tables::SIGNATURES); + auto sig = signatures->get(); + + ccf::kv::Version raw_seqno = 0; + if (sig.has_value()) + { + raw_seqno = sig.value().seqno; + } - ccf::kv::Version cose_seqno = 0; - auto cose_signatures = - args.tx.template ro(Tables::COSE_SIGNATURES); - auto cose_sig = cose_signatures->get(ccf::IdentityType::CLASSICAL); - if (cose_sig.has_value() && !cose_sig->empty()) - { - auto receipt = ccf::cose::decode_ccf_receipt(cose_sig.value(), false); - auto txid = ccf::TxID::from_str(receipt.phdr.ccf.txid); - if (!txid.has_value()) + ccf::kv::Version cose_seqno = 0; + auto cose_signatures = + signed_state.template ro(Tables::COSE_SIGNATURES); + auto cose_sig = cose_signatures->get(ccf::IdentityType::CLASSICAL); + if (cose_sig.has_value() && !cose_sig->empty()) { - throw std::logic_error(fmt::format( - "Failed to parse txid from COSE signature: {}", - receipt.phdr.ccf.txid)); + auto receipt = + ccf::cose::decode_ccf_receipt(cose_sig.value(), false); + auto txid = ccf::TxID::from_str(receipt.phdr.ccf.txid); + if (!txid.has_value()) + { + throw std::logic_error(fmt::format( + "Failed to parse txid from COSE signature: {}", + receipt.phdr.ccf.txid)); + } + cose_seqno = txid->seqno; } - cose_seqno = txid->seqno; - } - result.last_signed_seqno = std::max(raw_seqno, cose_seqno); + result.last_signed_seqno = std::max(raw_seqno, cose_seqno); + } + else + { + result.last_signed_seqno = std::max( + this->node_operation.get_last_recovered_signed_idx(), + result.startup_seqno); + } auto node_configuration_subsystem = this->context.get_subsystem(); @@ -872,8 +884,8 @@ namespace ccf return make_success(result); }; - make_read_only_endpoint( - "/state", HTTP_GET, json_read_only_adapter(get_state), no_auth_required) + make_command_endpoint( + "/state", HTTP_GET, json_command_adapter(get_state), no_auth_required) .set_auto_schema() .set_forwarding_required(endpoints::ForwardingRequired::Never) .install(); @@ -1666,8 +1678,33 @@ namespace ccf "Service is already created."); } + std::optional previous_signed_root; + if (ctx.tx.ro(network.service)->has()) + { + auto signed_state = + network.tables->create_read_only_tx_at_replicated_state(); + const auto tree = + signed_state + .ro(Tables::SERIALISED_MERKLE_TREE) + ->get(); + if (!tree.has_value()) + { + return make_error( + HTTP_STATUS_INTERNAL_SERVER_ERROR, + ccf::errors::InternalError, + "Previous service has no materialised signed root"); + } + previous_signed_root = + ccf::MerkleTreeHistory(tree.value()).get_root(); + } + InternalTablesAccess::create_service( - ctx.tx, in.service_cert, in.create_txid, in.service_data, recovering); + ctx.tx, + in.service_cert, + in.create_txid, + in.service_data, + recovering, + previous_signed_root); if (recovering) { diff --git a/src/node/rpc/test/internal_tables_access_test.cpp b/src/node/rpc/test/internal_tables_access_test.cpp index f7f730ee44c2..743fe9f3ef48 100644 --- a/src/node/rpc/test/internal_tables_access_test.cpp +++ b/src/node/rpc/test/internal_tables_access_test.cpp @@ -679,10 +679,26 @@ TEST_CASE("create_service publishes the classical signing identity") INFO("Recovery publishes the new key and preserves legacy recovery state"); { auto tx = kv_store.create_tx(); - tx.wo(Tables::SERIALISED_MERKLE_TREE) - ->put(tree.serialise()); + REQUIRE_THROWS_WITH_AS( + InternalTablesAccess::create_service( + tx, recovered_cert, {2, 10}, nullptr, true), + "Previous service has no materialised signed root", + std::logic_error); + REQUIRE( + !tx.ro(Tables::PREVIOUS_SERVICE_IDENTITY) + ->has()); + REQUIRE(tx.ro(Tables::SERVICE)->get()->cert == service_cert); + } + + { + auto tx = kv_store.create_tx(); InternalTablesAccess::create_service( - tx, recovered_cert, {2, 10}, nullptr, true /* recovering */); + tx, + recovered_cert, + {2, 10}, + nullptr, + true /* recovering */, + tree.get_root()); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } diff --git a/src/node/rpc/test/node_frontend_test.cpp b/src/node/rpc/test/node_frontend_test.cpp index b08da3b78ec6..e58d6b45170d 100644 --- a/src/node/rpc/test/node_frontend_test.cpp +++ b/src/node/rpc/test/node_frontend_test.cpp @@ -520,6 +520,28 @@ TEST_CASE("Self certificate authentication") CHECK(error_reason.contains("before certificate's Not Before")); } +TEST_CASE("Node state is explicitly nontransactional metadata") +{ + NetworkState network; + StubNodeContext context; + TestNodeRpcFrontend frontend(network, context); + frontend.open(); + + ::http::Request request("state", HTTP_GET); + auto session = std::make_shared( + ccf::InvalidSessionId, std::vector{}); + auto rpc_ctx = ccf::make_rpc_context(session, request.build_request()); + const auto endpoint = + frontend.get_node_endpoints().find_endpoint_without_kv(*rpc_ctx); + REQUIRE(endpoint != nullptr); + CHECK( + endpoint->execution_mode == ccf::endpoints::EndpointExecutionMode::Command); + CHECK( + endpoint->properties.forwarding_required == + ccf::endpoints::ForwardingRequired::Never); + CHECK(endpoint->authn_policies.empty()); +} + TEST_CASE("Pending-node cleanup uses renewed client certificates") { NetworkState network; diff --git a/src/node/test/historical_queries.cpp b/src/node/test/historical_queries.cpp index dbfe03c2eb98..7aaf042f6bf7 100644 --- a/src/node/test/historical_queries.cpp +++ b/src/node/test/historical_queries.cpp @@ -2214,7 +2214,8 @@ TEST_CASE( for (const auto& written_signatures : signature_transactions) { - auto tx = store.create_tx(); + const auto txid = store.next_txid(); + auto tx = store.create_reserved_tx(txid); auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); for (const auto& [identity_type, signature] : written_signatures) { @@ -2222,12 +2223,22 @@ TEST_CASE( } tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({}); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - - const auto txid = store.current_txid(); + auto info = tx.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + store.commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true) == ccf::kv::CommitResult::SUCCESS); + + REQUIRE(store.current_txid() == txid); INFO("Signature transaction: ", txid.to_str()); { - auto read_tx = store.create_read_only_tx(); + auto read_tx = store.create_read_only_tx_at_replicated_state(); REQUIRE( read_tx.ro(ccf::Tables::COSE_SIGNATURES)->size() == 2); diff --git a/src/node/test/history.cpp b/src/node/test/history.cpp index dedfe6cd5ed7..f2c9e1e7876b 100644 --- a/src/node/test/history.cpp +++ b/src/node/test/history.cpp @@ -157,12 +157,27 @@ TEST_CASE("Check signature verification") INFO("Issue a bogus signature, rejected by verification on the backup"); { - auto txs = primary_store.create_tx(); - auto sigs = txs.rw(signatures); - ccf::PrimarySignature bogus(ccf::kv::test::PrimaryNodeId, 0); + const auto txid = primary_store.next_txid(); + auto txs = primary_store.create_reserved_tx(txid); + auto sigs = txs.wo(signatures); + ccf::PrimarySignature bogus(ccf::kv::test::PrimaryNodeId, txid.seqno); + bogus.view = txid.view; + bogus.root = primary_history->get_replicated_state_root(); bogus.sig = std::vector(256, 1); sigs->put(bogus); - REQUIRE(txs.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + txs.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put(primary_history->serialise_tree(txid.seqno - 1)); + auto info = txs.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + primary_store.commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true) == ccf::kv::CommitResult::FAIL_NO_REPLICATE); } } @@ -411,20 +426,18 @@ class TestPendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; - MapT& other_table; public: - TestPendingTx(ccf::TxID txid_, ccf::kv::Store& store_, MapT& other_table_) : + TestPendingTx(ccf::TxID txid_, ccf::kv::Store& store_) : txid(txid_), - store(store_), - other_table(other_table_) + store(store_) {} ccf::kv::PendingTxInfo call() override { auto txr = store.create_reserved_tx(txid); - auto txrv = txr.rw(other_table); - txrv->put(0, 1); + txr.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({}); return txr.commit_reserved(); } }; @@ -456,7 +469,6 @@ TEST_CASE("Pending signatures retain their endorsed certificate") constexpr auto store_term = 2; store.initialise_term(store_term); - MapT table("public:table"); const auto gap_txid = store.next_txid(); history->emit_signature(); @@ -465,11 +477,10 @@ TEST_CASE("Pending signatures retain their endorsed certificate") history->set_endorsed_certificate(second_cert); REQUIRE( store.commit( - gap_txid, - std::make_unique(gap_txid, store, table), - false) == ccf::kv::CommitResult::SUCCESS); + gap_txid, std::make_unique(gap_txid, store), false) == + ccf::kv::CommitResult::SUCCESS); - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); auto signatures = tx.ro(ccf::Tables::SIGNATURES); const auto signature = signatures->get(); REQUIRE(signature.has_value()); @@ -530,8 +541,8 @@ class PausedReservedSignatureTx : public ccf::kv::PendingTx ccf::kv::PendingTxInfo call() override { auto tx = store.create_reserved_tx(txid); - auto sig = tx.rw(signatures); - auto tree = tx.rw(serialised_tree); + auto sig = tx.wo(signatures); + auto tree = tx.wo(serialised_tree); sig->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); tree->put({}); @@ -562,7 +573,6 @@ TEST_CASE( store.set_consensus(consensus); MapT table("public:table"); - MapT other_table("public:other_table"); INFO("Write first tx"); { @@ -583,8 +593,7 @@ TEST_CASE( REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); REQUIRE(consensus->count == 1); - store.commit( - rv, std::make_unique(rv, store, other_table), true); + store.commit(rv, std::make_unique(rv, store), true); REQUIRE(consensus->count == 3); } @@ -841,15 +850,18 @@ TEST_CASE("COSE signature table holds one entry per identity") INFO("A table carrying two identities round-trips both"); { - auto tx = store.create_tx(); + auto tx = store.create_reserved_tx(store.next_txid()); auto* handle = tx.wo(ccf::Tables::COSE_SIGNATURES); handle->put(ccf::IdentityType::CLASSICAL, ec384_sig); handle->put(ccf::IdentityType::PQ, mldsa65_sig); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({}); + REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); + store.compact(store.current_version()); } { - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); auto* handle = tx.ro(ccf::Tables::COSE_SIGNATURES); // A reader which only understands ECDSA still finds it, unaffected by @@ -875,22 +887,33 @@ TEST_CASE("CLASSICAL COSE signatures interoperate with the legacy singleton") const ccf::CoseSignature keyed_signature{4, 5, 6}; { - auto tx = store.create_tx(); + auto tx = store.create_reserved_tx(store.next_txid()); tx.wo(ccf::Tables::COSE_SIGNATURES) ->put(legacy_signature); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({}); + REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); + store.compact(store.current_version()); } { - auto tx = store.create_tx(); - auto* signatures = tx.rw(ccf::Tables::COSE_SIGNATURES); + auto tx = store.create_read_only_tx_at_replicated_state(); + auto* signatures = tx.ro(ccf::Tables::COSE_SIGNATURES); REQUIRE(signatures->get(ccf::IdentityType::CLASSICAL) == legacy_signature); + } + + { + auto tx = store.create_reserved_tx(store.next_txid()); + auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); signatures->put(ccf::IdentityType::CLASSICAL, keyed_signature); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({}); + REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); + store.compact(store.current_version()); } { - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); REQUIRE( tx.ro(ccf::Tables::COSE_SIGNATURES)->get() == keyed_signature); diff --git a/src/node/test/snapshot.cpp b/src/node/test/snapshot.cpp index bc51829d1b11..3de022a6571c 100644 --- a/src/node/test/snapshot.cpp +++ b/src/node/test/snapshot.cpp @@ -67,7 +67,7 @@ TEST_CASE("Snapshot with merkle tree" * doctest::test_suite("snapshot")) { // No snapshot here, only verify that a fresh tree can be started from the // mini-tree in a signature and the hash of the signature - auto tx = source_store.create_read_only_tx(); + auto tx = source_store.create_read_only_tx_at_replicated_state(); auto signatures = tx.ro(ccf::Tables::SIGNATURES); REQUIRE(signatures->has()); auto sig = signatures->get().value(); diff --git a/src/node/test/snapshotter.cpp b/src/node/test/snapshotter.cpp index f4761a4483b8..ab1a3530c741 100644 --- a/src/node/test/snapshotter.cpp +++ b/src/node/test/snapshotter.cpp @@ -758,14 +758,25 @@ TEST_CASE("Rekey ledger while snapshot is in progress") { // It is necessary to record a signature for the snapshot to be // deserialisable by the backup store - auto tx = network.tables->create_tx(); - auto sigs = tx.rw(ccf::Tables::SIGNATURES); + const auto txid = network.tables->next_txid(); + auto tx = network.tables->create_reserved_tx(txid); + auto sigs = tx.wo(ccf::Tables::SIGNATURES); auto trees = - tx.rw(ccf::Tables::SERIALISED_MERKLE_TREE); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE); sigs->put({ccf::kv::test::PrimaryNodeId, 0, 0, {}, {}, {}, {}}); auto tree = history->serialise_tree(snapshot_idx - 1); trees->put(tree); - tx.commit(); + auto info = tx.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + network.tables->commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + false) == ccf::kv::CommitResult::SUCCESS); REQUIRE(record_signature(history, snapshotter, snapshot_idx)); snapshotter->commit(snapshot_idx, true); diff --git a/src/rust/app_bridge.cpp b/src/rust/app_bridge.cpp index da9e023841a7..f10d3540a905 100644 --- a/src/rust/app_bridge.cpp +++ b/src/rust/app_bridge.cpp @@ -5,6 +5,7 @@ #include "ccf/common_auth_policies.h" #include "ccf/http_status.h" #include "ccf/kv/map.h" +#include "ccf/kv/map_access.h" #include "ccf/odata_error.h" #include "ccf/rust_ffi.h" #include "kv/compacted_version_conflict.h" @@ -303,6 +304,10 @@ namespace ctx->compacted_version_conflict = e; return CCF_RUST_INTERNAL_ERROR; } + catch (const ccf::kv::MapAccessDenied&) + { + return CCF_RUST_ACCESS_DENIED; + } }); } diff --git a/src/rust/ccf-app/src/lib.rs b/src/rust/ccf-app/src/lib.rs index 375b88444066..10cd4cb6058b 100644 --- a/src/rust/ccf-app/src/lib.rs +++ b/src/rust/ccf-app/src/lib.rs @@ -14,6 +14,7 @@ //! response status is 2xx. A handler returns an [`EndpointError`] to send an //! error response, and `?` on a [`BridgeResult`] sends HTTP 500. Panics are //! caught and also sent as HTTP 500, which requires `panic = "unwind"`. +//! Current KV operations on signature tables return [`BridgeError::AccessDenied`]. #![deny(missing_docs, rustdoc::broken_intra_doc_links)] @@ -60,6 +61,7 @@ enum RawResult { InvalidArgument = 2, ReadOnly = 3, InternalError = 4, + AccessDenied = 5, } #[repr(i32)] @@ -200,6 +202,7 @@ fn decode_result(result: i32) -> Result<(), BridgeError> { value if value == RawResult::NotFound as i32 => Err(BridgeError::NotFound), value if value == RawResult::InvalidArgument as i32 => Err(BridgeError::InvalidArgument), value if value == RawResult::ReadOnly as i32 => Err(BridgeError::ReadOnly), + value if value == RawResult::AccessDenied as i32 => Err(BridgeError::AccessDenied), _ => Err(BridgeError::Internal), } } @@ -232,6 +235,10 @@ pub enum BridgeError { Internal, /// The SDK and CCF were built with different ABI versions. AbiMismatch, + /// Current transactions cannot access `public:ccf.internal.signatures`, + /// `public:ccf.internal.cose_signatures` or `public:ccf.internal.tree`. + /// This applies even if the map or key does not exist. + AccessDenied, } /// Result of an SDK call into CCF. @@ -640,6 +647,8 @@ impl<'ctx> WriteContext<'ctx> { } /// Read-only access to a raw-byte KV map, from [`ReadOnlyContext::map`]. +/// +/// Operations on restricted maps return [`BridgeError::AccessDenied`]. pub struct ReadOnlyMap<'a, 'ctx> { context: &'a mut Context<'ctx>, name: &'a str, @@ -661,6 +670,7 @@ impl ReadOnlyMap<'_, '_> { /// /// Writes are visible to later reads in the same transaction, and are applied /// only if the response status is 2xx. +/// Operations on restricted maps return [`BridgeError::AccessDenied`]. pub struct Map<'a, 'ctx> { context: &'a mut Context<'ctx>, name: &'a str, @@ -964,9 +974,20 @@ mod tests { assert_eq!(decode_result(1), Err(BridgeError::NotFound)); assert_eq!(decode_result(2), Err(BridgeError::InvalidArgument)); assert_eq!(decode_result(3), Err(BridgeError::ReadOnly)); + assert_eq!(decode_result(4), Err(BridgeError::Internal)); + assert_eq!(decode_result(5), Err(BridgeError::AccessDenied)); + assert_eq!(decode_result(-1), Err(BridgeError::Internal)); assert_eq!(decode_result(99), Err(BridgeError::Internal)); } + #[test] + fn access_denied_remains_an_http_500_bridge_error() { + let error = EndpointError::from(BridgeError::AccessDenied); + assert_eq!(error.status, 500); + assert_eq!(error.code, "InternalError"); + assert_eq!(error.message, "CCF bridge error: AccessDenied"); + } + #[test] fn rejects_null_registry() { // SAFETY: This intentionally exercises null validation. diff --git a/tests/basic_rust.py b/tests/basic_rust.py index 82d106ea0c45..5f2d2376d794 100644 --- a/tests/basic_rust.py +++ b/tests/basic_rust.py @@ -79,6 +79,39 @@ def test_basic_rust(network, args): return network +@reqs.description("Rust KV calls report explicit denial of current signature tables") +@reqs.supports_methods("/app/signature-table-access/{table}/{operation}") +def test_signature_table_access_denied(network, args): + primary, _ = network.find_primary() + + with primary.client() as anonymous: + for table in ("signatures", "cose_signatures", "tree"): + for method, operations in ( + (anonymous.get, ("get", "has")), + (anonymous.post, ("get", "has", "put", "remove")), + ): + for operation in operations: + path = f"/app/signature-table-access/{table}/{operation}" + response = method(path) + assert ( + response.status_code == http.HTTPStatus.INTERNAL_SERVER_ERROR + ), ( + path, + response, + ) + error = response.body.json()["error"] + assert error["code"] == "InternalError", (path, error) + assert error["message"] == "CCF bridge error: AccessDenied", ( + path, + error, + ) + + response = anonymous.get("/app/health") + assert response.status_code == http.HTTPStatus.OK, response + + return network + + def test_compaction_conflict_is_retried(network, args): primary, _ = network.find_primary() @@ -135,6 +168,7 @@ def run(args): ) as network: network.start_and_open(args) test_basic_rust(network, args) + test_signature_table_access_denied(network, args) test_compaction_conflict_is_retried(network, args) diff --git a/tests/e2e_operations.py b/tests/e2e_operations.py index 6a5a39dbdbe8..02251e6c081a 100644 --- a/tests/e2e_operations.py +++ b/tests/e2e_operations.py @@ -1558,6 +1558,8 @@ def test_ledger_chunk_redirect_gap(network, args): with new_node.client(interface_name=infra.interfaces.PRIMARY_RPC_INTERFACE) as c: r = c.get("/node/state") + assert r.status_code == http.HTTPStatus.OK, r + assert infra.clients.CCF_TX_ID_HEADER not in r.headers, r.headers startup_seqno = r.body.json()["startup_seqno"] # The new node should have started from a snapshot taken after the commit at the start of the test assert ( diff --git a/tests/governance.py b/tests/governance.py index c92dd84f7a53..c455ff2a9b1d 100644 --- a/tests/governance.py +++ b/tests/governance.py @@ -12,6 +12,7 @@ import governance_api import governance_history import governance_js +import infra.clients import infra.crypto import infra.e2e_args import infra.interfaces @@ -338,6 +339,12 @@ def run_test_all_members(network): @reqs.description("Test ack state digest updates") def test_ack_state_digest_update(network, args): for node in network.get_joined_nodes(): + with node.client() as c: + state = c.get("/node/state") + assert state.status_code == http.HTTPStatus.OK, state + assert infra.clients.CCF_TX_ID_HEADER not in state.headers, state.headers + assert state.body.json()["last_signed_seqno"] > 0, state.body.json() + member = network.consortium.get_any_active_member() updated = member.update_ack_state_digest(node) updated_digest = updated.body.json() diff --git a/tests/infra/network.py b/tests/infra/network.py index 247527646e80..8ddabf1bdad7 100644 --- a/tests/infra/network.py +++ b/tests/infra/network.py @@ -1923,7 +1923,7 @@ def wait_for_all_nodes_to_commit(self, primary=None, tx_id=None, timeout=10): if tx_id is None: while time.time() < end_time: with primary.client() as c: - resp = c.get("/node/state") # Well-known read-only endpoint + resp = c.get("/node/network") tx_id = TxID(resp.view, resp.seqno) if tx_id.valid(): break diff --git a/tests/programmability.py b/tests/programmability.py index e4b1f92ca9f8..b91747d2d071 100644 --- a/tests/programmability.py +++ b/tests/programmability.py @@ -261,6 +261,13 @@ def test_custom_endpoints_kv_restrictions(network, args): user = network.users[0] module_name = "restrictions.js" + signature_tables = ( + "public:ccf.internal.signatures", + "public:ccf.internal.cose_signatures", + "public:ccf.internal.tree", + ) + read_operations = ("get", "has", "getVersionOfPreviousWrite", "forEach", "size") + write_operations = ("set", "delete", "clear") endpoints = { "/try_read": { @@ -276,6 +283,19 @@ def test_custom_endpoints_kv_restrictions(network, args): mode="readwrite", ) }, + "/try_operation_ro": { + "post": endpoint_properties( + js_module=module_name, + js_function="try_operation", + ) + }, + "/try_operation_rw": { + "post": endpoint_properties( + js_module=module_name, + js_function="try_operation", + mode="readwrite", + ) + }, "/try_read_retargeted": { "post": endpoint_properties( js_module=module_name, @@ -294,6 +314,18 @@ def test_custom_endpoints_kv_restrictions(network, args): js_function="try_read_current_via_historical_handle", ) }, + "/try_read_historical_via_current_handle": { + "post": endpoint_properties( + js_module=module_name, + js_function="try_read_historical_via_current_handle", + ) + }, + "/read_historical_signature_tables": { + "post": endpoint_properties( + js_module=module_name, + js_function="read_historical_signature_tables", + ) + }, } with open( @@ -398,6 +430,59 @@ def test_custom_endpoints_kv_restrictions(network, args): r = c.post("/app/try_write", {"table": "public:ccf.internal.foo"}) assert r.status_code == http.HTTPStatus.BAD_REQUEST.value, r.status_code + LOG.info("Current signature tables are inaccessible, not merely read-only") + for path in ("/app/try_operation_ro", "/app/try_operation_rw"): + for table in signature_tables: + for operation in read_operations + write_operations: + for receiver in ( + {}, + {"via": "my_js_table"}, + {"via": "my_js_table", "forged": True}, + ): + body = {"table": table, "operation": operation, **receiver} + r = c.post(path, body) + assert r.status_code == http.HTTPStatus.BAD_REQUEST, ( + path, + body, + r.status_code, + r.body.text(), + ) + expected = ( + "KV Map Handle object expected" + if receiver.get("forged") + else "inaccessible" + ) + assert expected in r.body.text(), (body, r.body.text()) + + LOG.info( + "Other public internal tables, including neighboring names, remain read-only" + ) + for table in ( + "public:ccf.internal.foo", + "public:ccf.internal.signatures_other", + "public:ccf.internal.cose_signatures_other", + "public:ccf.internal.tree.nested", + ): + for operation in read_operations: + r = c.post( + "/app/try_operation_ro", {"table": table, "operation": operation} + ) + assert r.status_code == http.HTTPStatus.OK, ( + table, + operation, + r.body.text(), + ) + for operation in write_operations: + r = c.post( + "/app/try_operation_rw", {"table": table, "operation": operation} + ) + assert r.status_code == http.HTTPStatus.BAD_REQUEST, ( + table, + operation, + r.body.text(), + ) + assert "read-only" in r.body.text(), r.body.text() + LOG.info("Cannot grant access to (hypothetical) private gov/internal tables") r = c.post("/app/try_read", {"table": "ccf.gov.foo"}) assert r.status_code == http.HTTPStatus.BAD_REQUEST.value, r.status_code @@ -458,6 +543,13 @@ def post_until_available(client, path, body): ) assert r.status_code == http.HTTPStatus.BAD_REQUEST.value, r.status_code + r = post_until_available( + c, + "/app/try_read_historical", + {"table": "public:ccf.internal.foo", "seqno": seqno}, + ) + assert r.status_code == http.HTTPStatus.OK, (r.status_code, r.body.text()) + LOG.info("A historical handle cannot be used against the current KV") r = post_until_available( c, @@ -466,6 +558,68 @@ def post_until_available(client, path, body): ) assert r.status_code == http.HTTPStatus.BAD_REQUEST.value, r.status_code + LOG.info("Historical signature tables expose actual entries at a signed seqno") + deadline = time.time() + 10 + while True: + r = c.get("/node/state") + assert r.status_code == http.HTTPStatus.OK, r.status_code + signed_seqno = r.body.json()["last_signed_seqno"] + if signed_seqno >= int(seqno): + break + assert time.time() < deadline, "No signature covering the test write" + time.sleep(0.1) + network.wait_for_all_nodes_to_commit(primary=primary) + + r = post_until_available( + c, "/app/read_historical_signature_tables", {"seqno": signed_seqno} + ) + assert r.status_code == http.HTTPStatus.OK, (r.status_code, r.body.text()) + result = r.body.json() + assert int(result["transactionId"].split(".")[1]) == signed_seqno, result + assert result["isSignatureTransaction"], result + assert set(result["tables"]) == set(signature_tables), result + required_tables = set(signature_tables[1:]) + if result["rawSignatureExpected"]: + required_tables.add(signature_tables[0]) + for table, contents in result["tables"].items(): + assert contents["writeDenied"] == dict.fromkeys(write_operations, True), ( + table, + contents, + ) + assert contents["size"] == len(contents["entries"]), (table, contents) + if table not in required_tables: + assert contents["size"] == 0, (table, contents) + continue + assert contents["size"] > 0, (table, contents) + assert [0] * 8 in [entry["key"] for entry in contents["entries"]], ( + table, + contents, + ) + if table != signature_tables[1]: + assert contents["size"] == 1, (table, contents) + for entry in contents["entries"]: + assert entry["valueSize"] > 0, (table, entry) + assert entry["has"], (table, entry) + assert entry["getMatches"], (table, entry) + assert entry["version"] == signed_seqno, (table, entry) + + LOG.info("Current and historical signature handles cannot exchange methods") + for table in signature_tables: + r = post_until_available( + c, + "/app/try_read_current_via_historical_handle", + {"table": table, "via": "my_js_table", "seqno": signed_seqno}, + ) + assert r.status_code == http.HTTPStatus.BAD_REQUEST, r.body.text() + assert "different key-value store" in r.body.text(), r.body.text() + r = post_until_available( + c, + "/app/try_read_historical_via_current_handle", + {"table": table, "seqno": signed_seqno}, + ) + assert r.status_code == http.HTTPStatus.BAD_REQUEST, r.body.text() + assert "different key-value store" in r.body.text(), r.body.text() + return network diff --git a/tests/programmability/restrictions.js b/tests/programmability/restrictions.js index 8cb6286161b6..3546dd35ec4c 100644 --- a/tests/programmability/restrictions.js +++ b/tests/programmability/restrictions.js @@ -1,5 +1,55 @@ const FIXED_KEY = ccf.strToBuf("hello"); const FIXED_VALUE = ccf.strToBuf("world"); +const SIGNATURE_KEY = new ArrayBuffer(8); +const SIGNATURE_TABLES = [ + "public:ccf.internal.signatures", + "public:ccf.internal.cose_signatures", + "public:ccf.internal.tree", +]; + +function perform_operation(handle, receiver, operation) { + switch (operation) { + case "get": + return handle.get.call(receiver, SIGNATURE_KEY); + case "has": + return handle.has.call(receiver, SIGNATURE_KEY); + case "getVersionOfPreviousWrite": + return handle.getVersionOfPreviousWrite.call(receiver, SIGNATURE_KEY); + case "forEach": + return handle.forEach.call(receiver, () => {}); + case "size": + return Object.getOwnPropertyDescriptor(handle, "size").get.call(receiver); + case "set": + return handle.set.call(receiver, SIGNATURE_KEY, FIXED_VALUE); + case "delete": + return handle.delete.call(receiver, SIGNATURE_KEY); + case "clear": + return handle.clear.call(receiver); + default: + throw new Error(`Unknown operation: ${operation}`); + } +} + +export function try_operation(request) { + const body = request.body.json(); + try { + const receiver = body.forged + ? { _map_name: body.table } + : ccf.kv[body.table]; + const handle = ccf.kv[body.via ?? body.table]; + perform_operation(handle, receiver, body.operation); + } catch (e) { + return { + statusCode: 400, + body: `Failed to ${body.operation} table: ${body.table}\n${e}`, + }; + } + + return { + statusCode: 200, + body: `Permitted to ${body.operation} table: ${body.table}`, + }; +} export function try_read(request) { const table_name = request.body.json().table; @@ -125,7 +175,7 @@ export function try_read_current_via_historical_handle(request) { } const historical_handle = states[0].kv[body.table]; - const permitted = ccf.kv[body.table]; + const permitted = ccf.kv[body.via ?? body.table]; try { permitted.get.call(historical_handle, FIXED_KEY); @@ -141,3 +191,98 @@ export function try_read_current_via_historical_handle(request) { body: `Permitted to read from table: ${body.table}`, }; } + +export function try_read_historical_via_current_handle(request) { + const body = request.body.json(); + const states = ccf.historical.getStateRange(3, body.seqno, body.seqno, 1800); + if (states === null) { + return { + statusCode: 202, + headers: { "retry-after": "1" }, + body: `Historical state at ${body.seqno} is not yet available`, + }; + } + + try { + const historical_handle = states[0].kv[body.table]; + historical_handle.get.call(ccf.kv[body.table], SIGNATURE_KEY); + } catch (e) { + return { + statusCode: 400, + body: `Failed to read historical KV via current handle for table: ${body.table}\n${e}`, + }; + } + + return { + statusCode: 200, + body: `Permitted to read from table: ${body.table}`, + }; +} + +export function read_historical_signature_tables(request) { + const body = request.body.json(); + const states = ccf.historical.getStateRange(4, body.seqno, body.seqno, 1800); + if (states === null) { + return { + statusCode: 202, + headers: { "retry-after": "1" }, + body: `Historical state at ${body.seqno} is not yet available`, + }; + } + + try { + const state = states[0]; + const tables = {}; + for (const table of SIGNATURE_TABLES) { + const handle = state.kv[table]; + const entries = []; + handle.forEach((value, key) => { + const stored_value = handle.get(key); + const bytes = new Uint8Array(value); + const stored_bytes = new Uint8Array(stored_value); + entries.push({ + key: Array.from(new Uint8Array(key)), + valueSize: value.byteLength, + has: handle.has(key), + getMatches: + stored_value !== undefined && + stored_bytes.length === bytes.length && + bytes.every((byte, index) => byte === stored_bytes[index]), + version: handle.getVersionOfPreviousWrite(key), + }); + }); + const write_denied = {}; + for (const operation of ["set", "delete", "clear"]) { + try { + perform_operation(handle, handle, operation); + write_denied[operation] = false; + } catch (e) { + if (!(e instanceof TypeError)) { + throw e; + } + write_denied[operation] = true; + } + } + tables[table] = { + size: handle.size, + entries, + writeDenied: write_denied, + }; + } + + return { + statusCode: 200, + body: { + transactionId: state.transactionId, + isSignatureTransaction: state.receipt.is_signature_transaction, + rawSignatureExpected: state.receipt.signature.length > 0, + tables, + }, + }; + } catch (e) { + return { + statusCode: 400, + body: `Failed to read historical signature tables at ${body.seqno}\n${e}`, + }; + } +} From 63aa90bef9285ae7afbe4f9cb4945dd562c1fc1f Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Fri, 2 Oct 2026 02:06:37 +0100 Subject: [PATCH 02/22] Reference the 8.0 signature-table access PR in release notes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c89f8949a760..c977b4883f1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,12 +11,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Changed -- `GET /node/state` is now a non-transactional command endpoint. Its response body schema is unchanged, but it no longer returns `x-ms-ccf-transaction-id`; `last_signed_seqno` reports progress from a coherent materialised ledger prefix, not an application KV snapshot. +- `GET /node/state` is now a non-transactional command endpoint. Its response body schema is unchanged, but it no longer returns `x-ms-ccf-transaction-id`; `last_signed_seqno` reports progress from a coherent materialised ledger prefix, not an application KV snapshot (#8490). ### Removed -- Removed ordinary live KV access to `public:ccf.internal.signatures`, `public:ccf.internal.cose_signatures` and `public:ccf.internal.tree` in native C++/Rust and current-KV JavaScript application/governance contexts. `Tx`, `ReadOnlyTx` and `TxDiff` reject all typed and untyped handles to these tables. Use historical state or receipt APIs instead; historical read-only access and offline ledger parsing remain supported. All other table permissions are unchanged. - - Copied older constitutions must remove eager raw-signature reads which initialise `ack.state_digest` when adding or resetting members, and use the existing [state-digest update and acknowledgement workflow](doc/governance/adding_member.rst#activating-a-new-member). Default constitutions from 7.0.17 onward already use this workflow. +- Removed ordinary live KV access to `public:ccf.internal.signatures`, `public:ccf.internal.cose_signatures` and `public:ccf.internal.tree` in native C++/Rust and current-KV JavaScript application/governance contexts. `Tx`, `ReadOnlyTx` and `TxDiff` reject all typed and untyped handles to these tables. Use historical state or receipt APIs instead; historical read-only access and offline ledger parsing remain supported. All other table permissions are unchanged (#8490). + - Copied older constitutions must remove eager raw-signature reads which initialise `ack.state_digest` when adding or resetting members, and use the existing [state-digest update and acknowledgement workflow](doc/governance/adding_member.rst#activating-a-new-member). Default constitutions from 7.0.17 onward already use this workflow (#8490). ## [7.0.18] From cc47c22e2989c381fef8b21f7004633c0f386a13 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Fri, 2 Oct 2026 08:15:45 +0100 Subject: [PATCH 03/22] Fix clang-tidy diagnostics for signature-table access policy Use byte-sized access and transaction-role enums and rely on constexpr's implicit inline linkage. This resolves the PR-caused performance-enum-size and redundant-inline diagnostics without changing CI checks or access behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- include/ccf/tx.h | 3 ++- src/kv/internal_table_names.h | 2 +- src/kv/tx_pimpl.h | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/include/ccf/tx.h b/include/ccf/tx.h index 2c9ce4444cf6..242107c59bd8 100644 --- a/include/ccf/tx.h +++ b/include/ccf/tx.h @@ -7,6 +7,7 @@ #include "ccf/kv/version.h" #include "ccf/tx_id.h" +#include #include #include #include @@ -48,7 +49,7 @@ namespace ccf::kv class BaseTx { protected: - enum class AccessMode + enum class AccessMode : std::uint8_t { ReadOnly, ReadWrite, diff --git a/src/kv/internal_table_names.h b/src/kv/internal_table_names.h index d32e2d02080d..1e9b470557fd 100644 --- a/src/kv/internal_table_names.h +++ b/src/kv/internal_table_names.h @@ -19,7 +19,7 @@ namespace ccf::Tables namespace ccf::kv { - inline constexpr bool is_signature_table(std::string_view name) + constexpr bool is_signature_table(std::string_view name) { return name == ccf::Tables::SIGNATURES || name == ccf::Tables::COSE_SIGNATURES || diff --git a/src/kv/tx_pimpl.h b/src/kv/tx_pimpl.h index 48bb2b9cc133..0d15f127b1f6 100644 --- a/src/kv/tx_pimpl.h +++ b/src/kv/tx_pimpl.h @@ -8,7 +8,7 @@ namespace ccf::kv { struct BaseTx::PrivateImpl { - enum class Role + enum class Role : std::uint8_t { Ordinary, Reserved, From 2e579e14f542d0a203a5530740db9b3be81f9851 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Fri, 2 Oct 2026 09:00:11 +0100 Subject: [PATCH 04/22] Quieten signature-table denial logging and document /node/state availability Log denied signature-table access at DEBUG, since the condition is already reported to the caller through MapAccessDenied and a probing application should not emit a FAIL line per request. Record in the changelog and recovery documentation that GET /node/state is now served while the KV store is not yet ready. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- doc/operations/recovery.rst | 2 +- src/kv/tx.cpp | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c977b4883f1b..fd18861b2291 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Changed -- `GET /node/state` is now a non-transactional command endpoint. Its response body schema is unchanged, but it no longer returns `x-ms-ccf-transaction-id`; `last_signed_seqno` reports progress from a coherent materialised ledger prefix, not an application KV snapshot (#8490). +- `GET /node/state` is now a non-transactional command endpoint. Its response body schema is unchanged, but it no longer returns `x-ms-ccf-transaction-id`; `last_signed_seqno` reports progress from a coherent materialised ledger prefix, not an application KV snapshot. It is also served while the node's KV store is not yet ready, for example during public ledger recovery or snapshot installation, rather than returning `503 FrontendNotOpen`; `last_signed_seqno` then reports the last recovered signed seqno (#8490). ### Removed diff --git a/doc/operations/recovery.rst b/doc/operations/recovery.rst index fa3e58168e68..e668b7b64f85 100644 --- a/doc/operations/recovery.rst +++ b/doc/operations/recovery.rst @@ -42,7 +42,7 @@ Each node will then immediately restore the public entries of its ledger (``ledg .. note:: - From CCF 8.0, :http:GET:`/node/state` is a non-transactional command endpoint and no longer returns the ``x-ms-ccf-transaction-id`` response header. Its response body schema is unchanged. The ``last_signed_seqno`` field is read from a coherent, locally materialised ledger prefix. It is progress metadata, independent of application KV snapshots, not a transaction ID for this request. + From CCF 8.0, :http:GET:`/node/state` is a non-transactional command endpoint and no longer returns the ``x-ms-ccf-transaction-id`` response header. Its response body schema is unchanged. The ``last_signed_seqno`` field is read from a coherent, locally materialised ledger prefix. It is progress metadata, independent of application KV snapshots, not a transaction ID for this request. The endpoint is served while the node's KV store is not yet ready, so it can be polled throughout public ledger recovery and snapshot installation. Public-ledger replay temporarily reconstructs the previous service's node entries and consensus configuration. When the recovery service is created, the recovery transaction deletes all previous-service node entries and their associated endorsed certificates and local-sealing records. These nodes do not pass through the normal ``Retired`` and ``retired_committed`` states because the previous service does not participate in the new service's consensus. Consequently, previous-service nodes are absent from both :http:GET:`/node/network/nodes` and :http:GET:`/node/network/removable_nodes` after recovery. See :ref:`architecture/consensus/index:Retirement details` for the normal live-service retirement sequence. diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index 5db4fe8da0ee..68489e95c342 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -67,9 +67,12 @@ namespace ccf::kv if (reason != nullptr) { + // Denials are reported to the caller through the exception. Logging at + // a quieter level avoids a FAIL line per request from a probing or + // misbehaving application. const auto message = fmt::format("Access to map '{}' denied: {}", map_name, reason); - LOG_FAIL_FMT("{}", message); + LOG_DEBUG_FMT("{}", message); throw MapAccessDenied(message); } } From 4888bf81900587c1cb64e110cf9c41284b4fe18a Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Fri, 2 Oct 2026 09:54:06 +0100 Subject: [PATCH 05/22] Benchmark KV handle acquisition Add a handle_acquisition suite to kv_bench timing a minimal read-only transaction (create, acquire one handle, read one key) and the cached re-acquisition of a held handle. These are the only paths exercising the per-handle access policy, and none of the existing commit-centric suites time them. Publish both to Bencher so the cost is tracked. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/kv/test/kv_bench.cpp | 77 ++++++++++++++++++++++++++++++++ tests/convert_pico_to_bencher.py | 12 +++++ 2 files changed, 89 insertions(+) diff --git a/src/kv/test/kv_bench.cpp b/src/kv/test/kv_bench.cpp index 90eb829bb9dd..225c059c2c9f 100644 --- a/src/kv/test/kv_bench.cpp +++ b/src/kv/test/kv_bench.cpp @@ -171,6 +171,69 @@ static void tx_diff(picobench::state& s) throw std::logic_error("Diff visited unexpected number of entries"); } +// Minimal read-only transaction: create it, acquire one handle and read one +// key. Covers transaction creation, map lookup, change set capture and the +// per-handle access policy, none of which the commit-centric suites time. +template +static void ro_tx_single_handle(picobench::state& s) +{ + ccf::logger::config::level() = ccf::LoggerLevel::INFO; + + ccf::kv::Store kv_store; + auto secrets = create_ledger_secrets(); + auto encryptor = std::make_shared(secrets); + kv_store.set_encryptor(encryptor); + + const auto map0 = build_map_name("map0", SD); + const auto key = gen_key(0); + { + auto tx = kv_store.create_tx(); + tx.rw(map0)->put(key, gen_value(0)); + auto rc = tx.commit(); + if (rc != ccf::kv::CommitResult::SUCCESS) + throw std::logic_error( + "Transaction commit failed: " + std::to_string(rc)); + } + + s.start_timer(); + for (int i = 0; i < s.iterations(); i++) + { + auto tx = kv_store.create_read_only_tx(); + auto value = tx.ro(map0)->get(key); + if (!value.has_value()) + throw std::logic_error("Expected key is missing"); + clobber_memory(); + } + s.stop_timer(); +} + +// Re-acquiring a handle already held by the transaction: the cached lookup +// path, where the access policy check is the dominant cost. +static void reacquire_cached_handle(picobench::state& s) +{ + ccf::logger::config::level() = ccf::LoggerLevel::INFO; + + ccf::kv::Store kv_store; + auto secrets = create_ledger_secrets(); + auto encryptor = std::make_shared(secrets); + kv_store.set_encryptor(encryptor); + + const auto map0 = build_map_name("map0", ccf::kv::SecurityDomain::PUBLIC); + + auto tx = kv_store.create_tx(); + auto* first = tx.rw(map0); + + s.start_timer(); + for (int i = 0; i < s.iterations(); i++) + { + auto* handle = tx.rw(map0); + if (handle != first) + throw std::logic_error("Cached handle was not reused"); + clobber_memory(); + } + s.stop_timer(); +} + template static void commit_latency(picobench::state& s) { @@ -316,6 +379,20 @@ PICOBENCH(deserialise).iterations(tx_count).samples(sample_size); PICOBENCH_SUITE("tx_diff"); PICOBENCH(tx_diff).iterations(tx_count).samples(sample_size); +const std::vector handle_count = {1000, 10000}; + +PICOBENCH_SUITE("handle_acquisition"); +PICOBENCH(ro_tx_single_handle) + .iterations(handle_count) + .samples(sample_size) + .baseline(); +PICOBENCH(ro_tx_single_handle) + .iterations(handle_count) + .samples(sample_size); +PICOBENCH(reacquire_cached_handle) + .iterations(handle_count) + .samples(sample_size); + const std::vector map_count = {20, 100}; PICOBENCH_SUITE("serialise_snapshot"); diff --git a/tests/convert_pico_to_bencher.py b/tests/convert_pico_to_bencher.py index 10679b5b3c96..0e22220a9ac4 100644 --- a/tests/convert_pico_to_bencher.py +++ b/tests/convert_pico_to_bencher.py @@ -53,6 +53,18 @@ "Benchmark": "des_snap<1000>", "D": "100", }, + { + "_name": "KV read-only tx handle acquisition", + "Suite": "handle_acquisition", + "Benchmark": "ro_tx_single_handle", + "D": "10000", + }, + { + "_name": "KV cached handle re-acquisition", + "Suite": "handle_acquisition", + "Benchmark": "reacquire_cached_handle", + "D": "10000", + }, ], "map_bench.csv": [ { From b37f6c73012b2f517bcbd3c2b19ff5a8daad2c5b Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Fri, 2 Oct 2026 11:21:16 +0100 Subject: [PATCH 06/22] Fix clang-tidy returns in materialised KV view factories VMSS Virtual A's LLVM 18 clang-tidy rejects the explicit TxDiff and ReadOnlyTx return constructors under modernize-return-braced-init-list. Use braced return initializers, preserving the private constructors, pinned prefix and rollback epoch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/kv/store.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/kv/store.h b/src/kv/store.h index 816028e1356c..262fdf58e18f 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1352,8 +1352,8 @@ namespace ccf::kv if (is_historical) { std::lock_guard vguard(version_lock); - return TxDiff( - this, std::max(last_replicated, compacted.load()), rollback_count); + return { + this, std::max(last_replicated, compacted.load()), rollback_count}; } return {this}; } @@ -1363,8 +1363,8 @@ namespace ccf::kv std::lock_guard vguard(version_lock); // Consensus may compact synchronously in replicate(), before // last_replicated is advanced. Both versions are complete prefixes. - return ReadOnlyTx( - this, std::max(last_replicated, compacted.load()), rollback_count); + return { + this, std::max(last_replicated, compacted.load()), rollback_count}; } CommittableTx create_tx() From 260c66f29fb0d5e1c046205a7457a29d46b40280 Mon Sep 17 00:00:00 2001 From: amchamay Date: Thu, 26 Nov 2026 13:53:33 +0000 Subject: [PATCH 07/22] Trim redundant tests, handle benchmark, and duplicate map-access guard Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- include/ccf/kv/tx.h | 8 +- samples/apps/basic_rust/src/lib.rs | 80 +-- src/js/test/js.cpp | 50 +- src/kv/committable_tx.h | 9 - src/kv/test/kv_bench.cpp | 77 --- src/kv/test/kv_test.cpp | 759 ++++++++------------------ src/kv/tx.cpp | 14 +- tests/basic_rust.py | 26 +- tests/convert_pico_to_bencher.py | 12 - tests/programmability.py | 117 +--- tests/programmability/restrictions.js | 123 +---- 11 files changed, 302 insertions(+), 973 deletions(-) diff --git a/include/ccf/kv/tx.h b/include/ccf/kv/tx.h index 412c9982162a..8d9f8655b94e 100644 --- a/include/ccf/kv/tx.h +++ b/include/ccf/kv/tx.h @@ -73,9 +73,7 @@ namespace ccf::kv const std::string& map_name, std::unique_ptr&& handle); MapChanges get_map_and_change_set_by_name( - const std::string& map_name, - bool track_deletes_on_missing_keys, - AccessMode access); + const std::string& map_name, bool track_deletes_on_missing_keys); std::list get_possible_handles( const std::string& map_name); @@ -113,8 +111,8 @@ namespace ccf::kv retain_handle(map_name, std::move(abstract_handle)); return typed_handle; } - auto [abstract_map, change_set] = get_map_and_change_set_by_name( - map_name, track_deletes_on_missing_keys, access); + auto [abstract_map, change_set] = + get_map_and_change_set_by_name(map_name, track_deletes_on_missing_keys); if (change_set == nullptr) { diff --git a/samples/apps/basic_rust/src/lib.rs b/samples/apps/basic_rust/src/lib.rs index b5263d6fe4f6..05da6f584e08 100644 --- a/samples/apps/basic_rust/src/lib.rs +++ b/samples/apps/basic_rust/src/lib.rs @@ -10,28 +10,12 @@ const COMPACTION_DELAY_MS: u64 = 2_000; const COMPACTION_MARKER: &str = "compaction_marker"; const COMPACTION_RECORDS: &str = "compaction_records"; const RECORDS: &str = "records"; -const SIGNATURE_TABLE_KEY: &[u8] = &[0; 8]; static COMPACTION_READY: AtomicBool = AtomicBool::new(false); fn required_key(value: Result, BridgeError>) -> Result { value?.ok_or_else(|| EndpointError::new(400, "InvalidResourceName", "Missing key")) } -fn signature_table_name( - value: Result, BridgeError>, -) -> Result<&'static str, EndpointError> { - match value?.as_deref() { - Some("signatures") => Ok("public:ccf.internal.signatures"), - Some("cose_signatures") => Ok("public:ccf.internal.cose_signatures"), - Some("tree") => Ok("public:ccf.internal.tree"), - _ => Err(EndpointError::new( - 400, - "InvalidResourceName", - "Unknown signature table", - )), - } -} - fn register(registry: &mut Registry) -> Result<(), BridgeError> { // SNIPPET_START: rust_put_record registry.read_write( @@ -68,61 +52,27 @@ fn register(registry: &mut Registry) -> Result<(), BridgeError> { )?; // SNIPPET_END: rust_get_record - registry.read_only( - "/signature-table-access/{table}/{operation}", - "GET", - Auth::None, - |context| -> EndpointResult { - let table = signature_table_name(context.path_param("table"))?; - let operation = required_key(context.path_param("operation"))?; - match operation.as_str() { - "get" => { - let _ = context.map(table).get(SIGNATURE_TABLE_KEY)?; - } - "has" => { - let _ = context.map(table).has(SIGNATURE_TABLE_KEY)?; - } - _ => { - return Err(EndpointError::new( - 400, - "InvalidOperation", - "Unknown read operation", - )); - } - } - Err(EndpointError::internal( - "Signature table access was permitted", - )) - }, - )?; - registry.read_write( - "/signature-table-access/{table}/{operation}", + "/signature-table-access", "POST", Auth::None, |context| -> EndpointResult { - let table = signature_table_name(context.path_param("table"))?; - let operation = required_key(context.path_param("operation"))?; - match operation.as_str() { - "get" => { - let _ = context.map(table).get(SIGNATURE_TABLE_KEY)?; - } - "has" => { - let _ = context.map(table).has(SIGNATURE_TABLE_KEY)?; - } - "put" => context.map(table).put(SIGNATURE_TABLE_KEY, b"probe")?, - "remove" => context.map(table).remove(SIGNATURE_TABLE_KEY)?, - _ => { - return Err(EndpointError::new( - 400, - "InvalidOperation", - "Unknown KV operation", - )); + for table in [ + "public:ccf.internal.signatures", + "public:ccf.internal.cose_signatures", + "public:ccf.internal.tree", + ] { + if context.map(table).get(&[0; 8]) != Err(BridgeError::AccessDenied) + || context.map(table).put(&[0; 8], b"probe") != Err(BridgeError::AccessDenied) + { + return Err(EndpointError::internal(format!( + "Expected AccessDenied for {table}" + ))); } } - Err(EndpointError::internal( - "Signature table access was permitted", - )) + context.set_status(200)?; + context.set_body(b"denied")?; + Ok(()) }, )?; diff --git a/src/js/test/js.cpp b/src/js/test/js.cpp index 75f133ce68e8..4d40971767e6 100644 --- a/src/js/test/js.cpp +++ b/src/js/test/js.cpp @@ -2948,29 +2948,13 @@ TEST_CASE("Current JS signature table handles deny every operation") CAPTURE(access); auto tx = store.create_tx(); const auto body = std::string(signature_table_test_prelude) + R"JS( -const reader = ccf.kv["public:ccf.internal.table"]; -const writer = ccf.kv["public:signature_permission_probe"]; for (const table of signatureTables) { - const indirectName = ["public:ccf", "internal", table.split(".").pop()].join("."); - const handle = Reflect.get(ccf.kv, indirectName); - handle._map_name = "public:ccf.internal.table"; - handle._source = "Historical"; - handle._seqno = 1; - const direct = [...readOperations(handle), ...writeOperations(handle)]; - const borrowed = [...readOperations(reader), ...writeOperations(writer)]; - for (const [name, operation] of direct) { + const handle = ccf.kv[table]; + for (const [, operation] of [ + ...readOperations(handle), ...writeOperations(handle) + ]) { expectTypeError(() => operation(handle), table, "inaccessible"); } - for (const [name, operation] of borrowed) { - expectTypeError(() => operation(handle), table, "inaccessible"); - for (const forged of [ - {_map_name: table}, - Object.create(handle), - new Proxy(handle, {}) - ]) { - expectTypeError(() => operation(forged), "KV Map Handle object expected"); - } - } } for (const table of [ "public:ccf.internal.table", @@ -2979,10 +2963,10 @@ for (const table of [ "public:ccf.internal.tree_other" ]) { const handle = ccf.kv[table]; - for (const [name, operation] of readOperations(handle)) { + for (const [, operation] of readOperations(handle)) { operation(handle); } - for (const [name, operation] of writeOperations(handle)) { + for (const [, operation] of writeOperations(handle)) { expectTypeError(() => operation(handle), table, "read-only"); } } @@ -3060,7 +3044,6 @@ TEST_CASE("Historical JS signature table handles retain read-only access") restricted) + signature_table_test_prelude + R"JS( export function run() { - const currentReader = ccf.kv["public:ccf.internal.table"]; for (const table of signatureTables) { const handle = testState.kv[table]; if (restricted) { @@ -3099,28 +3082,9 @@ export function run() { if (seen !== handle.size) { throw new Error(`Unexpected iteration count for ${table}`); } - for (const [name, operation] of writeOperations(handle)) { + for (const [, operation] of writeOperations(handle)) { expectTypeError(() => operation(handle), table, "read-only"); } - - const current = ccf.kv[table]; - for (const [name, operation] of readOperations(currentReader)) { - expectTypeError(() => operation(handle), "different key-value store"); - } - for (const [name, operation] of readOperations(handle)) { - expectTypeError(() => operation(current), "different key-value store"); - expectTypeError( - () => operation({_map_name: table, _seqno: 1}), - "KV Map Handle object expected"); - } - handle._map_name = "public:ccf.internal.table"; - handle._source = "CurrentTx"; - if (handle.size !== (populated ? 1 : 0)) { - throw new Error(`Historical handle identity changed for ${table}`); - } - for (const [name, operation] of readOperations(currentReader)) { - expectTypeError(() => operation(handle), "different key-value store"); - } } } )JS"; diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 56224a8497d9..747bd7912ca1 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -6,7 +6,6 @@ #include "ccf/ds/hex.h" #include "ccf/kv/tx.h" #include "ds/internal_logger.h" -#include "kv/internal_table_names.h" #include "kv/tx_pimpl.h" #include "kv_serialiser.h" #include "kv_types.h" @@ -547,14 +546,6 @@ namespace ccf::kv for (const auto& [map_name, changes] : all_changes) { - if (!is_signature_table(map_name)) - { - const auto message = std::format( - "Reserved transaction cannot write to map '{}'", map_name); - LOG_FAIL_FMT("{}", message); - throw MapAccessDenied(message); - } - if ( changes.changeset->read_version.has_value() || !changes.changeset->reads.empty()) diff --git a/src/kv/test/kv_bench.cpp b/src/kv/test/kv_bench.cpp index 08785224837b..3b28f4dbe17a 100644 --- a/src/kv/test/kv_bench.cpp +++ b/src/kv/test/kv_bench.cpp @@ -204,69 +204,6 @@ static void tx_diff(picobench::state& s) throw std::logic_error("Diff visited unexpected number of entries"); } -// Minimal read-only transaction: create it, acquire one handle and read one -// key. Covers transaction creation, map lookup, change set capture and the -// per-handle access policy, none of which the commit-centric suites time. -template -static void ro_tx_single_handle(picobench::state& s) -{ - ccf::logger::config::level() = ccf::LoggerLevel::INFO; - - ccf::kv::Store kv_store; - auto secrets = create_ledger_secrets(); - auto encryptor = std::make_shared(secrets); - kv_store.set_encryptor(encryptor); - - const auto map0 = build_map_name("map0", SD); - const auto key = gen_key(0); - { - auto tx = kv_store.create_tx(); - tx.rw(map0)->put(key, gen_value(0)); - auto rc = tx.commit(); - if (rc != ccf::kv::CommitResult::SUCCESS) - throw std::logic_error( - "Transaction commit failed: " + std::to_string(rc)); - } - - s.start_timer(); - for (int i = 0; i < s.iterations(); i++) - { - auto tx = kv_store.create_read_only_tx(); - auto value = tx.ro(map0)->get(key); - if (!value.has_value()) - throw std::logic_error("Expected key is missing"); - clobber_memory(); - } - s.stop_timer(); -} - -// Re-acquiring a handle already held by the transaction: the cached lookup -// path, where the access policy check is the dominant cost. -static void reacquire_cached_handle(picobench::state& s) -{ - ccf::logger::config::level() = ccf::LoggerLevel::INFO; - - ccf::kv::Store kv_store; - auto secrets = create_ledger_secrets(); - auto encryptor = std::make_shared(secrets); - kv_store.set_encryptor(encryptor); - - const auto map0 = build_map_name("map0", ccf::kv::SecurityDomain::PUBLIC); - - auto tx = kv_store.create_tx(); - auto* first = tx.rw(map0); - - s.start_timer(); - for (int i = 0; i < s.iterations(); i++) - { - auto* handle = tx.rw(map0); - if (handle != first) - throw std::logic_error("Cached handle was not reused"); - clobber_memory(); - } - s.stop_timer(); -} - template static void commit_latency(picobench::state& s) { @@ -421,20 +358,6 @@ PICOBENCH(deserialise).iterations(tx_count).samples(sample_size); PICOBENCH_SUITE("tx_diff"); PICOBENCH(tx_diff).iterations(tx_count).samples(sample_size); -const std::vector handle_count = {1000, 10000}; - -PICOBENCH_SUITE("handle_acquisition"); -PICOBENCH(ro_tx_single_handle) - .iterations(handle_count) - .samples(sample_size) - .baseline(); -PICOBENCH(ro_tx_single_handle) - .iterations(handle_count) - .samples(sample_size); -PICOBENCH(reacquire_cached_handle) - .iterations(handle_count) - .samples(sample_size); - const std::vector map_count = {20, 100}; PICOBENCH_SUITE("serialise_snapshot"); diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index 87e5e19c84b4..c0c5b96e317f 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -103,113 +103,95 @@ TEST_CASE("Live transactions cannot acquire signature table handles") { ccf::kv::Store store; store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + + auto check_denied = [&store]() { + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Restricted table: ", std::string_view(name)); + MapTypes::StringString typed_map(name); + + auto tx = store.create_tx(); + CHECK_THROWS_AS(tx.ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx.rw(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx.wo(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.rw(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.wo(name), ccf::kv::MapAccessDenied); + + auto ro = store.create_read_only_tx(); + CHECK_THROWS_AS(ro.ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + ro.ro(name), ccf::kv::MapAccessDenied); + auto diff = store.create_tx_diff(); + CHECK_THROWS_AS(diff.diff(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + diff.diff(name), ccf::kv::MapAccessDenied); + } + }; + + INFO("Denied before any signature exists, without creating maps or snapshot"); + auto deferred_tx = store.create_tx(); + auto deferred_ro = store.create_read_only_tx(); + CHECK_THROWS_AS( + deferred_tx.ro(ccf::Tables::SIGNATURES), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + deferred_ro.ro(ccf::Tables::SIGNATURES), + ccf::kv::MapAccessDenied); + check_denied(); for (const auto* name : {ccf::Tables::SIGNATURES, ccf::Tables::COSE_SIGNATURES, ccf::Tables::SERIALISED_MERKLE_TREE}) { - INFO("Restricted table: ", std::string_view(name)); - MapTypes::StringString typed_map(name); - - auto tx = store.create_tx(); - CHECK_THROWS_AS(tx.ro(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(tx.rw(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(tx.wo(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.ro(name), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.rw(name), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.wo(name), ccf::kv::MapAccessDenied); - - auto tx_ptr = store.create_tx_ptr(); - CHECK_THROWS_AS(tx_ptr->ro(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(tx_ptr->rw(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(tx_ptr->wo(typed_map), ccf::kv::MapAccessDenied); - ccf::kv::Tx direct_tx(&store); - CHECK_THROWS_AS(direct_tx.ro(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(direct_tx.rw(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(direct_tx.wo(typed_map), ccf::kv::MapAccessDenied); - - auto ro = store.create_read_only_tx(); - CHECK_THROWS_AS(ro.ro(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - ro.ro(name), ccf::kv::MapAccessDenied); - auto ro_ptr = store.create_read_only_tx_ptr(); - CHECK_THROWS_AS(ro_ptr->ro(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - ro_ptr->ro(name), ccf::kv::MapAccessDenied); - ccf::kv::ReadOnlyTx direct_ro(&store); - CHECK_THROWS_AS(direct_ro.ro(typed_map), ccf::kv::MapAccessDenied); - - auto diff = store.create_tx_diff(); - CHECK_THROWS_AS(diff.diff(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - diff.diff(name), ccf::kv::MapAccessDenied); - ccf::kv::TxDiff direct_diff(&store); - CHECK_THROWS_AS(direct_diff.diff(typed_map), ccf::kv::MapAccessDenied); CHECK(store.get_map(store.current_version(), name) == nullptr); } CHECK(store.current_version() == 0); -} - -TEST_CASE("Signature read denial is independent of a pending signature") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); + INFO("Denied while a signature reservation is pending and after it commits"); const auto signature_txid = store.next_txid(); + check_denied(); + MapTypes::StringString ordinary("public:ordinary"); { - auto tx = store.create_tx(); - CHECK_THROWS_AS( - tx.ro(ccf::Tables::SIGNATURES), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.ro(ccf::Tables::COSE_SIGNATURES), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE), - ccf::kv::MapAccessDenied); + auto writer = store.create_tx(); + writer.rw(ordinary)->put("key", "value"); + REQUIRE(writer.commit() == ccf::kv::CommitResult::SUCCESS); + } + REQUIRE(deferred_tx.ro(ordinary)->get("key") == "value"); + REQUIRE(deferred_ro.ro(ordinary)->get("key") == "value"); + REQUIRE( + publish_signature_entry(store, signature_txid, 42) == + ccf::kv::CommitResult::SUCCESS); + check_denied(); - MapTypes::StringString ordinary("public:ordinary"); - tx.rw(ordinary)->put("key", "value"); + INFO("Restrictions apply only to the exact three public signature tables"); + for (const auto* name : + {"public:ccf.internal.signatures_extra", + "public:ccf.internal.cose_signatures.extra", + "public:ccf.internal.tree_extra", + "ccf.internal.signatures", + ccf::Tables::ENCRYPTED_PAST_LEDGER_SECRET}) + { + INFO("Allowed table: ", std::string_view(name)); + MapTypes::StringString map(name); + auto tx = store.create_tx(); + tx.wo(map)->put("key", "value"); + REQUIRE(tx.ro(map)->get("key") == "value"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); auto read = store.create_read_only_tx(); - CHECK(read.ro(ordinary)->get("key") == "value"); + REQUIRE(read.ro(map)->get("key") == "value"); + auto diff = store.create_tx_diff(); + REQUIRE(diff.diff(map)->size() == 1); } - - auto signature = store.create_reserved_tx(signature_txid); - signature.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature( - ccf::kv::test::PrimaryNodeId, signature_txid.seqno)); - signature.wo(ccf::Tables::COSE_SIGNATURES) - ->put(ccf::IdentityType::CLASSICAL, {42}); - signature.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({43}); - auto info = signature.commit_reserved(); - REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); - REQUIRE( - store.commit( - signature_txid, - std::make_unique( - std::move(info.data), - std::move(info.claims_digest), - std::move(info.commit_evidence_digest), - std::move(info.hooks)), - true) == ccf::kv::CommitResult::SUCCESS); - - auto tx = store.create_tx(); - CHECK_THROWS_AS( - tx.ro(ccf::Tables::SIGNATURES), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.ro(ccf::Tables::COSE_SIGNATURES), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE), - ccf::kv::MapAccessDenied); } TEST_CASE("Historical signature entries remain readable") @@ -217,14 +199,7 @@ TEST_CASE("Historical signature entries remain readable") ccf::kv::Store source; source.set_encryptor(std::make_shared()); const auto txid = source.next_txid(); - auto signature = source.create_reserved_tx(txid); - signature.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); - signature.wo(ccf::Tables::COSE_SIGNATURES) - ->put(ccf::IdentityType::CLASSICAL, {42}); - signature.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({43}); - auto info = signature.commit_reserved(); + auto info = make_signature_entry(source, txid, 42); REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); ccf::kv::Store historical(true); @@ -242,208 +217,80 @@ TEST_CASE("Historical signature entries remain readable") ->get(ccf::IdentityType::CLASSICAL) == std::vector{42}); REQUIRE( tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE) - ->get() == std::vector{43}); + ->get() == std::vector{42}); - ccf::Signatures signatures(ccf::Tables::SIGNATURES); - ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); - ccf::SerialisedMerkleTree tree(ccf::Tables::SERIALISED_MERKLE_TREE); auto ptr = historical.create_read_only_tx_ptr(); - REQUIRE(ptr->ro(signatures)->get()->seqno == txid.seqno); - REQUIRE( - ptr->ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == - std::vector{42}); - REQUIRE(ptr->ro(tree)->get() == std::vector{43}); - + auto diff = historical.create_tx_diff(); for (const auto* name : {ccf::Tables::SIGNATURES, ccf::Tables::COSE_SIGNATURES, ccf::Tables::SERIALISED_MERKLE_TREE}) { INFO("Historical table: ", std::string_view(name)); - auto untyped_read = historical.create_read_only_tx(); - REQUIRE(untyped_read.ro(name)->size() == 1); - auto untyped_ptr = historical.create_read_only_tx_ptr(); - REQUIRE(untyped_ptr->ro(name)->size() == 1); - auto diff = historical.create_tx_diff(); + REQUIRE(ptr->ro(name)->size() == 1); REQUIRE(diff.diff(name)->size() == 1); - ccf::kv::ReadOnlyTx direct_ro(&historical); - CHECK_THROWS_AS( - direct_ro.ro(name), ccf::kv::MapAccessDenied); auto ordinary = historical.create_tx(); CHECK_THROWS_AS( ordinary.ro(name), ccf::kv::MapAccessDenied); CHECK_THROWS_AS( ordinary.wo(name), ccf::kv::MapAccessDenied); - auto ordinary_ptr = historical.create_tx_ptr(); - CHECK_THROWS_AS( - ordinary_ptr->rw(name), ccf::kv::MapAccessDenied); } - auto typed_diff = historical.create_tx_diff(); - REQUIRE(typed_diff.diff(cose_signatures)->size() == 1); } -TEST_CASE("Reserved transactions cannot backfill readable maps") +TEST_CASE("Reserved transactions are write-only on signature tables") { ccf::kv::Store store; store.set_encryptor(std::make_shared()); - auto reserved = store.create_reserved_tx(store.next_txid()); - CHECK_THROWS_AS( - reserved.wo("public:ordinary"), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - reserved.rw("public:ordinary"), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - reserved.ro("public:ordinary"), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - reserved.ro(ccf::Tables::SIGNATURES), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - reserved.rw(ccf::Tables::SIGNATURES), - ccf::kv::MapAccessDenied); - CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); -} - -TEST_CASE("Native direct map lookups enforce transaction access policy") -{ - class DirectLookupTx : public ccf::kv::BaseTx - { - public: - using ccf::kv::BaseTx::AccessMode; - using ccf::kv::BaseTx::BaseTx; - - ccf::kv::MapChanges lookup(const std::string& name, AccessMode access) - { - return get_map_and_change_set_by_name(name, false, access); - } - }; - - using Access = DirectLookupTx::AccessMode; - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - DirectLookupTx ordinary(&store); - DirectLookupTx reserved(&store); - auto reserved_role = store.create_reserved_tx(store.next_txid()); - static_cast(reserved) = std::move(reserved_role); + store.set_consensus(std::make_shared()); - for (const auto access : - {Access::ReadOnly, Access::ReadWrite, Access::WriteOnly, Access::Diff}) + INFO("Cannot access non-signature maps or upgrade signature handles"); { + auto reserved = store.create_reserved_tx(store.next_txid()); CHECK_THROWS_AS( - reserved.lookup("public:ordinary", access), ccf::kv::MapAccessDenied); + reserved.wo("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.rw("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.ro("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); + for (const auto* name : {ccf::Tables::SIGNATURES, ccf::Tables::COSE_SIGNATURES, ccf::Tables::SERIALISED_MERKLE_TREE}) { - INFO("Direct lookup table: ", std::string_view(name)); - CHECK_THROWS_AS(ordinary.lookup(name, access), ccf::kv::MapAccessDenied); - if (access != Access::WriteOnly) - { - CHECK_THROWS_AS( - reserved.lookup(name, access), ccf::kv::MapAccessDenied); - } - CHECK(store.get_map(store.current_version(), name) == nullptr); + INFO("Reserved table: ", std::string_view(name)); + auto* handle = reserved.wo(name); + CHECK(reserved.wo(name) == handle); + CHECK_THROWS_AS( + reserved.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.rw(name), ccf::kv::MapAccessDenied); } } - CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); - auto normal = ordinary.lookup("public:ordinary", Access::ReadOnly); - REQUIRE(normal.map != nullptr); - REQUIRE(normal.changeset != nullptr); - auto signature = reserved.lookup(ccf::Tables::SIGNATURES, Access::WriteOnly); - REQUIRE(signature.map != nullptr); - REQUIRE(signature.changeset != nullptr); -} - -TEST_CASE("Signature restrictions apply only to the exact table family") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - for (const auto* name : - {"public:ccf.internal.signatures_extra", - "public:ccf.internal.cose_signatures.extra", - "public:ccf.internal.tree_extra", - "ccf.internal.signatures", - "ccf.internal.tree", - ccf::Tables::ENCRYPTED_PAST_LEDGER_SECRET}) + INFO("Clear on an empty signature table records a read and is rejected"); { - INFO("Allowed table: ", std::string_view(name)); - MapTypes::StringString map(name); - auto tx = store.create_tx(); - tx.wo(map)->put("key", "first"); - REQUIRE(tx.ro(map)->get("key") == "first"); - tx.rw(map)->put("key", "second"); - REQUIRE(tx.ro(map)->get("key") == "second"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - auto read = store.create_read_only_tx(); - REQUIRE(read.ro(map)->get("key") == "second"); - auto diff = store.create_tx_diff(); - REQUIRE(diff.diff(map)->size() == 1); auto reserved = store.create_reserved_tx(store.next_txid()); - CHECK_THROWS_AS(reserved.wo(map), ccf::kv::MapAccessDenied); - } -} - -TEST_CASE("Denied signature handles do not acquire a snapshot") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto tx = store.create_tx(); - auto ro = store.create_read_only_tx(); - CHECK_THROWS_AS( - tx.ro(ccf::Tables::SIGNATURES), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - ro.ro(ccf::Tables::SIGNATURES), ccf::kv::MapAccessDenied); - MapTypes::StringString map("public:ordinary"); - auto writer = store.create_tx(); - writer.rw(map)->put("key", "new"); - REQUIRE(writer.commit() == ccf::kv::CommitResult::SUCCESS); - REQUIRE(tx.ro(map)->get("key") == "new"); - REQUIRE(ro.ro(map)->get("key") == "new"); -} - -TEST_CASE("Reserved write-only handles cannot be upgraded to readable handles") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto reserved = store.create_reserved_tx(store.next_txid()); - for (const auto* name : - {ccf::Tables::SIGNATURES, - ccf::Tables::COSE_SIGNATURES, - ccf::Tables::SERIALISED_MERKLE_TREE}) - { - INFO("Reserved table: ", std::string_view(name)); - MapTypes::StringString map(name); - auto* typed_handle = reserved.wo(map); - CHECK(reserved.wo(map) == typed_handle); - CHECK_THROWS_AS(reserved.ro(map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(reserved.rw(map), ccf::kv::MapAccessDenied); - auto* untyped_handle = reserved.wo(name); - CHECK(reserved.wo(name) == untyped_handle); - CHECK_THROWS_AS( - reserved.ro(name), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - reserved.rw(name), ccf::kv::MapAccessDenied); + auto* tree = reserved.wo( + ccf::Tables::SERIALISED_MERKLE_TREE); + tree->clear(); + tree->put({1}); + CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); } -} -TEST_CASE("Reserved transactions reject all recorded read dependencies") -{ - for (const std::string_view observation : - {"get", "version", "foreach", "range", "size", "clear"}) + INFO("Recorded read dependencies on populated signature tables are rejected"); + const auto baseline = store.next_txid(); + REQUIRE( + publish_signature_entry(store, baseline, 1) == + ccf::kv::CommitResult::SUCCESS); + for (const std::string_view observation : {"get", "foreach", "clear"}) { INFO("Reserved observation: ", observation); - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - store.set_consensus( - std::make_shared()); - const auto baseline = store.next_txid(); - REQUIRE( - publish_signature_entry(store, baseline, 1) == - ccf::kv::CommitResult::SUCCESS); auto reserved = store.create_reserved_tx(store.next_txid()); auto* handle = reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); @@ -452,23 +299,10 @@ TEST_CASE("Reserved transactions reject all recorded read dependencies") { REQUIRE(handle->get(key).has_value()); } - else if (observation == "version") - { - REQUIRE(handle->get_version_of_previous_write(key) == baseline.seqno); - } else if (observation == "foreach") { handle->foreach([](const auto&, const auto&) { return true; }); } - else if (observation == "range") - { - handle->range( - [](const auto&, const auto&) {}, std::nullopt, std::nullopt); - } - else if (observation == "size") - { - REQUIRE(handle->size() == 1); - } else { reserved @@ -476,46 +310,10 @@ TEST_CASE("Reserved transactions reject all recorded read dependencies") ->clear(); } handle->put(key, {2}); - reserved.wo(ccf::Tables::COSE_SIGNATURES) - ->put(ccf::IdentityType::CLASSICAL, {2}); CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); - auto check = store.create_read_only_tx_at_replicated_state(); - REQUIRE( - check.ro(ccf::Tables::SERIALISED_MERKLE_TREE) - ->get() == std::vector{1}); - REQUIRE( - check.ro(ccf::Tables::COSE_SIGNATURES) - ->get(ccf::IdentityType::CLASSICAL) == std::vector{1}); } } -TEST_CASE("Reserved commit validates maps even after base reconstruction") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto ordinary = store.create_tx(); - ordinary.wo("public:ordinary")->put("key", "value"); - auto reserved = store.create_reserved_tx(store.next_txid()); - static_cast(reserved) = std::move(ordinary); - CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); - CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); -} - -TEST_CASE("Reserved clear cannot depend on an empty signature table") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto reserved = store.create_reserved_tx(store.next_txid()); - auto* tree = - reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); - tree->clear(); - tree->put({1}); - CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); - CHECK( - store.get_map( - store.current_version(), ccf::Tables::SERIALISED_MERKLE_TREE) == nullptr); -} - TEST_CASE("Materialised reads exclude gaps and cannot tear signature state") { ccf::kv::Store store; @@ -563,8 +361,6 @@ TEST_CASE("Materialised reads exclude gaps and cannot tear signature state") REQUIRE( read->ro(ccf::Tables::SERIALISED_MERKLE_TREE) ->get() == std::vector{1}); - REQUIRE( - read->ro(ccf::Tables::SIGNATURES)->size() == 1); } auto current = store.create_read_only_tx_at_replicated_state(); @@ -580,252 +376,155 @@ TEST_CASE("Materialised reads exclude gaps and cannot tear signature state") ->get() == std::vector{2}); } -TEST_CASE("Materialised reads reject handles after a rollback epoch changes") +TEST_CASE("Materialised reads reject rollback and see replication compaction") { - for (const bool is_historical : {false, true}) - { - INFO("Historical store: ", is_historical); - ccf::kv::Store store(is_historical); - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); - constexpr ccf::View initial_view = 2; - constexpr ccf::View replacement_view = 3; - store.initialise_term(initial_view); - MapTypes::StringString raw("public:raw"); - ccf::Signatures signatures(ccf::Tables::SIGNATURES); - ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); - ccf::SerialisedMerkleTree tree(ccf::Tables::SERIALISED_MERKLE_TREE); - - { - auto tx = store.create_tx(); - tx.rw(raw)->put("key", "old"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - const auto initial_signature = store.next_txid(); - REQUIRE( - publish_signature_entry(store, initial_signature, 1) == - ccf::kv::CommitResult::SUCCESS); + SUBCASE("Rollback before lookup invalidates live and historical views") + { + for (const bool is_historical : {false, true}) + { + INFO("Historical store: ", is_historical); + ccf::kv::Store store(is_historical); + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + constexpr ccf::View initial_view = 2; + constexpr ccf::View replacement_view = 3; + store.initialise_term(initial_view); + MapTypes::StringString raw("public:raw"); + ccf::Signatures signatures(ccf::Tables::SIGNATURES); + ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); - auto old = store.create_read_only_tx_at_replicated_state(); - REQUIRE(old.ro(raw)->get("key") == "old"); - REQUIRE(old.ro(signatures)->get()->seqno == initial_signature.seqno); - auto public_read = store.create_read_only_tx(); - auto pointer_read = store.create_read_only_tx_ptr(); - auto diff = store.create_tx_diff(); - if (is_historical) - { - REQUIRE( - public_read.ro(signatures)->get()->seqno == initial_signature.seqno); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "old"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto initial_signature = store.next_txid(); REQUIRE( - pointer_read->ro(signatures)->get()->seqno == initial_signature.seqno); - REQUIRE(diff.diff(cose_signatures)->size() == 1); - } + publish_signature_entry(store, initial_signature, 1) == + ccf::kv::CommitResult::SUCCESS); - store.rollback({initial_view, 0}, replacement_view); - consensus->view_history.rollback(0); - consensus->flush(); - { - auto tx = store.create_tx(); - tx.rw(raw)->put("key", "replacement"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - const auto replacement_signature = store.next_txid(); - REQUIRE(replacement_signature.view == replacement_view); - REQUIRE(replacement_signature.seqno == initial_signature.seqno); - REQUIRE( - publish_signature_entry(store, replacement_signature, 2) == - ccf::kv::CommitResult::SUCCESS); + auto old = store.create_read_only_tx_at_replicated_state(); + REQUIRE(old.ro(signatures)->get()->seqno == initial_signature.seqno); + auto diff = store.create_tx_diff(); + if (is_historical) + { + REQUIRE(diff.diff(cose_signatures)->size() == 1); + } - CHECK_THROWS_AS(old.ro(raw), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS(old.ro(signatures), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS(old.ro(cose_signatures), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS(old.ro(tree), ccf::kv::CompactedVersionConflict); - for (const auto* name : - {ccf::Tables::SIGNATURES, - ccf::Tables::COSE_SIGNATURES, - ccf::Tables::SERIALISED_MERKLE_TREE}) - { - INFO("Invalidated table: ", std::string_view(name)); - CHECK_THROWS_AS( - old.ro(name), ccf::kv::CompactedVersionConflict); - } - if (is_historical) - { - CHECK_THROWS_AS( - public_read.ro(signatures), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS(public_read.ro(tree), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS( - pointer_read->ro(signatures), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS( - pointer_read->ro(cose_signatures), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS( - diff.diff(cose_signatures), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS( - diff.diff(ccf::Tables::SERIALISED_MERKLE_TREE), - ccf::kv::CompactedVersionConflict); - } + store.rollback({initial_view, 0}, replacement_view); + consensus->view_history.rollback(0); + consensus->flush(); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "replacement"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto replacement_signature = store.next_txid(); + REQUIRE(replacement_signature.seqno == initial_signature.seqno); + REQUIRE( + publish_signature_entry(store, replacement_signature, 2) == + ccf::kv::CommitResult::SUCCESS); - auto fresh = store.create_read_only_tx_at_replicated_state(); - REQUIRE(fresh.ro(raw)->get("key") == "replacement"); - REQUIRE(fresh.ro(signatures)->get()->seqno == replacement_signature.seqno); - REQUIRE( - fresh.ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == - std::vector{2}); - REQUIRE(fresh.ro(tree)->get() == std::vector{2}); - if (is_historical) - { - auto fresh_pointer = store.create_read_only_tx_ptr(); - REQUIRE(fresh_pointer->ro(tree)->get() == std::vector{2}); - auto fresh_diff = store.create_tx_diff(); - REQUIRE(fresh_diff.diff(cose_signatures)->size() == 1); + CHECK_THROWS_AS(old.ro(raw), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS(old.ro(signatures), ccf::kv::CompactedVersionConflict); + if (is_historical) + { + CHECK_THROWS_AS( + diff.diff(cose_signatures), ccf::kv::CompactedVersionConflict); + } + + auto fresh = store.create_read_only_tx_at_replicated_state(); + REQUIRE(fresh.ro(raw)->get("key") == "replacement"); + REQUIRE( + fresh.ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == + std::vector{2}); } } -} -TEST_CASE("Materialised reads reject rollback during snapshot acquisition") -{ - class ReplacingStore : public ccf::kv::Store + SUBCASE("Rollback during snapshot acquisition is detected") { - public: - std::function replace_during_lookup = nullptr; - bool replacement_triggered = false; - - std::shared_ptr get_map( - ccf::kv::Version version, const std::string& name) override + class ReplacingStore : public ccf::kv::Store { - if ( - name == ccf::Tables::COSE_SIGNATURES && - replace_during_lookup != nullptr) + public: + std::function replace_during_lookup = nullptr; + bool replacement_triggered = false; + + std::shared_ptr get_map( + ccf::kv::Version version, const std::string& name) override { - auto replace = replace_during_lookup; - replace_during_lookup = nullptr; - replacement_triggered = true; - replace(); + if ( + name == ccf::Tables::COSE_SIGNATURES && + replace_during_lookup != nullptr) + { + auto replace = std::exchange(replace_during_lookup, nullptr); + replacement_triggered = true; + replace(); + } + return ccf::kv::Store::get_map(version, name); } - return ccf::kv::Store::get_map(version, name); - } - }; + }; - ReplacingStore store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); - constexpr ccf::View initial_view = 2; - constexpr ccf::View replacement_view = 3; - store.initialise_term(initial_view); - MapTypes::StringString raw("public:raw"); - ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); - ccf::SerialisedMerkleTree tree(ccf::Tables::SERIALISED_MERKLE_TREE); - { - auto tx = store.create_tx(); - tx.rw(raw)->put("key", "old"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - const auto initial_signature = store.next_txid(); - REQUIRE( - publish_signature_entry(store, initial_signature, 1) == - ccf::kv::CommitResult::SUCCESS); - auto old = store.create_read_only_tx_at_replicated_state(); - REQUIRE(old.ro(raw)->get("key") == "old"); - REQUIRE(old.ro(tree)->get() == std::vector{1}); - - store.replace_during_lookup = [&]() { - store.rollback({initial_view, 0}, replacement_view); - consensus->view_history.rollback(0); - consensus->flush(); - auto tx = store.create_tx(); - tx.rw(raw)->put("key", "replacement"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - const auto replacement_signature = store.next_txid(); - REQUIRE(replacement_signature.view == replacement_view); - REQUIRE(replacement_signature.seqno == initial_signature.seqno); + ReplacingStore store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + store.initialise_term(2); + ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); + const auto initial_signature = store.next_txid(); REQUIRE( - publish_signature_entry(store, replacement_signature, 2) == + publish_signature_entry(store, initial_signature, 1) == ccf::kv::CommitResult::SUCCESS); - }; + auto old = store.create_read_only_tx_at_replicated_state(); - CHECK_THROWS_AS(old.ro(cose_signatures), ccf::kv::CompactedVersionConflict); - REQUIRE(store.replacement_triggered); - CHECK_THROWS_AS(old.ro(tree), ccf::kv::CompactedVersionConflict); - auto fresh = store.create_read_only_tx_at_replicated_state(); - REQUIRE(fresh.ro(raw)->get("key") == "replacement"); - REQUIRE( - fresh.ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == - std::vector{2}); - REQUIRE(fresh.ro(tree)->get() == std::vector{2}); -} + store.replace_during_lookup = [&]() { + store.rollback({2, 0}, 3); + consensus->view_history.rollback(0); + consensus->flush(); + REQUIRE( + publish_signature_entry(store, store.next_txid(), 2) == + ccf::kv::CommitResult::SUCCESS); + }; -TEST_CASE("Materialised reads include a prefix compacted inside replication") -{ - class CompactingConsensus : public ccf::kv::test::PrimaryStubConsensus + CHECK_THROWS_AS(old.ro(cose_signatures), ccf::kv::CompactedVersionConflict); + REQUIRE(store.replacement_triggered); + } + + SUBCASE("Prefix compacted synchronously inside replication is visible") { - ccf::kv::Store& store; + class CompactingConsensus : public ccf::kv::test::PrimaryStubConsensus + { + ccf::kv::Store& store; - public: - bool compact_before_return = false; - std::optional observed_signature; + public: + std::optional observed_signature; - explicit CompactingConsensus(ccf::kv::Store& store_) : store(store_) {} + explicit CompactingConsensus(ccf::kv::Store& store_) : store(store_) {} - bool replicate(const ccf::kv::BatchVector& entries, ccf::View view) override - { - const auto result = PrimaryStubConsensus::replicate(entries, view); - if (compact_before_return) + bool replicate( + const ccf::kv::BatchVector& entries, ccf::View view) override { + const auto result = PrimaryStubConsensus::replicate(entries, view); store.compact(std::get<0>(entries.back())); auto read = store.create_read_only_tx_at_replicated_state(); - auto signature = - read.ro(ccf::Tables::SIGNATURES)->get(); - if (signature.has_value()) + if (auto sig = read.ro(ccf::Tables::SIGNATURES)->get()) { - observed_signature = signature->seqno; + observed_signature = sig->seqno; } + return result; } - return result; - } - }; - - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(store); - store.set_consensus(consensus); - const auto txid = store.next_txid(); - consensus->compact_before_return = true; - REQUIRE( - publish_signature_entry(store, txid, 1) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(store.compacted_version() == txid.seqno); - REQUIRE(consensus->observed_signature == txid.seqno); -} + }; -TEST_CASE("Materialised read contexts cannot acquire a writable commit view") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - store.set_consensus(std::make_shared()); - store.initialise_term(2); - MapTypes::StringString map("public:ordinary"); - { - auto tx = store.create_tx(); - tx.rw(map)->put("key", "baseline"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(store); + store.set_consensus(consensus); + const auto txid = store.next_txid(); + REQUIRE( + publish_signature_entry(store, txid, 1) == + ccf::kv::CommitResult::SUCCESS); + REQUIRE(consensus->observed_signature == txid.seqno); } - auto read = store.create_read_only_tx_at_replicated_state(); - auto* untyped = read.ro(map.get_name()); - using Serialiser = MapTypes::StringString::ValueSerialiser; - untyped->put( - Serialiser::to_serialised("key"), Serialiser::to_serialised("pending")); - - auto tx = store.create_tx(); - static_cast(tx) = std::move(read); - CHECK_THROWS_AS(tx.rw(map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(tx.wo(map), ccf::kv::MapAccessDenied); - CHECK_THROWS_WITH_AS( - tx.set_read_txid({2, 1}, 2), "Read TxID already set", std::logic_error); - CHECK(tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); - CHECK(store.current_version() == 1); - auto check = store.create_read_only_tx(); - CHECK(check.ro(map)->get("key") == "baseline"); } TEST_CASE("Zero-revision whole-map dependencies") diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index 37ee70d061e0..4341e9a3ed4e 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -104,12 +104,8 @@ namespace ccf::kv } MapChanges BaseTx::get_map_and_change_set_by_name( - const std::string& map_name, - bool track_deletes_on_missing_keys, - AccessMode access) + const std::string& map_name, bool track_deletes_on_missing_keys) { - check_map_access(map_name, access); - auto& read_txid = pimpl->read_txid; #ifdef CCF_KV_TRACING trace::Context trace_context(pimpl->trace_attempt.id); @@ -159,9 +155,13 @@ namespace ccf::kv auto change_set = untyped_map->create_change_set( read_txid->seqno, track_deletes_on_missing_keys); // Rollback can replace a map between the access check and snapshot capture. - if (pimpl->role == PrivateImpl::Role::MaterialisedReadOnly) + if ( + pimpl->role == PrivateImpl::Role::MaterialisedReadOnly && + !pimpl->store->check_rollback_count(pimpl->read_rollback_count)) { - check_map_access(map_name, access); + throw CompactedVersionConflict(std::format( + "Materialised state for map '{}' was invalidated by rollback", + map_name)); } return {abstract_map, std::move(change_set)}; } diff --git a/tests/basic_rust.py b/tests/basic_rust.py index 7c2ab130e0b5..3894eaddc475 100644 --- a/tests/basic_rust.py +++ b/tests/basic_rust.py @@ -80,34 +80,14 @@ def test_basic_rust(network, args): @reqs.description("Rust KV calls report explicit denial of current signature tables") -@reqs.supports_methods("/app/signature-table-access/{table}/{operation}") +@reqs.supports_methods("/app/signature-table-access") def test_signature_table_access_denied(network, args): primary, _ = network.find_primary() with primary.client() as anonymous: - for table in ("signatures", "cose_signatures", "tree"): - for method, operations in ( - (anonymous.get, ("get", "has")), - (anonymous.post, ("get", "has", "put", "remove")), - ): - for operation in operations: - path = f"/app/signature-table-access/{table}/{operation}" - response = method(path) - assert ( - response.status_code == http.HTTPStatus.INTERNAL_SERVER_ERROR - ), ( - path, - response, - ) - error = response.body.json()["error"] - assert error["code"] == "InternalError", (path, error) - assert error["message"] == "CCF bridge error: AccessDenied", ( - path, - error, - ) - - response = anonymous.get("/app/health") + response = anonymous.post("/app/signature-table-access") assert response.status_code == http.HTTPStatus.OK, response + assert response.body.text() == "denied" return network diff --git a/tests/convert_pico_to_bencher.py b/tests/convert_pico_to_bencher.py index 0e22220a9ac4..10679b5b3c96 100644 --- a/tests/convert_pico_to_bencher.py +++ b/tests/convert_pico_to_bencher.py @@ -53,18 +53,6 @@ "Benchmark": "des_snap<1000>", "D": "100", }, - { - "_name": "KV read-only tx handle acquisition", - "Suite": "handle_acquisition", - "Benchmark": "ro_tx_single_handle", - "D": "10000", - }, - { - "_name": "KV cached handle re-acquisition", - "Suite": "handle_acquisition", - "Benchmark": "reacquire_cached_handle", - "D": "10000", - }, ], "map_bench.csv": [ { diff --git a/tests/programmability.py b/tests/programmability.py index a99a54116d5a..8fbb7a292904 100644 --- a/tests/programmability.py +++ b/tests/programmability.py @@ -277,8 +277,6 @@ def test_custom_endpoints_kv_restrictions(network, args): "public:ccf.internal.cose_signatures", "public:ccf.internal.tree", ) - read_operations = ("get", "has", "getVersionOfPreviousWrite", "forEach", "size") - write_operations = ("set", "delete", "clear") endpoints = { "/try_read": { @@ -294,19 +292,6 @@ def test_custom_endpoints_kv_restrictions(network, args): mode="readwrite", ) }, - "/try_operation_ro": { - "post": endpoint_properties( - js_module=module_name, - js_function="try_operation", - ) - }, - "/try_operation_rw": { - "post": endpoint_properties( - js_module=module_name, - js_function="try_operation", - mode="readwrite", - ) - }, "/try_read_retargeted": { "post": endpoint_properties( js_module=module_name, @@ -325,12 +310,6 @@ def test_custom_endpoints_kv_restrictions(network, args): js_function="try_read_current_via_historical_handle", ) }, - "/try_read_historical_via_current_handle": { - "post": endpoint_properties( - js_module=module_name, - js_function="try_read_historical_via_current_handle", - ) - }, "/read_historical_signature_tables": { "post": endpoint_properties( js_module=module_name, @@ -442,57 +421,28 @@ def test_custom_endpoints_kv_restrictions(network, args): assert r.status_code == http.HTTPStatus.BAD_REQUEST.value, r.status_code LOG.info("Current signature tables are inaccessible, not merely read-only") - for path in ("/app/try_operation_ro", "/app/try_operation_rw"): - for table in signature_tables: - for operation in read_operations + write_operations: - for receiver in ( - {}, - {"via": "my_js_table"}, - {"via": "my_js_table", "forged": True}, - ): - body = {"table": table, "operation": operation, **receiver} - r = c.post(path, body) - assert r.status_code == http.HTTPStatus.BAD_REQUEST, ( - path, - body, - r.status_code, - r.body.text(), - ) - expected = ( - "KV Map Handle object expected" - if receiver.get("forged") - else "inaccessible" - ) - assert expected in r.body.text(), (body, r.body.text()) + for table in signature_tables: + for path in ("/app/try_read", "/app/try_write"): + r = c.post(path, {"table": table}) + assert r.status_code == http.HTTPStatus.BAD_REQUEST, ( + path, + table, + r.status_code, + r.body.text(), + ) + assert "inaccessible" in r.body.text(), (table, r.body.text()) - LOG.info( - "Other public internal tables, including neighboring names, remain read-only" - ) + LOG.info("Neighboring public internal tables remain read-only") for table in ( - "public:ccf.internal.foo", "public:ccf.internal.signatures_other", "public:ccf.internal.cose_signatures_other", "public:ccf.internal.tree.nested", ): - for operation in read_operations: - r = c.post( - "/app/try_operation_ro", {"table": table, "operation": operation} - ) - assert r.status_code == http.HTTPStatus.OK, ( - table, - operation, - r.body.text(), - ) - for operation in write_operations: - r = c.post( - "/app/try_operation_rw", {"table": table, "operation": operation} - ) - assert r.status_code == http.HTTPStatus.BAD_REQUEST, ( - table, - operation, - r.body.text(), - ) - assert "read-only" in r.body.text(), r.body.text() + r = c.post("/app/try_read", {"table": table}) + assert r.status_code == http.HTTPStatus.OK, (table, r.body.text()) + r = c.post("/app/try_write", {"table": table}) + assert r.status_code == http.HTTPStatus.BAD_REQUEST, (table, r.body.text()) + assert "read-only" in r.body.text(), (table, r.body.text()) LOG.info("Cannot grant access to (hypothetical) private gov/internal tables") r = c.post("/app/try_read", {"table": "ccf.gov.foo"}) @@ -593,43 +543,12 @@ def post_until_available(client, path, body): if result["rawSignatureExpected"]: required_tables.add(signature_tables[0]) for table, contents in result["tables"].items(): - assert contents["writeDenied"] == dict.fromkeys(write_operations, True), ( - table, - contents, - ) - assert contents["size"] == len(contents["entries"]), (table, contents) + assert contents["writeDenied"], (table, contents) + assert contents["size"] == contents["entries"], (table, contents) if table not in required_tables: assert contents["size"] == 0, (table, contents) continue assert contents["size"] > 0, (table, contents) - assert [0] * 8 in [entry["key"] for entry in contents["entries"]], ( - table, - contents, - ) - if table != signature_tables[1]: - assert contents["size"] == 1, (table, contents) - for entry in contents["entries"]: - assert entry["valueSize"] > 0, (table, entry) - assert entry["has"], (table, entry) - assert entry["getMatches"], (table, entry) - assert entry["version"] == signed_seqno, (table, entry) - - LOG.info("Current and historical signature handles cannot exchange methods") - for table in signature_tables: - r = post_until_available( - c, - "/app/try_read_current_via_historical_handle", - {"table": table, "via": "my_js_table", "seqno": signed_seqno}, - ) - assert r.status_code == http.HTTPStatus.BAD_REQUEST, r.body.text() - assert "different key-value store" in r.body.text(), r.body.text() - r = post_until_available( - c, - "/app/try_read_historical_via_current_handle", - {"table": table, "seqno": signed_seqno}, - ) - assert r.status_code == http.HTTPStatus.BAD_REQUEST, r.body.text() - assert "different key-value store" in r.body.text(), r.body.text() return network diff --git a/tests/programmability/restrictions.js b/tests/programmability/restrictions.js index 3546dd35ec4c..d3ca125e8c51 100644 --- a/tests/programmability/restrictions.js +++ b/tests/programmability/restrictions.js @@ -1,56 +1,11 @@ const FIXED_KEY = ccf.strToBuf("hello"); const FIXED_VALUE = ccf.strToBuf("world"); -const SIGNATURE_KEY = new ArrayBuffer(8); const SIGNATURE_TABLES = [ "public:ccf.internal.signatures", "public:ccf.internal.cose_signatures", "public:ccf.internal.tree", ]; -function perform_operation(handle, receiver, operation) { - switch (operation) { - case "get": - return handle.get.call(receiver, SIGNATURE_KEY); - case "has": - return handle.has.call(receiver, SIGNATURE_KEY); - case "getVersionOfPreviousWrite": - return handle.getVersionOfPreviousWrite.call(receiver, SIGNATURE_KEY); - case "forEach": - return handle.forEach.call(receiver, () => {}); - case "size": - return Object.getOwnPropertyDescriptor(handle, "size").get.call(receiver); - case "set": - return handle.set.call(receiver, SIGNATURE_KEY, FIXED_VALUE); - case "delete": - return handle.delete.call(receiver, SIGNATURE_KEY); - case "clear": - return handle.clear.call(receiver); - default: - throw new Error(`Unknown operation: ${operation}`); - } -} - -export function try_operation(request) { - const body = request.body.json(); - try { - const receiver = body.forged - ? { _map_name: body.table } - : ccf.kv[body.table]; - const handle = ccf.kv[body.via ?? body.table]; - perform_operation(handle, receiver, body.operation); - } catch (e) { - return { - statusCode: 400, - body: `Failed to ${body.operation} table: ${body.table}\n${e}`, - }; - } - - return { - statusCode: 200, - body: `Permitted to ${body.operation} table: ${body.table}`, - }; -} - export function try_read(request) { const table_name = request.body.json().table; var handle; @@ -175,7 +130,7 @@ export function try_read_current_via_historical_handle(request) { } const historical_handle = states[0].kv[body.table]; - const permitted = ccf.kv[body.via ?? body.table]; + const permitted = ccf.kv[body.table]; try { permitted.get.call(historical_handle, FIXED_KEY); @@ -192,36 +147,9 @@ export function try_read_current_via_historical_handle(request) { }; } -export function try_read_historical_via_current_handle(request) { - const body = request.body.json(); - const states = ccf.historical.getStateRange(3, body.seqno, body.seqno, 1800); - if (states === null) { - return { - statusCode: 202, - headers: { "retry-after": "1" }, - body: `Historical state at ${body.seqno} is not yet available`, - }; - } - - try { - const historical_handle = states[0].kv[body.table]; - historical_handle.get.call(ccf.kv[body.table], SIGNATURE_KEY); - } catch (e) { - return { - statusCode: 400, - body: `Failed to read historical KV via current handle for table: ${body.table}\n${e}`, - }; - } - - return { - statusCode: 200, - body: `Permitted to read from table: ${body.table}`, - }; -} - export function read_historical_signature_tables(request) { const body = request.body.json(); - const states = ccf.historical.getStateRange(4, body.seqno, body.seqno, 1800); + const states = ccf.historical.getStateRange(3, body.seqno, body.seqno, 1800); if (states === null) { return { statusCode: 202, @@ -235,39 +163,28 @@ export function read_historical_signature_tables(request) { const tables = {}; for (const table of SIGNATURE_TABLES) { const handle = state.kv[table]; - const entries = []; + let entries = 0; handle.forEach((value, key) => { - const stored_value = handle.get(key); - const bytes = new Uint8Array(value); - const stored_bytes = new Uint8Array(stored_value); - entries.push({ - key: Array.from(new Uint8Array(key)), - valueSize: value.byteLength, - has: handle.has(key), - getMatches: - stored_value !== undefined && - stored_bytes.length === bytes.length && - bytes.every((byte, index) => byte === stored_bytes[index]), - version: handle.getVersionOfPreviousWrite(key), - }); + if ( + !handle.has(key) || + handle.get(key) === undefined || + value.byteLength === 0 || + handle.getVersionOfPreviousWrite(key) !== body.seqno + ) { + throw new Error(`Unreadable historical entry in ${table}`); + } + entries++; }); - const write_denied = {}; - for (const operation of ["set", "delete", "clear"]) { - try { - perform_operation(handle, handle, operation); - write_denied[operation] = false; - } catch (e) { - if (!(e instanceof TypeError)) { - throw e; - } - write_denied[operation] = true; + let writeDenied = false; + try { + handle.set(FIXED_KEY, FIXED_VALUE); + } catch (e) { + if (!(e instanceof TypeError)) { + throw e; } + writeDenied = true; } - tables[table] = { - size: handle.size, - entries, - writeDenied: write_denied, - }; + tables[table] = { size: handle.size, entries, writeDenied }; } return { From 1bdba856c52d3c7161edae9c04b8d75ae0f1d01f Mon Sep 17 00:00:00 2001 From: amchamay Date: Thu, 26 Nov 2026 14:55:25 +0000 Subject: [PATCH 08/22] Avoid version_lock contention in rollback_count checks and materialised tx setup Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/kv/store.h | 43 +++++++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/src/kv/store.h b/src/kv/store.h index 8ecbdf7d0eb5..282e13a87844 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -66,7 +66,9 @@ namespace ccf::kv // Always <= version: rollback() clamps it. Version last_committable = 0; - Version rollback_count = 0; + // Written only under version_lock; atomic so check_rollback_count() can + // read it without contending on version_lock. + std::atomic rollback_count = 0; std::unordered_map, bool>> pending_txs; @@ -1415,8 +1417,7 @@ namespace ccf::kv bool check_rollback_count(Version count) override { - std::lock_guard vguard(version_lock); - return rollback_count == count; + return rollback_count.load() == count; } std::optional> next_version( @@ -1440,7 +1441,7 @@ namespace ccf::kv Version v = next_version_unsafe(); KV_TRACE(trace::apply(this, v, term_of_next_version)); - return std::make_tuple(v, rollback_count); + return std::make_tuple(v, rollback_count.load()); } TxID next_txid() override @@ -1592,6 +1593,17 @@ namespace ccf::kv } } + private: + std::pair materialised_read_state() + { + std::lock_guard vguard(version_lock); + // Consensus may compact synchronously in replicate(), before + // last_replicated is advanced. Both versions are complete prefixes. + return { + std::max(last_replicated, compacted.load()), rollback_count.load()}; + } + + public: ReadOnlyTx create_read_only_tx() override { if (is_historical) @@ -1605,10 +1617,11 @@ namespace ccf::kv { if (is_historical) { - std::lock_guard vguard(version_lock); + const auto [read_version, read_rollback_count] = + materialised_read_state(); // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - return std::unique_ptr(new ReadOnlyTx( - this, std::max(last_replicated, compacted.load()), rollback_count)); + return std::unique_ptr( + new ReadOnlyTx(this, read_version, read_rollback_count)); } return std::make_unique(this); } @@ -1617,20 +1630,18 @@ namespace ccf::kv { if (is_historical) { - std::lock_guard vguard(version_lock); - return { - this, std::max(last_replicated, compacted.load()), rollback_count}; + const auto [read_version, read_rollback_count] = + materialised_read_state(); + return {this, read_version, read_rollback_count}; } return {this}; } ReadOnlyTx create_read_only_tx_at_replicated_state() { - std::lock_guard vguard(version_lock); - // Consensus may compact synchronously in replicate(), before - // last_replicated is advanced. Both versions are complete prefixes. - return { - this, std::max(last_replicated, compacted.load()), rollback_count}; + const auto [read_version, read_rollback_count] = + materialised_read_state(); + return {this, read_version, read_rollback_count}; } CommittableTx create_tx() @@ -1646,7 +1657,7 @@ namespace ccf::kv ReservedTx create_reserved_tx(const TxID& tx_id) { std::lock_guard vguard(version_lock); - return {this, term_of_last_version, tx_id, rollback_count}; + return {this, term_of_last_version, tx_id, rollback_count.load()}; } bool apply_tx_flags( From 9a5d36530d187d5cd4651ed1b0776c6e72cf48d3 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Sat, 28 Nov 2026 21:55:55 +0000 Subject: [PATCH 09/22] Track globally committed reads in reserved transactions Track get_globally_committed() and has_globally_committed() calls on untyped::ChangeSet::read_globally_committed and reject them in ReservedTx::commit_reserved() without altering conflict tracking for ordinary transactions. Add regression coverage for both methods after compaction. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- src/kv/committable_tx.h | 1 + src/kv/test/kv_test.cpp | 18 ++++++++++++++++-- src/kv/untyped_change_set.h | 1 + src/kv/untyped_map_handle.cpp | 4 ++++ 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 747bd7912ca1..3bf1e0084594 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -548,6 +548,7 @@ namespace ccf::kv { if ( changes.changeset->read_version.has_value() || + changes.changeset->read_globally_committed || !changes.changeset->reads.empty()) { const auto message = std::format( diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index c0c5b96e317f..720ddf6a0347 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -288,7 +288,13 @@ TEST_CASE("Reserved transactions are write-only on signature tables") REQUIRE( publish_signature_entry(store, baseline, 1) == ccf::kv::CommitResult::SUCCESS); - for (const std::string_view observation : {"get", "foreach", "clear"}) + store.compact(baseline.seqno); + for (const std::string_view observation : + {"get", + "foreach", + "clear", + "get_globally_committed", + "has_globally_committed"}) { INFO("Reserved observation: ", observation); auto reserved = store.create_reserved_tx(store.next_txid()); @@ -303,12 +309,20 @@ TEST_CASE("Reserved transactions are write-only on signature tables") { handle->foreach([](const auto&, const auto&) { return true; }); } - else + else if (observation == "clear") { reserved .wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->clear(); } + else if (observation == "get_globally_committed") + { + REQUIRE(handle->get_globally_committed(key).has_value()); + } + else + { + REQUIRE(handle->has_globally_committed(key)); + } handle->put(key, {2}); CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); } diff --git a/src/kv/untyped_change_set.h b/src/kv/untyped_change_set.h index e898fbac417b..9d9afd35d10e 100644 --- a/src/kv/untyped_change_set.h +++ b/src/kv/untyped_change_set.h @@ -46,6 +46,7 @@ namespace ccf::kv::untyped const Version start_version = {}; std::optional read_version = std::nullopt; + bool read_globally_committed = false; ccf::kv::untyped::Read reads; ccf::kv::untyped::Write writes; diff --git a/src/kv/untyped_map_handle.cpp b/src/kv/untyped_map_handle.cpp index 76f33be2aaba..a8428f961971 100644 --- a/src/kv/untyped_map_handle.cpp +++ b/src/kv/untyped_map_handle.cpp @@ -191,6 +191,8 @@ namespace ccf::kv::untyped std::optional MapHandle::get_globally_committed( const MapHandle::KeyType& key) { + tx_changes.read_globally_committed = true; + // If there is no committed value, return empty. auto search = tx_changes.committed.get(key); KV_TRACE(trace::operation( @@ -225,6 +227,8 @@ namespace ccf::kv::untyped bool MapHandle::has_globally_committed(const MapHandle::KeyType& key) { + tx_changes.read_globally_committed = true; + const auto* raw = tx_changes.committed.getp(key); KV_TRACE(trace::operation( tx_changes.trace_metadata, From 28693321379acbbe1def815c781ca9da3041597d Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Sat, 28 Nov 2026 22:13:23 +0000 Subject: [PATCH 10/22] Reject CommittableTx::commit() on reserved transactions Guard CommittableTx::commit() against PrivateImpl::Role::Reserved so reserved transactions cannot bypass commit_reserved() validation or allocate a fresh version directly or through a base reference. Add regression coverage in kv_test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- src/kv/committable_tx.h | 6 ++++++ src/kv/test/kv_test.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 3bf1e0084594..4261044f3827 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -197,6 +197,12 @@ namespace ccf::kv const ccf::ClaimsDigest& claims = ccf::empty_claims(), WriteSetObserver write_set_observer = nullptr) { + if (pimpl->role == PrivateImpl::Role::Reserved) + { + throw std::logic_error( + "Reserved transaction must be committed with commit_reserved()"); + } + if (committed) { throw std::logic_error("Transaction already committed"); diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index 720ddf6a0347..8177ccc4ae0a 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -4404,6 +4404,36 @@ TEST_CASE("CommittableTx guards") std::logic_error); } + SUBCASE("commit rejects a reserved transaction directly and via base ref") + { + ccf::kv::Store kv_store; + kv_store.set_encryptor(std::make_shared()); + + const auto reserved_txid = kv_store.next_txid(); + auto reserved = kv_store.create_reserved_tx(reserved_txid); + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({42}); + + REQUIRE_THROWS_WITH_AS( + reserved.commit(), + "Reserved transaction must be committed with commit_reserved()", + std::logic_error); + + ccf::kv::CommittableTx& base = reserved; + REQUIRE_THROWS_WITH_AS( + base.commit(), + "Reserved transaction must be committed with commit_reserved()", + std::logic_error); + + REQUIRE(kv_store.current_version() == reserved_txid.seqno); + REQUIRE_THROWS_WITH_AS( + auto _ = reserved.commit_version(), + "Transaction not yet committed", + std::logic_error); + REQUIRE( + reserved.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); + } + SUBCASE("commit_reserved rejects being called twice") { ccf::kv::Store kv_store; From 77bec9872026c2aa8c25e30ad9a3288255d085d5 Mon Sep 17 00:00:00 2001 From: amchamay Date: Mon, 30 Nov 2026 12:08:26 +0000 Subject: [PATCH 11/22] Test /node/state pre-readiness progress and narrow snapshot-install doc claim Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/operations/recovery.rst | 2 +- doc/releases/migration_7_x_to_8_x.rst | 2 +- src/node/rpc/test/node_frontend_test.cpp | 243 +++++++++++++++++++++++ src/node/rpc/test/node_stub.h | 9 +- 4 files changed, 251 insertions(+), 5 deletions(-) diff --git a/doc/operations/recovery.rst b/doc/operations/recovery.rst index 5d92eeb82650..8b5f54c833bf 100644 --- a/doc/operations/recovery.rst +++ b/doc/operations/recovery.rst @@ -42,7 +42,7 @@ Each node will then immediately restore the public entries of its ledger (``ledg .. note:: - From CCF 8.0, :http:GET:`/node/state` is non-transactional: it does not return the ``x-ms-ccf-transaction-id`` header, and ``last_signed_seqno`` reports node progress rather than a KV snapshot. The endpoint is available throughout public ledger recovery and snapshot installation, before the KV store is ready. + From CCF 8.0, :http:GET:`/node/state` is non-transactional: it does not return the ``x-ms-ccf-transaction-id`` header, and ``last_signed_seqno`` reports node progress rather than a KV snapshot. The endpoint is served before the KV store is ready, including during public ledger recovery. At startup, the host discovers the latest committed chunk end across all configured ledger directories before restoring mutable chunks. Mutable chunks whose reconstructed end is at or before this committed frontier, including incomplete chunks without an end index in their filename, are renamed with an ``.ignored`` suffix rather than reused for new appends. Chunks which overlap the committed history but extend beyond that frontier are retained. diff --git a/doc/releases/migration_7_x_to_8_x.rst b/doc/releases/migration_7_x_to_8_x.rst index e699fbb2f06a..bfd56e2767b8 100644 --- a/doc/releases/migration_7_x_to_8_x.rst +++ b/doc/releases/migration_7_x_to_8_x.rst @@ -128,4 +128,4 @@ From CCF 8.0, ``public:ccf.internal.signatures``, ``public:ccf.internal.cose_sig Use historical KV views, :doc:`receipt APIs ` or :doc:`offline ledger parsing ` instead; see :ref:`audit/read_write_restrictions:Signature-Transaction Tables` and :ref:`build_apps/kv/kv_how_to:Signature Metadata`. - Custom constitutions based on releases before 7.0.17 that read ``public:ccf.internal.signatures`` or ``public:ccf.internal.cose_signatures`` when adding or resetting a member must remove those reads and use the :ref:`state-digest update and acknowledgement workflow `. -- :http:GET:`/node/state` is now non-transactional: it no longer returns the ``x-ms-ccf-transaction-id`` header, and it is served during public ledger recovery and snapshot installation before the KV store is ready. +- :http:GET:`/node/state` is now non-transactional: it no longer returns the ``x-ms-ccf-transaction-id`` header, and it is served before the KV store is ready, including during public ledger recovery. diff --git a/src/node/rpc/test/node_frontend_test.cpp b/src/node/rpc/test/node_frontend_test.cpp index 1140fc0cb5d0..a380c2bf6db5 100644 --- a/src/node/rpc/test/node_frontend_test.cpp +++ b/src/node/rpc/test/node_frontend_test.cpp @@ -636,8 +636,209 @@ TEST_CASE("Self certificate authentication") TEST_CASE("Node state is explicitly nontransactional metadata") { + class MinimalNodeState : public ccf::AbstractNodeState + { + ccf::CCFConfig config = {}; + nlohmann::json node_data = nullptr; + + public: + void transition_service_to_open( + ccf::kv::Tx&, AbstractGovernanceEffects::ServiceIdentities) override + { + throw std::logic_error("Unimplemented"); + } + + bool rekey_ledger(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + void trigger_recovery_shares_refresh(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + void trigger_ledger_chunk(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + void trigger_snapshot(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + [[nodiscard]] bool is_in_initialised_state() const override + { + return false; + } + + [[nodiscard]] bool is_part_of_public_network() const override + { + return false; + } + + [[nodiscard]] bool is_primary() const override + { + return false; + } + + bool can_replicate() override + { + return false; + } + + std::optional get_primary() override + { + return std::nullopt; + } + + [[nodiscard]] bool is_reading_public_ledger() const override + { + return false; + } + + [[nodiscard]] bool is_reading_private_ledger() const override + { + return false; + } + + [[nodiscard]] bool is_part_of_network() const override + { + return false; + } + + ccf::kv::Version get_last_recovered_signed_idx() override + { + return 0; + } + + void initiate_private_recovery(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + ExtendedState state() override + { + return {NodeStartupState::uninitialized, std::nullopt, std::nullopt}; + } + + QuoteVerificationResult verify_quote( + ccf::kv::ReadOnlyTx&, + const QuoteInfo&, + const std::vector&, + pal::PlatformAttestationMeasurement&, + const std::optional>&, + std::shared_ptr) override + { + throw std::logic_error("Unimplemented"); + } + + ccf::kv::Version get_startup_snapshot_seqno() override + { + return 0; + } + + SessionMetrics get_session_metrics() override + { + return {}; + } + + ccf::crypto::Pem get_self_signed_certificate() override + { + return {}; + } + + const ccf::COSESignaturesConfig& get_cose_signatures_config() override + { + throw std::logic_error("Unimplemented"); + } + + RecoveryDecisionProtocolSubsystem& get_recovery_decision_protocol() override + { + throw std::logic_error("Unimplemented"); + } + + void shuffle_sealed_shares(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + [[nodiscard]] const ccf::CCFConfig& get_node_config() const override + { + return config; + } + + [[nodiscard]] const nlohmann::json& get_node_data() const override + { + return node_data; + } + + ccf::crypto::Pem get_network_cert() override + { + return {}; + } + + void stop_notice() override {} + + bool has_received_stop_notice() override + { + return false; + } + + bool is_member_frontend_open() override + { + return false; + } + + bool is_user_frontend_open() override + { + return false; + } + + [[nodiscard]] bool is_accessible_to_members() const override + { + return false; + } + + std::shared_ptr get_store() override + { + return nullptr; + } + }; + NetworkState network; + network.tables->set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + network.tables->set_consensus(consensus); + + // Record a higher signed seqno in the KV so pre-readiness checks fail if + // they accidentally read from the store instead of node progress metadata. + constexpr ccf::kv::Version kv_signed_seqno = 99; + { + const auto txid = network.tables->next_txid(); + auto tx = network.tables->create_reserved_tx(txid); + tx.wo(Tables::SIGNATURES) + ->put( + ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, kv_signed_seqno)); + tx.wo(Tables::SERIALISED_MERKLE_TREE)->put({}); + auto info = tx.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + network.tables->commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true) == ccf::kv::CommitResult::SUCCESS); + } + + MinimalNodeState node_state; StubNodeContext context; + context.install_subsystem(std::make_shared( + node_state, NodeConfigurationSubsystem::InterfaceRegexes{})); TestNodeRpcFrontend frontend(network, context); frontend.open(); @@ -654,6 +855,48 @@ TEST_CASE("Node state is explicitly nontransactional metadata") endpoint->properties.forwarding_required == ccf::endpoints::ForwardingRequired::Never); CHECK(endpoint->authn_policies.empty()); + + for (const auto readiness : + {ccf::kv::StoreReadiness::Unavailable, + ccf::kv::StoreReadiness::InstallingSnapshot}) + { + network.tables->set_readiness(readiness); + context.node_operation->extended_state = { + NodeStartupState::readingPublicLedger, std::nullopt, std::nullopt}; + + for (const auto& [recovered, startup, expected] : std::vector< + std::tuple>{ + {25, 10, 25}, {10, 40, 40}}) + { + context.node_operation->last_recovered_signed_idx = recovered; + context.node_operation->startup_snapshot_seqno = startup; + + const auto response = + frontend_process(frontend, nullptr, "state", {}, HTTP_GET); + REQUIRE(response.status == HTTP_STATUS_OK); + CHECK_FALSE(response.headers.contains(ccf::http::headers::CCF_TX_ID)); + + const auto out = parse_response_body(response); + CHECK(out.state == NodeStartupState::readingPublicLedger); + CHECK(out.startup_seqno == startup); + CHECK(out.last_signed_seqno == expected); + } + } + + network.tables->set_readiness(ccf::kv::StoreReadiness::Ready); + context.node_operation->extended_state = { + NodeStartupState::partOfNetwork, std::nullopt, std::nullopt}; + context.node_operation->last_recovered_signed_idx = 0; + context.node_operation->startup_snapshot_seqno = 10; + + const auto response = + frontend_process(frontend, nullptr, "state", {}, HTTP_GET); + REQUIRE(response.status == HTTP_STATUS_OK); + CHECK_FALSE(response.headers.contains(ccf::http::headers::CCF_TX_ID)); + const auto out = parse_response_body(response); + CHECK(out.state == NodeStartupState::partOfNetwork); + CHECK(out.startup_seqno == 10); + CHECK(out.last_signed_seqno == kv_signed_seqno); } TEST_CASE("Pending-node cleanup uses renewed client certificates") diff --git a/src/node/rpc/test/node_stub.h b/src/node/rpc/test/node_stub.h index dd1ad0287e68..18a7eb454889 100644 --- a/src/node/rpc/test/node_stub.h +++ b/src/node/rpc/test/node_stub.h @@ -19,10 +19,13 @@ namespace ccf bool is_public = false; bool can_replicate_result = true; ccf::COSESignaturesConfig cose_signatures_config = {}; + ExtendedState extended_state = {NodeStartupState::partOfNetwork, {}, {}}; + ccf::kv::Version last_recovered_signed_idx = ccf::kv::NoVersion; + ccf::kv::Version startup_snapshot_seqno = 0; ExtendedState state() override { - return {NodeStartupState::partOfNetwork, {}, {}}; + return extended_state; } bool is_in_initialised_state() const override @@ -77,7 +80,7 @@ namespace ccf ccf::kv::Version get_last_recovered_signed_idx() override { - return ccf::kv::NoVersion; + return last_recovered_signed_idx; } SessionMetrics get_session_metrics() override @@ -99,7 +102,7 @@ namespace ccf ccf::kv::Version get_startup_snapshot_seqno() override { - return 0; + return startup_snapshot_seqno; } void initiate_private_recovery(ccf::kv::Tx& tx) override From 8cef142fae498abd7ede0b2c99a9df9e307d5cc7 Mon Sep 17 00:00:00 2001 From: amchamay Date: Mon, 30 Nov 2026 14:22:28 +0000 Subject: [PATCH 12/22] Retry CompactedVersionConflict from process_command_without_kv on readiness transition Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/node/rpc/frontend.h | 29 +++++++++-- src/node/rpc/test/node_frontend_test.cpp | 64 +++++++++++++++++++++--- src/node/rpc/test/node_stub.h | 5 ++ 3 files changed, 87 insertions(+), 11 deletions(-) diff --git a/src/node/rpc/frontend.h b/src/node/rpc/frontend.h index 58d4f6aa6533..056429c77671 100644 --- a/src/node/rpc/frontend.h +++ b/src/node/rpc/frontend.h @@ -656,7 +656,7 @@ namespace ccf } } - void process_command_without_kv( + bool process_command_without_kv( std::shared_ptr ctx, endpoints::EndpointDefinitionPtr& endpoint, size_t& attempts) @@ -676,18 +676,27 @@ namespace ccf HTTP_STATUS_SERVICE_UNAVAILABLE, ccf::errors::FrontendNotOpen, "KV store is not ready."); - return; + return true; } if (!check_uri_allowed(ctx, endpoint)) { - return; + return true; } ++attempts; endpoints::CommandEndpointContext args(ctx); endpoints.execute_command_endpoint(endpoint, args); } + catch (const ccf::kv::CompactedVersionConflict& e) + { + // A command endpoint may observe readiness transition to Ready mid-call + // and conflict with a concurrent compaction or rollback. Retry in the + // outer loop so the next attempt runs against the current readiness. + LOG_DEBUG_FMT( + "Command execution conflicted with compaction: {}", e.what()); + return false; + } catch (RpcException& e) { ctx->clear_response_headers(); @@ -713,6 +722,8 @@ namespace ccf ccf::errors::InternalError, e.what()); } + + return true; } bool check_backpressure( @@ -940,8 +951,16 @@ namespace ccf if (!tables.is_ready()) { - process_command_without_kv(ctx, endpoint, attempts); - return; + if (attempts > 0) + { + ctx->reset_response(); + } + + if (process_command_without_kv(ctx, endpoint, attempts)) + { + return; + } + continue; } // Readiness is published after these pointers. Load them only after diff --git a/src/node/rpc/test/node_frontend_test.cpp b/src/node/rpc/test/node_frontend_test.cpp index a380c2bf6db5..699f1a6fc4ac 100644 --- a/src/node/rpc/test/node_frontend_test.cpp +++ b/src/node/rpc/test/node_frontend_test.cpp @@ -807,20 +807,37 @@ TEST_CASE("Node state is explicitly nontransactional metadata") } }; + class RollbackingStore : public ccf::kv::Store + { + public: + std::function on_signature_lookup = nullptr; + + std::shared_ptr get_map( + ccf::kv::Version version, const std::string& name) override + { + if (name == Tables::SIGNATURES && on_signature_lookup != nullptr) + { + auto callback = std::exchange(on_signature_lookup, nullptr); + callback(); + } + return ccf::kv::Store::get_map(version, name); + } + }; + NetworkState network; + auto store = std::make_shared(); + network.tables = store; network.tables->set_encryptor(std::make_shared()); auto consensus = std::make_shared(); network.tables->set_consensus(consensus); + network.tables->initialise_term(2); - // Record a higher signed seqno in the KV so pre-readiness checks fail if - // they accidentally read from the store instead of node progress metadata. - constexpr ccf::kv::Version kv_signed_seqno = 99; - { + auto publish_signature = [&](ccf::kv::Version reported_seqno) { const auto txid = network.tables->next_txid(); auto tx = network.tables->create_reserved_tx(txid); tx.wo(Tables::SIGNATURES) ->put( - ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, kv_signed_seqno)); + ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, reported_seqno)); tx.wo(Tables::SERIALISED_MERKLE_TREE)->put({}); auto info = tx.commit_reserved(); REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); @@ -833,7 +850,12 @@ TEST_CASE("Node state is explicitly nontransactional metadata") std::move(info.commit_evidence_digest), std::move(info.hooks)), true) == ccf::kv::CommitResult::SUCCESS); - } + }; + + // Record a higher signed seqno in the KV so pre-readiness checks fail if + // they accidentally read from the store instead of node progress metadata. + constexpr ccf::kv::Version kv_signed_seqno = 99; + publish_signature(kv_signed_seqno); MinimalNodeState node_state; StubNodeContext context; @@ -897,6 +919,36 @@ TEST_CASE("Node state is explicitly nontransactional metadata") CHECK(out.state == NodeStartupState::partOfNetwork); CHECK(out.startup_seqno == 10); CHECK(out.last_signed_seqno == kv_signed_seqno); + + // Regression: if readiness flips to Ready after RpcFrontend enters + // process_command_without_kv(), a concurrent rollback during get_state()'s + // signature lookup throws CompactedVersionConflict (not a std::exception). + // The frontend must catch and retry it rather than terminating the node. + constexpr ccf::kv::Version post_rollback_seqno = 105; + bool transitioned_to_ready = false; + bool rollback_triggered = false; + network.tables->set_readiness(ccf::kv::StoreReadiness::Unavailable); + context.node_operation->on_state = [&]() { + transitioned_to_ready = true; + network.tables->set_readiness(ccf::kv::StoreReadiness::Ready); + context.node_operation->on_state = nullptr; + }; + store->on_signature_lookup = [&]() { + rollback_triggered = true; + network.tables->rollback({2, 0}, 3); + consensus->view_history.rollback(0); + consensus->flush(); + publish_signature(post_rollback_seqno); + }; + + const auto raced_response = + frontend_process(frontend, nullptr, "state", {}, HTTP_GET); + CHECK(transitioned_to_ready); + CHECK(rollback_triggered); + REQUIRE(raced_response.status == HTTP_STATUS_OK); + CHECK_FALSE(raced_response.headers.contains(ccf::http::headers::CCF_TX_ID)); + const auto raced_out = parse_response_body(raced_response); + CHECK(raced_out.last_signed_seqno == post_rollback_seqno); } TEST_CASE("Pending-node cleanup uses renewed client certificates") diff --git a/src/node/rpc/test/node_stub.h b/src/node/rpc/test/node_stub.h index 18a7eb454889..986b62f0f850 100644 --- a/src/node/rpc/test/node_stub.h +++ b/src/node/rpc/test/node_stub.h @@ -22,9 +22,14 @@ namespace ccf ExtendedState extended_state = {NodeStartupState::partOfNetwork, {}, {}}; ccf::kv::Version last_recovered_signed_idx = ccf::kv::NoVersion; ccf::kv::Version startup_snapshot_seqno = 0; + std::function on_state = nullptr; ExtendedState state() override { + if (on_state != nullptr) + { + on_state(); + } return extended_state; } From 1aa9ae612526901c5fd3ebc5b774289bd81da343 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Tue, 1 Dec 2026 15:45:14 +0000 Subject: [PATCH 13/22] Keep versioned migration notes in the 7.x to 8.x guide only Remove the redundant 'From CCF 8.0' notes from doc/governance/adding_member.rst and doc/operations/recovery.rst, and drop version-prefixed wording and historic constitution errata from doc/audit/read_write_restrictions.rst and doc/build_apps/kv/kv_how_to.rst. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- doc/audit/read_write_restrictions.rst | 11 +++++++---- doc/build_apps/kv/kv_how_to.rst | 7 +++++-- doc/governance/adding_member.rst | 4 ---- doc/operations/recovery.rst | 4 ---- 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/doc/audit/read_write_restrictions.rst b/doc/audit/read_write_restrictions.rst index 45fdf6eb8002..e2578e1b8af0 100644 --- a/doc/audit/read_write_restrictions.rst +++ b/doc/audit/read_write_restrictions.rst @@ -60,7 +60,8 @@ CCF ensures that governance audit is possible offline from a ledger, by consider If this table is moved, make sure the source is updated in-sync. (Ctrl+Shift+F: read_write_restrictions) -The possible access permissions are elaborated in the table below. The public internal column excludes the :ref:`signature-transaction tables ` described below. +The possible access permissions are elaborated in the table below. +The public internal column excludes the :ref:`signature-transaction tables ` described below. .. table:: KV permissions in different execution contexts :widths: auto @@ -84,12 +85,14 @@ Any violation of these restrictions (eg - calling ``set`` on a `Read-only` table Signature-Transaction Tables ---------------------------- -From CCF 8.0, the following public internal tables are inaccessible in current-KV application and governance contexts, including read-only endpoints, ballots and constitution functions, as well as in C++ and Rust transactions: +The following public internal tables are inaccessible in current-KV application and governance contexts, including read-only endpoints, ballots and constitution functions, as well as in C++ and Rust transactions: - ``public:ccf.internal.signatures`` - ``public:ccf.internal.cose_signatures`` - ``public:ccf.internal.tree`` -Other public internal tables retain the read-only permissions shown above. See :doc:`/build_apps/kv/kv_how_to` for the C++ and Rust transaction APIs. +Other public internal tables retain the read-only permissions shown above. +See :doc:`/build_apps/kv/kv_how_to` for the C++ and Rust transaction APIs. -Historical read-only access to these tables, :doc:`receipt APIs ` and :doc:`offline ledger parsing ` remain supported. For non-transactional progress metadata, use :http:GET:`/node/state`. Custom constitutions based on releases before 7.0.17 that read signatures to initialise member acknowledgement state digests must migrate to the :ref:`state-digest update and acknowledgement workflow `. \ No newline at end of file +Historical read-only access to these tables, :doc:`receipt APIs ` and :doc:`offline ledger parsing ` remain supported. +For non-transactional progress metadata, use :http:GET:`/node/state`. \ No newline at end of file diff --git a/doc/build_apps/kv/kv_how_to.rst b/doc/build_apps/kv/kv_how_to.rst index 913eae61555d..9a9c05ce1060 100644 --- a/doc/build_apps/kv/kv_how_to.rst +++ b/doc/build_apps/kv/kv_how_to.rst @@ -131,9 +131,12 @@ Note that, as in the sample above, it is possible to acquire different kinds of Signature Metadata ------------------ -From CCF 8.0, ``public:ccf.internal.signatures``, ``public:ccf.internal.cose_signatures`` and ``public:ccf.internal.tree`` are inaccessible in live transactions. ``Tx``, ``ReadOnlyTx`` and ``TxDiff`` reject all handles to these tables (``ro``, ``rw``, ``wo`` and ``diff``) with ``ccf::kv::MapAccessDenied`` in C++ and ``BridgeError::AccessDenied`` in Rust; see :ref:`audit/read_write_restrictions:Signature-Transaction Tables` for JavaScript. +``public:ccf.internal.signatures``, ``public:ccf.internal.cose_signatures`` and ``public:ccf.internal.tree`` are inaccessible in live transactions. +``Tx``, ``ReadOnlyTx`` and ``TxDiff`` reject all handles to these tables (``ro``, ``rw``, ``wo`` and ``diff``) with ``ccf::kv::MapAccessDenied`` in C++ and ``BridgeError::AccessDenied`` in Rust; see :ref:`audit/read_write_restrictions:Signature-Transaction Tables` for JavaScript. -For signature data and proofs, use :ref:`historical state ` or :doc:`receipt APIs ` instead. Historical KV views and offline ledger parsing remain supported. For node progress metadata, use :http:GET:`/node/state`, which is non-transactional and independent of any KV snapshot. +For signature data and proofs, use :ref:`historical state ` or :doc:`receipt APIs ` instead. +Historical KV views and offline ledger parsing remain supported. +For node progress metadata, use :http:GET:`/node/state`, which is non-transactional and independent of any KV snapshot. Removing a key -------------- diff --git a/doc/governance/adding_member.rst b/doc/governance/adding_member.rst index 18c0bef842bc..1eca5cdc3534 100644 --- a/doc/governance/adding_member.rst +++ b/doc/governance/adding_member.rst @@ -74,10 +74,6 @@ First, the new member should update and retrieve the latest state digest via the No state digest is recorded when a member is added. Until the member calls this ``:update`` endpoint, :http:GET:`/gov/members/state-digests/{memberId}` returns ``404 Not Found`` and the member cannot acknowledge a state digest. -.. note:: - - From CCF 8.0, ``public:ccf.internal.signatures`` and ``public:ccf.internal.cose_signatures`` are inaccessible in the current KV. Custom constitutions based on releases before 7.0.17 that read those tables when adding or resetting a member must remove those reads and rely on the ``:update`` and ``:ack`` workflow described here instead. See :ref:`audit/read_write_restrictions:Signature-Transaction Tables`. - .. code-block:: bash $ touch empty_file diff --git a/doc/operations/recovery.rst b/doc/operations/recovery.rst index 8b5f54c833bf..1db23074a0c0 100644 --- a/doc/operations/recovery.rst +++ b/doc/operations/recovery.rst @@ -40,10 +40,6 @@ To initiate the first phase of the recovery procedure, one or several nodes shou Each node will then immediately restore the public entries of its ledger (``ledger.directory`` and ``ledger.read_only_directories`` configuration entries). Because deserialising the public entries present in the ledger may take some time, operators can query the progress of the public recovery by calling :http:GET:`/node/state` which returns the version of the last signed recovered ledger entry. Once the public ledger is fully recovered, the recovered node automatically becomes part of the public network, allowing other nodes to join the network. -.. note:: - - From CCF 8.0, :http:GET:`/node/state` is non-transactional: it does not return the ``x-ms-ccf-transaction-id`` header, and ``last_signed_seqno`` reports node progress rather than a KV snapshot. The endpoint is served before the KV store is ready, including during public ledger recovery. - At startup, the host discovers the latest committed chunk end across all configured ledger directories before restoring mutable chunks. Mutable chunks whose reconstructed end is at or before this committed frontier, including incomplete chunks without an end index in their filename, are renamed with an ``.ignored`` suffix rather than reused for new appends. Chunks which overlap the committed history but extend beyond that frontier are retained. Public-ledger replay temporarily reconstructs the previous service's node entries and consensus configuration. From 96c96498a71696c6990ef224cfb52edcd1741237 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Tue, 1 Dec 2026 16:06:18 +0000 Subject: [PATCH 14/22] Remove friend class Store by aligning pinned constructor on BaseTx Move the materialised-read constructor onto BaseTx alongside the existing public BaseTx(AbstractStore*) constructor so ReadOnlyTx and TxDiff inherit it without friend declarations, keep Tx restricted to the 1-arg constructor, and switch Store::create_read_only_tx_ptr() back to std::make_unique. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- include/ccf/kv/tx.h | 21 +++++---------------- src/kv/store.h | 5 ++--- src/kv/tx.cpp | 13 +------------ 3 files changed, 8 insertions(+), 31 deletions(-) diff --git a/include/ccf/kv/tx.h b/include/ccf/kv/tx.h index 8d9f8655b94e..d625cbe3ac62 100644 --- a/include/ccf/kv/tx.h +++ b/include/ccf/kv/tx.h @@ -20,7 +20,6 @@ namespace ccf::kv class AbstractHandle; class AbstractMap; class AbstractStore; - class Store; namespace untyped { @@ -129,6 +128,10 @@ namespace ccf::kv public: BaseTx(AbstractStore* store_); + BaseTx( + AbstractStore* store_, + ccf::SeqNo read_version, + Version read_rollback_count); // To avoid accidental copies and promote use of pass-by-reference, this is // non-copyable @@ -147,13 +150,6 @@ namespace ccf::kv class TxDiff : public BaseTx { - private: - friend class Store; - TxDiff( - AbstractStore* store_, - ccf::SeqNo read_version, - Version read_rollback_count); - public: using BaseTx::BaseTx; @@ -185,13 +181,6 @@ namespace ccf::kv */ class ReadOnlyTx : public BaseTx { - private: - friend class Store; - ReadOnlyTx( - AbstractStore* store_, - ccf::SeqNo read_version, - Version read_rollback_count); - public: using BaseTx::BaseTx; @@ -236,7 +225,7 @@ namespace ccf::kv class Tx : public ReadOnlyTx { public: - using ReadOnlyTx::ReadOnlyTx; + Tx(AbstractStore* store_) : ReadOnlyTx(store_) {} /** Get a read-write handle from a map instance. * diff --git a/src/kv/store.h b/src/kv/store.h index 282e13a87844..e5e4af0829ab 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1619,9 +1619,8 @@ namespace ccf::kv { const auto [read_version, read_rollback_count] = materialised_read_state(); - // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - return std::unique_ptr( - new ReadOnlyTx(this, read_version, read_rollback_count)); + return std::make_unique( + this, read_version, read_rollback_count); } return std::make_unique(this); } diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index 4341e9a3ed4e..152a121a2957 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -202,18 +202,7 @@ namespace ccf::kv KV_TRACE(pimpl->trace_attempt.bind(store_)); } - ReadOnlyTx::ReadOnlyTx( - AbstractStore* store_, - ccf::SeqNo read_version, - Version read_rollback_count) : - BaseTx(store_) - { - pimpl->role = PrivateImpl::Role::MaterialisedReadOnly; - pimpl->read_txid = TxID(ccf::VIEW_UNKNOWN, read_version); - pimpl->read_rollback_count = read_rollback_count; - } - - TxDiff::TxDiff( + BaseTx::BaseTx( AbstractStore* store_, ccf::SeqNo read_version, Version read_rollback_count) : From 89853f4cabb50f0d57005b108e926fe41c0dac8f Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Tue, 1 Dec 2026 16:36:13 +0000 Subject: [PATCH 15/22] Throw MapAccessDenied without logging in BaseTx::check_map_access Match other exception throws in src/kv/tx.cpp and src/kv/store.h by throwing MapAccessDenied directly without logging at the throw site, and remove the now-unused internal_logger.h include. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- src/kv/tx.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index 152a121a2957..f124bce8a353 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -4,7 +4,6 @@ #include "ccf/kv/tx.h" #include "ds/ccf_assert.h" -#include "ds/internal_logger.h" #include "kv/compacted_version_conflict.h" #include "kv/internal_table_names.h" #include "kv/kv_types.h" @@ -69,13 +68,8 @@ namespace ccf::kv if (reason != nullptr) { - // Denials are reported to the caller through the exception. Logging at - // a quieter level avoids a FAIL line per request from a probing or - // misbehaving application. - const auto message = - std::format("Access to map '{}' denied: {}", map_name, reason); - LOG_DEBUG_FMT("{}", message); - throw MapAccessDenied(message); + throw MapAccessDenied( + std::format("Access to map '{}' denied: {}", map_name, reason)); } } From 0fd3b691a58f5d7f282c59b06c73999505eca983 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Tue, 1 Dec 2026 16:39:39 +0000 Subject: [PATCH 16/22] Check baseline signature survives at seqno 3 after rollback After B replicates at seqno 3, assert read_signature_seqno(*fixture.store) is still 2 so a stale seqno-3 signature from A left in materialised KV state would be detected. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- src/consensus/aft/test/view_straddling_rollback.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/consensus/aft/test/view_straddling_rollback.cpp b/src/consensus/aft/test/view_straddling_rollback.cpp index ab90318b248d..85a1c0fd30bb 100644 --- a/src/consensus/aft/test/view_straddling_rollback.cpp +++ b/src/consensus/aft/test/view_straddling_rollback.cpp @@ -123,6 +123,7 @@ TEST_CASE( CHECK(fixture.cft->ledger->ledger.size() == 3); CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); CHECK(read_value(*fixture.store, fixture.table, 2) == 3); + CHECK(read_signature_seqno(*fixture.store) == 2); INFO("The next transaction gets a fresh seqno and replicates normally"); auto next_tx = fixture.store->create_tx(); From 0e22c34dde3a52414d2492e9ce5bfd67166a591b Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Tue, 1 Dec 2026 17:41:46 +0000 Subject: [PATCH 17/22] Capture materialised read state inside BaseTx tag constructor Expose materialised_read_state() on AbstractStore and replace the 3-argument BaseTx(AbstractStore*, SeqNo, Version) constructor with a BaseTx(AbstractStore*, MaterialisedReadOnlyTag) overload that always captures (read_version, read_rollback_count) atomically from the store, so no caller can supply an arbitrary version or rollback count and no friend declarations are needed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- include/ccf/kv/tx.h | 9 ++++----- src/kv/kv_types.h | 1 + src/kv/store.h | 17 +++++------------ src/kv/tx.cpp | 7 +++---- 4 files changed, 13 insertions(+), 21 deletions(-) diff --git a/include/ccf/kv/tx.h b/include/ccf/kv/tx.h index d625cbe3ac62..868faf4530fe 100644 --- a/include/ccf/kv/tx.h +++ b/include/ccf/kv/tx.h @@ -5,7 +5,6 @@ #include "ccf/crypto/sha256_hash.h" #include "ccf/kv/abstract_handle.h" #include "ccf/kv/map_access.h" -#include "ccf/kv/version.h" #include "ccf/tx_id.h" #include @@ -127,11 +126,11 @@ namespace ccf::kv } public: + struct MaterialisedReadOnlyTag + {}; + BaseTx(AbstractStore* store_); - BaseTx( - AbstractStore* store_, - ccf::SeqNo read_version, - Version read_rollback_count); + BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag); // To avoid accidental copies and promote use of pass-by-reference, this is // non-copyable diff --git a/src/kv/kv_types.h b/src/kv/kv_types.h index 1b0e64560972..9e305c212673 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -839,6 +839,7 @@ namespace ccf::kv virtual Version current_version() = 0; virtual ccf::TxID current_txid() = 0; virtual std::pair current_txid_and_commit_term() = 0; + virtual std::pair materialised_read_state() = 0; virtual Version compacted_version() = 0; virtual Term commit_view() = 0; diff --git a/src/kv/store.h b/src/kv/store.h index e5e4af0829ab..0e38e4f4e74a 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1593,8 +1593,8 @@ namespace ccf::kv } } - private: - std::pair materialised_read_state() + public: + std::pair materialised_read_state() override { std::lock_guard vguard(version_lock); // Consensus may compact synchronously in replicate(), before @@ -1603,7 +1603,6 @@ namespace ccf::kv std::max(last_replicated, compacted.load()), rollback_count.load()}; } - public: ReadOnlyTx create_read_only_tx() override { if (is_historical) @@ -1617,10 +1616,8 @@ namespace ccf::kv { if (is_historical) { - const auto [read_version, read_rollback_count] = - materialised_read_state(); return std::make_unique( - this, read_version, read_rollback_count); + this, BaseTx::MaterialisedReadOnlyTag{}); } return std::make_unique(this); } @@ -1629,18 +1626,14 @@ namespace ccf::kv { if (is_historical) { - const auto [read_version, read_rollback_count] = - materialised_read_state(); - return {this, read_version, read_rollback_count}; + return {this, BaseTx::MaterialisedReadOnlyTag{}}; } return {this}; } ReadOnlyTx create_read_only_tx_at_replicated_state() { - const auto [read_version, read_rollback_count] = - materialised_read_state(); - return {this, read_version, read_rollback_count}; + return {this, BaseTx::MaterialisedReadOnlyTag{}}; } CommittableTx create_tx() diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index f124bce8a353..1ec55cffdba9 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -196,12 +196,11 @@ namespace ccf::kv KV_TRACE(pimpl->trace_attempt.bind(store_)); } - BaseTx::BaseTx( - AbstractStore* store_, - ccf::SeqNo read_version, - Version read_rollback_count) : + BaseTx::BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag) : BaseTx(store_) { + const auto [read_version, read_rollback_count] = + pimpl->store->materialised_read_state(); pimpl->role = PrivateImpl::Role::MaterialisedReadOnly; pimpl->read_txid = TxID(ccf::VIEW_UNKNOWN, read_version); pimpl->read_rollback_count = read_rollback_count; From 0e84e2ad6ee4b2d110aa87965a3e8b64e689dd20 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Tue, 1 Dec 2026 19:15:13 +0000 Subject: [PATCH 18/22] Name unused MaterialisedReadOnlyTag parameter for clang-tidy Satisfy clang-tidy's readability-named-parameter check on the BaseTx(AbstractStore*, MaterialisedReadOnlyTag) declaration and definition. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- include/ccf/kv/tx.h | 2 +- src/kv/tx.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/include/ccf/kv/tx.h b/include/ccf/kv/tx.h index 868faf4530fe..adcd889e5dda 100644 --- a/include/ccf/kv/tx.h +++ b/include/ccf/kv/tx.h @@ -130,7 +130,7 @@ namespace ccf::kv {}; BaseTx(AbstractStore* store_); - BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag); + BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag /*tag*/); // To avoid accidental copies and promote use of pass-by-reference, this is // non-copyable diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index 1ec55cffdba9..d194145a2b23 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -196,7 +196,7 @@ namespace ccf::kv KV_TRACE(pimpl->trace_attempt.bind(store_)); } - BaseTx::BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag) : + BaseTx::BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag /*tag*/) : BaseTx(store_) { const auto [read_version, read_rollback_count] = From 45678694ca83fedff96daba06f0efab921211bea Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Tue, 1 Dec 2026 20:43:43 +0000 Subject: [PATCH 19/22] Remove redundant public access specifier in Store Satisfy clang-tidy's readability-redundant-access-specifiers check on src/kv/store.h after making materialised_read_state() public. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 61f0875e745e42518effc6023504da6e --- src/kv/store.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/kv/store.h b/src/kv/store.h index 0e38e4f4e74a..c7f17211a719 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1593,7 +1593,6 @@ namespace ccf::kv } } - public: std::pair materialised_read_state() override { std::lock_guard vguard(version_lock); From b3bc7d837eab57d7d19a868c247a136dcd6319c2 Mon Sep 17 00:00:00 2001 From: amchamay Date: Wed, 2 Dec 2026 11:20:10 +0000 Subject: [PATCH 20/22] Clarify Rust vs C++ signature-table access denial in KV docs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/build_apps/kv/kv_how_to.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/build_apps/kv/kv_how_to.rst b/doc/build_apps/kv/kv_how_to.rst index 9a9c05ce1060..785692e265f2 100644 --- a/doc/build_apps/kv/kv_how_to.rst +++ b/doc/build_apps/kv/kv_how_to.rst @@ -132,7 +132,8 @@ Signature Metadata ------------------ ``public:ccf.internal.signatures``, ``public:ccf.internal.cose_signatures`` and ``public:ccf.internal.tree`` are inaccessible in live transactions. -``Tx``, ``ReadOnlyTx`` and ``TxDiff`` reject all handles to these tables (``ro``, ``rw``, ``wo`` and ``diff``) with ``ccf::kv::MapAccessDenied`` in C++ and ``BridgeError::AccessDenied`` in Rust; see :ref:`audit/read_write_restrictions:Signature-Transaction Tables` for JavaScript. +In C++, ``Tx``, ``ReadOnlyTx`` and ``TxDiff`` throw ``ccf::kv::MapAccessDenied`` when acquiring any handle to these tables (``ro``, ``rw``, ``wo`` and ``diff``). +In Rust, map operations on these tables return ``BridgeError::AccessDenied``; see :ref:`audit/read_write_restrictions:Signature-Transaction Tables` for JavaScript. For signature data and proofs, use :ref:`historical state ` or :doc:`receipt APIs ` instead. Historical KV views and offline ledger parsing remain supported. From 5e91d57f7ff6e2bc067fdcde4a771aa1c5e82e1d Mon Sep 17 00:00:00 2001 From: amchamay Date: Thu, 3 Dec 2026 13:48:05 +0000 Subject: [PATCH 21/22] Make MapAccessDenied a private non-std::exception handled by RpcFrontend Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/build_apps/kv/kv_how_to.rst | 4 +- include/ccf/kv/map_access.h | 14 ------- include/ccf/kv/tx.h | 1 - src/kv/committable_tx.h | 1 + src/kv/map_access_denied.h | 23 ++++++++++++ src/kv/test/kv_test.cpp | 20 +++++++--- src/kv/tx.cpp | 1 + src/node/rpc/frontend.h | 19 ++++++++++ src/node/rpc/test/frontend_test.cpp | 58 +++++++++++++++++++++++++++++ src/rust/app_bridge.cpp | 2 +- 10 files changed, 120 insertions(+), 23 deletions(-) delete mode 100644 include/ccf/kv/map_access.h create mode 100644 src/kv/map_access_denied.h diff --git a/doc/build_apps/kv/kv_how_to.rst b/doc/build_apps/kv/kv_how_to.rst index 785692e265f2..2b18a7279482 100644 --- a/doc/build_apps/kv/kv_how_to.rst +++ b/doc/build_apps/kv/kv_how_to.rst @@ -132,12 +132,12 @@ Signature Metadata ------------------ ``public:ccf.internal.signatures``, ``public:ccf.internal.cose_signatures`` and ``public:ccf.internal.tree`` are inaccessible in live transactions. -In C++, ``Tx``, ``ReadOnlyTx`` and ``TxDiff`` throw ``ccf::kv::MapAccessDenied`` when acquiring any handle to these tables (``ro``, ``rw``, ``wo`` and ``diff``). +In C++, acquiring any handle to these tables through ``Tx``, ``ReadOnlyTx`` or ``TxDiff`` (``ro``, ``rw``, ``wo`` or ``diff``) fails the request with an internal framework error. In Rust, map operations on these tables return ``BridgeError::AccessDenied``; see :ref:`audit/read_write_restrictions:Signature-Transaction Tables` for JavaScript. For signature data and proofs, use :ref:`historical state ` or :doc:`receipt APIs ` instead. Historical KV views and offline ledger parsing remain supported. -For node progress metadata, use :http:GET:`/node/state`, which is non-transactional and independent of any KV snapshot. +For node progress metadata, use :http:GET:`/node/state`, which is non-transactional: when the KV store is ready it reads ``last_signed_seqno`` from a pinned replicated view rather than the caller's transaction snapshot, and before readiness it falls back to recovery and startup progress. Removing a key -------------- diff --git a/include/ccf/kv/map_access.h b/include/ccf/kv/map_access.h deleted file mode 100644 index 3f60d75c4876..000000000000 --- a/include/ccf/kv/map_access.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the Apache 2.0 License. -#pragma once - -#include - -namespace ccf::kv -{ - class MapAccessDenied : public std::logic_error - { - public: - using std::logic_error::logic_error; - }; -} diff --git a/include/ccf/kv/tx.h b/include/ccf/kv/tx.h index adcd889e5dda..94930ae22f22 100644 --- a/include/ccf/kv/tx.h +++ b/include/ccf/kv/tx.h @@ -4,7 +4,6 @@ #include "ccf/crypto/sha256_hash.h" #include "ccf/kv/abstract_handle.h" -#include "ccf/kv/map_access.h" #include "ccf/tx_id.h" #include diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 4261044f3827..6f3ac59aecb7 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -6,6 +6,7 @@ #include "ccf/ds/hex.h" #include "ccf/kv/tx.h" #include "ds/internal_logger.h" +#include "kv/map_access_denied.h" #include "kv/tx_pimpl.h" #include "kv_serialiser.h" #include "kv_types.h" diff --git a/src/kv/map_access_denied.h b/src/kv/map_access_denied.h new file mode 100644 index 000000000000..97dad4a79864 --- /dev/null +++ b/src/kv/map_access_denied.h @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the Apache 2.0 License. +#pragma once + +#include +#include + +namespace ccf::kv +{ + class MapAccessDenied + { + private: + std::string msg; + + public: + explicit MapAccessDenied(std::string s) : msg(std::move(s)) {} + + [[nodiscard]] char const* what() const + { + return msg.c_str(); + } + }; +} diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index c5d4a8d3673e..2e5ed52e9ec1 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -13,6 +13,7 @@ #include "kv/compacted_version_conflict.h" #include "kv/kv_serialiser.h" #include "kv/ledger_chunker.h" +#include "kv/map_access_denied.h" #include "kv/null_encryptor.h" #include "kv/store.h" #include "kv/test/null_tx_history.h" @@ -4492,11 +4493,20 @@ TEST_CASE("CommittableTx guards") auto* handle = reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); REQUIRE(handle->get(ccf::SerialisedMerkleTree::create_unit()).has_value()); - REQUIRE_THROWS_WITH_AS( - reserved.commit_reserved(), - "Reserved transaction cannot depend on reads from map " - "'public:ccf.internal.tree'", - ccf::kv::MapAccessDenied); + bool denied = false; + try + { + reserved.commit_reserved(); + } + catch (const ccf::kv::MapAccessDenied& e) + { + denied = true; + CHECK( + std::string_view(e.what()) == + "Reserved transaction cannot depend on reads from map " + "'public:ccf.internal.tree'"); + } + REQUIRE(denied); REQUIRE_THROWS_WITH_AS( auto _ = reserved.commit_version(), "Transaction not yet committed", diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index d194145a2b23..7bf5a60eecc4 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -7,6 +7,7 @@ #include "kv/compacted_version_conflict.h" #include "kv/internal_table_names.h" #include "kv/kv_types.h" +#include "kv/map_access_denied.h" #include "kv/tx_pimpl.h" #include "kv/untyped_map.h" diff --git a/src/node/rpc/frontend.h b/src/node/rpc/frontend.h index cbec38040a23..bc5a15e750fe 100644 --- a/src/node/rpc/frontend.h +++ b/src/node/rpc/frontend.h @@ -16,6 +16,7 @@ #include "forwarder.h" #include "http/http_jwt.h" #include "kv/compacted_version_conflict.h" +#include "kv/map_access_denied.h" #include "kv/store.h" #include "node/endpoint_context_impl.h" #include "node/internal_tables_access.h" @@ -697,6 +698,14 @@ namespace ccf "Command execution conflicted with compaction: {}", e.what()); return false; } + catch (const ccf::kv::MapAccessDenied& e) + { + ctx->clear_response_headers(); + ctx->set_error( + HTTP_STATUS_INTERNAL_SERVER_ERROR, + ccf::errors::InternalError, + e.what()); + } catch (RpcException& e) { ctx->clear_response_headers(); @@ -1075,6 +1084,16 @@ namespace ccf "Transaction execution conflicted with compaction: {}", e.what()); continue; } + catch (const ccf::kv::MapAccessDenied& e) + { + ctx->clear_response_headers(); + ctx->set_error( + HTTP_STATUS_INTERNAL_SERVER_ERROR, + ccf::errors::InternalError, + e.what()); + + return; + } catch (RpcException& e) { ctx->clear_response_headers(); diff --git a/src/node/rpc/test/frontend_test.cpp b/src/node/rpc/test/frontend_test.cpp index 550b4463a238..232932a399b3 100644 --- a/src/node/rpc/test/frontend_test.cpp +++ b/src/node/rpc/test/frontend_test.cpp @@ -2141,6 +2141,64 @@ TEST_CASE("Retry endpoint lookup on compaction conflict") } } +TEST_CASE("MapAccessDenied bypasses std::exception and fails without retrying") +{ + class SignatureProbingRegistry : public ccf::UserEndpointRegistry + { + public: + size_t executions = 0; + bool caught_std_exception = false; + + explicit SignatureProbingRegistry(ccf::AbstractNodeContext& context) : + ccf::UserEndpointRegistry(context) + {} + + void init_handlers() override + { + ccf::UserEndpointRegistry::init_handlers(); + + make_read_only_endpoint( + "/probe_signature", + HTTP_GET, + [this](auto& ctx) { + ++executions; + try + { + (void)ctx.tx.template ro(ccf::Tables::SIGNATURES); + } + catch (const std::exception&) + { + caught_std_exception = true; + ctx.rpc_ctx->set_response_status(HTTP_STATUS_OK); + } + }, + no_auth_required) + .install(); + } + }; + + NetworkState network; + prepare_callers(network); + ccf::StubNodeContext context; + SignatureProbingRegistry registry(context); + RpcFrontend frontend(*network.tables, registry, context); + frontend.open(); + + auto rpc_ctx = ccf::make_rpc_context( + anonymous_session, + ::http::Request("/probe_signature", HTTP_GET).build_request()); + frontend.process(rpc_ctx); + CHECK_FALSE(rpc_ctx->response_is_pending); + CHECK_FALSE(registry.caught_std_exception); + CHECK(registry.executions == 1); + + const auto response = parse_response(rpc_ctx->serialise_response()); + CHECK(response.status == HTTP_STATUS_INTERNAL_SERVER_ERROR); + CHECK( + parse_response_body(response)["error"]["code"] == + ccf::errors::InternalError); +} + class TestCommitHistory : public ccf::NullTxHistory { public: diff --git a/src/rust/app_bridge.cpp b/src/rust/app_bridge.cpp index 3f67982cebee..6e31ee5ae45b 100644 --- a/src/rust/app_bridge.cpp +++ b/src/rust/app_bridge.cpp @@ -5,10 +5,10 @@ #include "ccf/endpoints/common_auth_policies.h" #include "ccf/http_status.h" #include "ccf/kv/map.h" -#include "ccf/kv/map_access.h" #include "ccf/odata_error.h" #include "ccf/rust_ffi.h" #include "kv/compacted_version_conflict.h" +#include "kv/map_access_denied.h" #include #include From 49eeea3a8129427cbfd3675fb153fdfec6fcd022 Mon Sep 17 00:00:00 2001 From: amchamay Date: Thu, 3 Dec 2026 14:10:32 +0000 Subject: [PATCH 22/22] Deduplicate retry response reset in RpcFrontend::process_command_inner Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/node/rpc/frontend.h | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/node/rpc/frontend.h b/src/node/rpc/frontend.h index bc5a15e750fe..7f7737c4bb35 100644 --- a/src/node/rpc/frontend.h +++ b/src/node/rpc/frontend.h @@ -958,13 +958,15 @@ namespace ccf return; } - if (!tables.is_ready()) + if (attempts > 0) { - if (attempts > 0) - { - ctx->reset_response(); - } + // If the endpoint has already been executed, the effects of its + // execution should be dropped + ctx->reset_response(); + } + if (!tables.is_ready()) + { if (process_command_without_kv(ctx, endpoint, attempts)) { return; @@ -985,13 +987,6 @@ namespace ccf std::unique_ptr tx_p = tables.create_tx_ptr(); set_root_on_proposals(*ctx, *tx_p, current_history); - if (attempts > 0) - { - // If the endpoint has already been executed, the effects of its - // execution should be dropped - ctx->reset_response(); - } - ++attempts; try