diff --git a/.changes/live-signature-table-access.removed.md b/.changes/live-signature-table-access.removed.md new file mode 100644 index 000000000000..b300fdbf2789 --- /dev/null +++ b/.changes/live-signature-table-access.removed.md @@ -0,0 +1,2 @@ +Live KV access to `public:ccf.internal.signatures`, `public:ccf.internal.cose_signatures` and `public:ccf.internal.tree` has been removed across C++, Rust and JavaScript contexts, and `GET /node/state` is now non-transactional without `x-ms-ccf-transaction-id` while remaining available during recovery. +See the [7.x to 8.x migration guide](doc/releases/migration_7_x_to_8_x.rst#signature-transaction-tables). diff --git a/doc/audit/read_write_restrictions.rst b/doc/audit/read_write_restrictions.rst index 965360eed8fe..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 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 +80,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 +---------------------------- + +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. + +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 af844210a5aa..2b18a7279482 100644 --- a/doc/build_apps/kv/kv_how_to.rst +++ b/doc/build_apps/kv/kv_how_to.rst @@ -128,6 +128,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 +------------------ + +``public:ccf.internal.signatures``, ``public:ccf.internal.cose_signatures`` and ``public:ccf.internal.tree`` are inaccessible in live transactions. +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: 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/doc/releases/migration_7_x_to_8_x.rst b/doc/releases/migration_7_x_to_8_x.rst index b61a276774dc..9bba453f6906 100644 --- a/doc/releases/migration_7_x_to_8_x.rst +++ b/doc/releases/migration_7_x_to_8_x.rst @@ -171,3 +171,12 @@ Nodes that join a service never create one. - Each transaction signed by a service with an ML-DSA identity also has an ML-DSA COSE receipt, returned by ``GET /node/receipt/cose`` with ``identity_type=PQ``, which is trusted across recoveries through the chain of ML-DSA endorsements (see :ref:`use_apps/verify_tx:COSE Receipt Verification`). Without ``identity_type`` the endpoint returns the classical receipt, but this default may change in a future release. Clients should set ``identity_type=CLASSICAL`` or ``identity_type=PQ`` explicitly. + +Signature-Transaction Tables +---------------------------- + +From CCF 8.0, ``public:ccf.internal.signatures``, ``public:ccf.internal.cose_signatures`` and ``public:ccf.internal.tree`` are inaccessible in live transactions across C++, Rust and JavaScript application and governance contexts. +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 before the KV store is ready, including during public ledger recovery. diff --git a/include/ccf/kv/tx.h b/include/ccf/kv/tx.h index 6adcea17bc46..94930ae22f22 100644 --- a/include/ccf/kv/tx.h +++ b/include/ccf/kv/tx.h @@ -6,6 +6,7 @@ #include "ccf/kv/abstract_handle.h" #include "ccf/tx_id.h" +#include #include #include #include @@ -46,6 +47,14 @@ namespace ccf::kv class BaseTx { protected: + enum class AccessMode : std::uint8_t + { + ReadOnly, + ReadWrite, + WriteOnly, + Diff + }; + struct PrivateImpl; std::unique_ptr pimpl; @@ -68,10 +77,16 @@ namespace ccf::kv 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) { @@ -110,7 +125,11 @@ namespace ccf::kv } public: + struct MaterialisedReadOnlyTag + {}; + BaseTx(AbstractStore* store_); + BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag /*tag*/); // To avoid accidental copies and promote use of pass-by-reference, this is // non-copyable @@ -135,7 +154,8 @@ namespace ccf::kv 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 @@ -146,7 +166,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); } }; @@ -171,7 +192,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 @@ -182,7 +204,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); } }; @@ -200,7 +223,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. * @@ -211,7 +234,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 @@ -222,7 +246,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. @@ -234,7 +259,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 @@ -245,7 +271,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/include/ccf/rust_ffi.h b/include/ccf/rust_ffi.h index fc97d01ae1a6..5672d16b14d5 100644 --- a/include/ccf/rust_ffi.h +++ b/include/ccf/rust_ffi.h @@ -44,6 +44,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; @@ -54,7 +55,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/samples/apps/basic_rust/src/lib.rs b/samples/apps/basic_rust/src/lib.rs index a84b81b00ec8..05da6f584e08 100644 --- a/samples/apps/basic_rust/src/lib.rs +++ b/samples/apps/basic_rust/src/lib.rs @@ -52,6 +52,30 @@ fn register(registry: &mut Registry) -> Result<(), BridgeError> { )?; // SNIPPET_END: rust_get_record + registry.read_write( + "/signature-table-access", + "POST", + Auth::None, + |context| -> EndpointResult { + 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}" + ))); + } + } + context.set_status(200)?; + context.set_body(b"denied")?; + Ok(()) + }, + )?; + 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/main.cpp b/src/consensus/aft/test/main.cpp index 4a51e65ca4de..7ad54e2dfaae 100644 --- a/src/consensus/aft/test/main.cpp +++ b/src/consensus/aft/test/main.cpp @@ -2,6 +2,7 @@ // Licensed under the Apache 2.0 License. #include "kv/store.h" +#include "kv/test/stub_consensus.h" #include "node/commit_callback_subsystem.h" #include "service/tables/signatures.h" #include "test_common.h" @@ -3444,6 +3445,8 @@ DOCTEST_TEST_CASE( ccf::Tables::SERIALISED_MERKLE_TREE}; ccf::kv::Store sender_store; + std::shared_ptr sender_consensus = + std::make_shared(); std::shared_ptr follower_store = std::make_shared(); std::shared_ptr follower_channels = @@ -3465,6 +3468,7 @@ DOCTEST_TEST_CASE( { auto encryptor = std::make_shared(); sender_store.set_encryptor(encryptor); + sender_store.set_consensus(sender_consensus); sender_store.initialise_term(1); follower_store->set_encryptor(encryptor); @@ -3494,12 +3498,23 @@ DOCTEST_TEST_CASE( { const auto txid = sender_store.next_txid(); auto tx = sender_store.create_reserved_tx(txid); - tx.rw(signatures)->put(ccf::PrimarySignature(primary_id, txid.seqno)); - tx.rw(serialised_tree)->put({}); + tx.wo(signatures)->put(ccf::PrimarySignature(primary_id, txid.seqno)); + tx.wo(serialised_tree)->put({}); auto [rc, data, claims_digest, commit_evidence_digest, tx_hooks] = tx.commit_reserved(); DOCTEST_REQUIRE(rc == ccf::kv::CommitResult::SUCCESS); - raw_entries.push_back(std::move(data)); + DOCTEST_REQUIRE( + sender_store.commit( + txid, + std::make_unique( + std::move(data), + std::move(claims_digest), + std::move(commit_evidence_digest), + std::move(tx_hooks)), + true) == ccf::kv::CommitResult::SUCCESS); + const auto replicated = sender_consensus->get_latest_data(); + DOCTEST_REQUIRE(replicated.has_value()); + raw_entries.push_back(*replicated); return txid.seqno; } @@ -3508,18 +3523,17 @@ DOCTEST_TEST_CASE( size_t value, const std::optional& new_config = std::nullopt) { - const auto txid = sender_store.next_txid(); - auto tx = sender_store.create_reserved_tx(txid); + auto tx = sender_store.create_tx(); tx.rw(values)->put(key, value); if (new_config.has_value()) { tx.rw(configs)->put(0, *new_config); } - auto [rc, data, claims_digest, commit_evidence_digest, tx_hooks] = - tx.commit_reserved(); - DOCTEST_REQUIRE(rc == ccf::kv::CommitResult::SUCCESS); - raw_entries.push_back(std::move(data)); - return txid.seqno; + DOCTEST_REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto replicated = sender_consensus->get_latest_data(); + DOCTEST_REQUIRE(replicated.has_value()); + raw_entries.push_back(*replicated); + return tx.commit_version(); } void deliver( diff --git a/src/consensus/aft/test/view_straddling_common.h b/src/consensus/aft/test/view_straddling_common.h index d424495e34cb..8b4e647a4ddd 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 Cft = 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 cft->force_become_primary(); initial_view = cft->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(cft->get_committed_seqno() == 1); - REQUIRE(cft->ledger->ledger.size() == 1); + REQUIRE(store->current_txid() == ccf::TxID(initial_view, 2)); + REQUIRE(cft->get_committed_seqno() == 2); + REQUIRE(cft->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() { cft->become_aware_of_new_term(cft->get_view() + 1); diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index c6913724ff93..60c35474bb9e 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 CFT 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.cft->get_last_idx() == 1); - CHECK(fixture.cft->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.cft->get_last_idx() == 2); + CHECK(fixture.cft->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 4a903058fb43..85a1c0fd30bb 100644 --- a/src/consensus/aft/test/view_straddling_rollback.cpp +++ b/src/consensus/aft/test/view_straddling_rollback.cpp @@ -15,15 +15,15 @@ // Interleaving, from review of PR #8209 (cjen1-msft, // src/consensus/aft/cft.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 CFT. // - 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. CFT rejects it. If that rejection rolls the Store -// back to CFT's last log index (1), it discards B's local application as +// back to CFT's last log index (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. @@ -57,16 +57,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; @@ -80,14 +76,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.cft->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.cft->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); @@ -99,8 +96,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( @@ -111,9 +108,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.cft->get_last_idx() == 1); - CHECK(fixture.cft->ledger->ledger.size() == 1); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); + CHECK(fixture.cft->get_last_idx() == 2); + CHECK(fixture.cft->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"); @@ -122,10 +119,11 @@ TEST_CASE( REQUIRE(current_result.has_value()); CHECK(current_result.value() == ccf::kv::CommitResult::SUCCESS); MESSAGE("After B is replicated: " << describe(fixture)); - CHECK(fixture.cft->get_last_idx() == 2); - CHECK(fixture.cft->ledger->ledger.size() == 2); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); + CHECK(fixture.cft->get_last_idx() == 3); + 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(); @@ -136,9 +134,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.cft->get_last_idx() == 3); - CHECK(fixture.cft->ledger->ledger.size() == 3); + CHECK(fixture.cft->get_last_idx() == 4); + CHECK(fixture.cft->ledger->ledger.size() == 4); } diff --git a/src/js/extensions/ccf/historical.cpp b/src/js/extensions/ccf/historical.cpp index 1682289b6b79..8fe771bfcddb 100644 --- a/src/js/extensions/ccf/historical.cpp +++ b/src/js/extensions/ccf/historical.cpp @@ -338,12 +338,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 942b92bbb6fb..eaf5bba7bcc7 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 4ed481fcc18f..5eaa1f0e0b6b 100644 --- a/src/js/permissions_checks.h +++ b/src/js/permissions_checks.h @@ -5,6 +5,8 @@ #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" #include @@ -12,7 +14,10 @@ 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 @@ -52,6 +57,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 1ac1a7965a2a..98a272914f8b 100644 --- a/src/js/test/js.cpp +++ b/src/js/test/js.cpp @@ -27,6 +27,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" #include @@ -533,6 +534,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( @@ -599,10 +638,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 = std::format("export function run() {{\n{}\n}}", body); auto func = ctx.get_exported_function(module, "run", "/test/kv_script"); @@ -2924,6 +2967,8 @@ namespace public: size_t tx_creations = 0; + CountingStore() : ccf::kv::Store(true) {} + std::unique_ptr create_read_only_tx_ptr() override { ++tx_creations; @@ -2941,6 +2986,245 @@ 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( +for (const table of signatureTables) { + const handle = ccf.kv[table]; + for (const [, operation] of [ + ...readOperations(handle), ...writeOperations(handle) + ]) { + expectTypeError(() => operation(handle), table, "inaccessible"); + } +} +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 [, operation] of readOperations(handle)) { + operation(handle); + } + for (const [, 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 = std::format( + "const populated = {};\nconst restricted = {};\n", + populated, + restricted) + + signature_table_test_prelude + R"JS( +export function run() { + 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 [, operation] of writeOperations(handle)) { + expectTypeError(() => operation(handle), table, "read-only"); + } + } +} +)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 97eb1a2c9fae..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" @@ -197,6 +198,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"); @@ -530,6 +537,7 @@ namespace ccf::kv rollback_count(rollback_count_) { version = reserved_tx_id.seqno; + pimpl->role = PrivateImpl::Role::Reserved; KV_TRACE(trace::unsupported(pimpl->store, "reserved transaction")); pimpl->commit_view = reserved_tx_id.view; pimpl->read_txid = TxID(read_term, reserved_tx_id.seqno - 1); @@ -543,6 +551,21 @@ namespace ccf::kv throw std::logic_error("Transaction already committed"); } + for (const auto& [map_name, changes] : all_changes) + { + if ( + changes.changeset->read_version.has_value() || + changes.changeset->read_globally_committed || + !changes.changeset->reads.empty()) + { + const auto message = std::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..1e9b470557fd 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 +{ + 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/kv_types.h b/src/kv/kv_types.h index e88bc7e40065..1e2accbebb07 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -854,6 +854,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/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/store.h b/src/kv/store.h index 51e2873c5236..c7f17211a719 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,21 +1593,48 @@ namespace ccf::kv } } + std::pair materialised_read_state() override + { + 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()}; + } + 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) + { + return std::make_unique( + this, BaseTx::MaterialisedReadOnlyTag{}); + } return std::make_unique(this); } TxDiff create_tx_diff() override { + if (is_historical) + { + return {this, BaseTx::MaterialisedReadOnlyTag{}}; + } return {this}; } + ReadOnlyTx create_read_only_tx_at_replicated_state() + { + return {this, BaseTx::MaterialisedReadOnlyTag{}}; + } + CommittableTx create_tx() { return {this}; @@ -1620,7 +1648,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( diff --git a/src/kv/test/kv_contention.cpp b/src/kv/test/kv_contention.cpp index 7ae932672eb8..86d2e9905673 100644 --- a/src/kv/test/kv_contention.cpp +++ b/src/kv/test/kv_contention.cpp @@ -387,11 +387,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 e3009c082ca5..bfe0b9f61940 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" @@ -719,9 +720,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(); @@ -1248,6 +1250,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"); @@ -1264,19 +1268,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 b808e3a721b3..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" @@ -43,6 +44,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; @@ -69,6 +101,448 @@ 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()); + 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}) + { + CHECK(store.get_map(store.current_version(), name) == nullptr); + } + CHECK(store.current_version() == 0); + + 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 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(); + + 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(); + REQUIRE(read.ro(map)->get("key") == "value"); + auto diff = store.create_tx_diff(); + REQUIRE(diff.diff(map)->size() == 1); + } +} + +TEST_CASE("Historical signature entries remain readable") +{ + ccf::kv::Store source; + source.set_encryptor(std::make_shared()); + const auto txid = source.next_txid(); + auto info = make_signature_entry(source, txid, 42); + 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{42}); + + auto ptr = historical.create_read_only_tx_ptr(); + 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)); + REQUIRE(ptr->ro(name)->size() == 1); + REQUIRE(diff.diff(name)->size() == 1); + + auto ordinary = historical.create_tx(); + CHECK_THROWS_AS( + ordinary.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + ordinary.wo(name), ccf::kv::MapAccessDenied); + } +} + +TEST_CASE("Reserved transactions are write-only on signature tables") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + store.set_consensus(std::make_shared()); + + INFO("Cannot access non-signature maps or upgrade signature handles"); + { + 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(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("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); + } + } + + INFO("Clear on an empty signature table records a read and is rejected"); + { + 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); + } + + 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); + 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()); + 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 == "foreach") + { + handle->foreach([](const auto&, const auto&) { return true; }); + } + 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); + } +} + +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}); + } + + 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 rollback and see replication compaction") +{ + 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 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(signatures)->get()->seqno == initial_signature.seqno); + auto diff = store.create_tx_diff(); + if (is_historical) + { + 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.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); + 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}); + } + } + + SUBCASE("Rollback during snapshot acquisition is detected") + { + 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 = std::exchange(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); + store.initialise_term(2); + ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); + 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(); + + 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); + }; + + CHECK_THROWS_AS(old.ro(cose_signatures), ccf::kv::CompactedVersionConflict); + REQUIRE(store.replacement_triggered); + } + + SUBCASE("Prefix compacted synchronously inside replication is visible") + { + class CompactingConsensus : public ccf::kv::test::PrimaryStubConsensus + { + ccf::kv::Store& store; + + public: + 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); + store.compact(std::get<0>(entries.back())); + auto read = store.create_read_only_tx_at_replicated_state(); + if (auto sig = read.ro(ccf::Tables::SIGNATURES)->get()) + { + observed_signature = sig->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(); + REQUIRE( + publish_signature_entry(store, txid, 1) == + ccf::kv::CommitResult::SUCCESS); + REQUIRE(consensus->observed_signature == txid.seqno); + } +} + TEST_CASE("Zero-revision whole-map dependencies") { using Result = ccf::kv::CommitResult; @@ -2592,24 +3066,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") @@ -2783,6 +3258,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( @@ -2799,24 +3276,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({}); @@ -2833,17 +3308,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() == @@ -3883,7 +4376,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. @@ -3912,13 +4406,44 @@ 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; 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); @@ -3957,22 +4482,31 @@ 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"); - REQUIRE_THROWS_WITH_AS( - reserved.commit_reserved(), - "Reserved transaction cannot be empty", - std::logic_error); + auto* handle = + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); + REQUIRE(handle->get(ccf::SerialisedMerkleTree::create_unit()).has_value()); + 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", @@ -4622,11 +5156,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, std::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++; } }); @@ -4635,16 +5169,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(std::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) @@ -4653,14 +5187,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(), - std::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 @@ -4689,7 +5221,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; @@ -4697,21 +5228,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; } @@ -4752,7 +5279,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); } @@ -5248,8 +5775,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({}); @@ -5324,8 +5851,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 5d8ee93551e4..cd0994896c82 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 e849df945890..7bf5a60eecc4 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -5,7 +5,9 @@ #include "ds/ccf_assert.h" #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" @@ -24,6 +26,54 @@ 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(std::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) + { + throw MapAccessDenied( + std::format("Access to map '{}' denied: {}", map_name, reason)); + } + } + void BaseTx::retain_change_set( const std::string& map_name, std::unique_ptr&& change_set, @@ -97,10 +147,18 @@ namespace ccf::kv std::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 && + !pimpl->store->check_rollback_count(pimpl->read_rollback_count)) + { + throw CompactedVersionConflict(std::format( + "Materialised state for map '{}' was invalidated by rollback", + map_name)); + } + return {abstract_map, std::move(change_set)}; } std::list BaseTx::get_possible_handles( @@ -139,6 +197,16 @@ namespace ccf::kv KV_TRACE(pimpl->trace_attempt.bind(store_)); } + BaseTx::BaseTx(AbstractStore* store_, MaterialisedReadOnlyTag /*tag*/) : + 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; + } + // 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 837010d23ed3..9598f14b6aee 100644 --- a/src/kv/tx_pimpl.h +++ b/src/kv/tx_pimpl.h @@ -9,7 +9,15 @@ namespace ccf::kv { struct BaseTx::PrivateImpl { + enum class Role : std::uint8_t + { + Ordinary, + Reserved, + MaterialisedReadOnly + }; + AbstractStore* store = nullptr; + Role role = Role::Ordinary; #ifdef CCF_KV_TRACING trace::Attempt trace_attempt; #endif @@ -25,6 +33,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/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, diff --git a/src/node/gov/handlers/acks.h b/src/node/gov/handlers/acks.h index d24f1c29d8c0..78018795cb0d 100644 --- a/src/node/gov/handlers/acks.h +++ b/src/node/gov/handlers/acks.h @@ -78,7 +78,8 @@ namespace ccf::gov::endpoints } template - inline void update_state_digest(Ctx& ctx, ApiVersion api_version) + inline void update_state_digest( + Ctx& ctx, ApiVersion api_version, NetworkState& network) { switch (api_version) { @@ -132,9 +133,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()) { @@ -351,7 +356,7 @@ namespace ccf::gov::endpoints inline void init_ack_handlers( ccf::BaseEndpointRegistry& registry, - NetworkState& /*network*/, + NetworkState& network, ShareManager& share_manager) { auto get_state_digest = [](auto& ctx, ApiVersion api_version) { @@ -367,8 +372,8 @@ namespace ccf::gov::endpoints .set_openapi_summary("Get a member's state digest") .install(); - auto update_state_digest = [](auto& ctx, ApiVersion api_version) { - detail::update_state_digest(ctx, api_version); + auto update_state_digest = [&network](auto& ctx, ApiVersion api_version) { + detail::update_state_digest(ctx, api_version, network); }; registry .make_endpoint( diff --git a/src/node/history.h b/src/node/history.h index 2117b61d6820..39f30641cf76 100644 --- a/src/node/history.h +++ b/src/node/history.h @@ -613,7 +613,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(); @@ -661,7 +661,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(); // Since COSE signatures have not always been emitted, it is possible in a // mixed-service to see an _old_ COSE signature (by reading from the KV) diff --git a/src/node/internal_tables_access.h b/src/node/internal_tables_access.h index eb98d24c7241..57bacf3458e1 100644 --- a/src/node/internal_tables_access.h +++ b/src/node/internal_tables_access.h @@ -396,7 +396,9 @@ namespace ccf const std::optional& pq_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); const auto prev_service_info = service->get(); @@ -457,27 +459,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 f2fed41caa9c..092c36eb4e9f 100644 --- a/src/node/node_state.h +++ b/src/node/node_state.h @@ -1161,7 +1161,7 @@ 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) @@ -2256,7 +2256,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); @@ -2326,7 +2326,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/frontend.h b/src/node/rpc/frontend.h index 7755ceb5f6c3..7f7737c4bb35 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" @@ -656,7 +657,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 +677,35 @@ 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 (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(); @@ -713,6 +731,8 @@ namespace ccf ccf::errors::InternalError, e.what()); } + + return true; } bool check_backpressure( @@ -938,10 +958,20 @@ namespace ccf return; } + if (attempts > 0) + { + // If the endpoint has already been executed, the effects of its + // execution should be dropped + ctx->reset_response(); + } + if (!tables.is_ready()) { - process_command_without_kv(ctx, endpoint, attempts); - return; + if (process_command_without_kv(ctx, endpoint, attempts)) + { + return; + } + continue; } // Readiness is published after these pointers. Load them only after @@ -957,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 @@ -1056,6 +1079,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/node_frontend.h b/src/node/rpc/node_frontend.h index 8a776fcc3ce8..aceb26a84a67 100644 --- a/src/node/rpc/node_frontend.h +++ b/src/node/rpc/node_frontend.h @@ -843,7 +843,7 @@ namespace ccf } auto get_state( - ccf::endpoints::ReadOnlyEndpointContext& args, + ccf::endpoints::CommandEndpointContext& /*args*/, nlohmann::json&& /*params*/) { GetState::Out result; @@ -854,34 +854,44 @@ namespace ccf result.last_recovered_seqno = lrs; 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.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.ro(Tables::SIGNATURES); + auto sig = signatures->get(); - ccf::kv::Version cose_seqno = 0; - auto* cose_signatures = - args.tx.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 raw_seqno = 0; + if (sig.has_value()) { - throw std::logic_error(std::format( - "Failed to parse txid from COSE signature: {}", - receipt.phdr.ccf.txid)); + raw_seqno = sig.value().seqno; } - cose_seqno = txid->seqno; - } - result.last_signed_seqno = std::max(raw_seqno, cose_seqno); + ccf::kv::Version cose_seqno = 0; + auto* cose_signatures = + signed_state.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()) + { + throw std::logic_error(std::format( + "Failed to parse txid from COSE signature: {}", + receipt.phdr.ccf.txid)); + } + cose_seqno = txid->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(); @@ -1575,13 +1585,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.pq_service_cert, in.create_txid, in.service_data, - recovering); + recovering, + previous_signed_root); if (recovering) { @@ -1953,12 +1983,12 @@ namespace ccf .install(); auto get_state = [this]( - ccf::endpoints::ReadOnlyEndpointContext& args, + ccf::endpoints::CommandEndpointContext& args, nlohmann::json&& json) { return this->get_state(args, std::move(json)); }; - 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_redirection_strategy(endpoints::RedirectionStrategy::None) .install(); 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/node/rpc/test/internal_tables_access_test.cpp b/src/node/rpc/test/internal_tables_access_test.cpp index 8dc1bd04b094..3faf914578da 100644 --- a/src/node/rpc/test/internal_tables_access_test.cpp +++ b/src/node/rpc/test/internal_tables_access_test.cpp @@ -939,18 +939,14 @@ TEST_CASE("Identity endorsements link consecutive service recoveries") const TestIdentity identity; { auto tx = store.create_tx(); - if (generation != 0) - { - tx.wo(Tables::SERIALISED_MERKLE_TREE) - ->put(tree.serialise()); - } InternalTablesAccess::create_service( tx, identity.cert, identity.pq_cert, creations[generation], {{"generation", generation}}, - generation != 0); + generation != 0, + generation != 0 ? std::make_optional(tree.get_root()) : std::nullopt); REQUIRE(InternalTablesAccess::endorse_previous_identity( tx, *identity.key, identity.pq_key)); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); @@ -1056,13 +1052,14 @@ namespace bool classical_only = false) { auto tx = store.create_tx(); - if (count != 0) - { - tx.wo(Tables::SERIALISED_MERKLE_TREE) - ->put(tree.serialise()); - } InternalTablesAccess::create_service( - tx, identity.cert, identity.pq_cert, create_txid, nullptr, count != 0); + tx, + identity.cert, + identity.pq_cert, + create_txid, + nullptr, + count != 0, + count != 0 ? std::make_optional(tree.get_root()) : std::nullopt); if (classical_only) { auto* service = tx.rw(Tables::SERVICE); @@ -1196,8 +1193,8 @@ TEST_CASE("Failed recovery creation preserves the previous service") REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } const char* expected_error = - "Previous service doesn't have a serialised merkle tree"; - SUBCASE("Missing serialised Merkle tree") {} + "Previous service has no materialised signed root"; + SUBCASE("Missing materialised signed root") {} SUBCASE("Missing creation transaction") { auto tx = store.create_tx(); @@ -2061,15 +2058,27 @@ TEST_CASE("create_service publishes the service signing identities") 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, recovered_pq_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, recovered_pq_cert, {2, 10}, nullptr, - true /* recovering */); + 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 b16c38d54236..dff08340915e 100644 --- a/src/node/rpc/test/node_frontend_test.cpp +++ b/src/node/rpc/test/node_frontend_test.cpp @@ -635,6 +635,323 @@ TEST_CASE("Self certificate authentication") CHECK(error_reason.contains("before certificate's Not Before")); } +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; + } + }; + + 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); + + 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, reported_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); + }; + + // 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; + context.install_subsystem(std::make_shared( + node_state, NodeConfigurationSubsystem::InterfaceRegexes{})); + 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()); + + 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); + + // 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") { NetworkState network; diff --git a/src/node/rpc/test/node_stub.h b/src/node/rpc/test/node_stub.h index dd1ad0287e68..986b62f0f850 100644 --- a/src/node/rpc/test/node_stub.h +++ b/src/node/rpc/test/node_stub.h @@ -19,10 +19,18 @@ 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; + std::function on_state = nullptr; ExtendedState state() override { - return {NodeStartupState::partOfNetwork, {}, {}}; + if (on_state != nullptr) + { + on_state(); + } + return extended_state; } bool is_in_initialised_state() const override @@ -77,7 +85,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 +107,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 diff --git a/src/node/test/historical_queries.cpp b/src/node/test/historical_queries.cpp index 565659694053..f7e65ec2311f 100644 --- a/src/node/test/historical_queries.cpp +++ b/src/node/test/historical_queries.cpp @@ -1965,39 +1965,94 @@ TEST_CASE("Historical cache rejects signatures which misreport their TxID") // Write a signature transaction by hand, which declares a TxID in a later // view than the one it is actually committed in - const auto signature_seqno = store.current_version() + 1; - const ccf::TxID declared_id{store.current_txid().view + 1, signature_seqno}; + const auto signature_txid = store.next_txid(); + const auto signature_seqno = signature_txid.seqno; + const ccf::TxID declared_id{signature_txid.view + 1, signature_seqno}; { - auto tx = store.create_tx(); - const auto root = history->get_replicated_state_root(); - const std::vector root_hash(root.h.begin(), root.h.end()); - if (signing_mode == ccf::LedgerSignMode::Dual) + class MisreportedSignatureTx : public ccf::kv::PendingTx { - tx.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature( - ccf::NodeId{"node_id"}, - declared_id.seqno, - declared_id.view, - root, - {}, - state.node_kp->sign_hash(root_hash.data(), root_hash.size()), - node_cert)); - } - const auto& cose_config = history->get_cose_signatures_config(); - tx.wo(ccf::Tables::COSE_SIGNATURES) - ->put( - ccf::IdentityType::CLASSICAL, - ccf::cose::sign_ledger( - *state.service_kp, - ccf::crypto::kid_from_key(state.service_kp->public_key_der()), - 0, - cose_config.issuer, - cose_config.subject, - declared_id.to_str(), - root_hash)); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put(history->serialise_tree(signature_seqno - 1)); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + ccf::kv::Store& store; + ccf::TxID txid; + ccf::TxID declared_id; + ccf::LedgerSignMode signing_mode; + ccf::crypto::Sha256Hash root; + std::vector serialised_tree; + ccf::crypto::ECKeyPairPtr node_kp; + ccf::crypto::Pem node_cert; + ccf::crypto::ECKeyPairPtr service_kp; + ccf::COSESignaturesConfig cose_config; + + public: + MisreportedSignatureTx( + ccf::kv::Store& store_, + ccf::TxID txid_, + ccf::TxID declared_id_, + ccf::LedgerSignMode signing_mode_, + ccf::crypto::Sha256Hash root_, + std::vector serialised_tree_, + ccf::crypto::ECKeyPairPtr node_kp_, + ccf::crypto::Pem node_cert_, + ccf::crypto::ECKeyPairPtr service_kp_, + ccf::COSESignaturesConfig cose_config_) : + store(store_), + txid(txid_), + declared_id(declared_id_), + signing_mode(signing_mode_), + root(root_), + serialised_tree(std::move(serialised_tree_)), + node_kp(std::move(node_kp_)), + node_cert(std::move(node_cert_)), + service_kp(std::move(service_kp_)), + cose_config(std::move(cose_config_)) + {} + + ccf::kv::PendingTxInfo call() override + { + auto tx = store.create_reserved_tx(txid); + const std::vector root_hash(root.h.begin(), root.h.end()); + if (signing_mode == ccf::LedgerSignMode::Dual) + { + tx.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature( + ccf::NodeId{"node_id"}, + declared_id.seqno, + declared_id.view, + root, + {}, + node_kp->sign_hash(root_hash.data(), root_hash.size()), + node_cert)); + } + tx.wo(ccf::Tables::COSE_SIGNATURES) + ->put( + ccf::IdentityType::CLASSICAL, + ccf::cose::sign_ledger( + *service_kp, + ccf::crypto::kid_from_key(service_kp->public_key_der()), + 0, + cose_config.issuer, + cose_config.subject, + declared_id.to_str(), + root_hash)); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put(serialised_tree); + return tx.commit_reserved(); + } + }; + + auto pending = std::make_unique( + store, + signature_txid, + declared_id, + signing_mode, + history->get_replicated_state_root(), + history->serialise_tree(signature_seqno - 1), + state.node_kp, + node_cert, + state.service_kp, + history->get_cose_signatures_config()); + REQUIRE( + store.commit(signature_txid, std::move(pending), true) == + ccf::kv::CommitResult::SUCCESS); } const auto signature_id = store.current_txid(); REQUIRE(signature_id.seqno == signature_seqno); @@ -4071,7 +4126,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) { @@ -4079,12 +4135,22 @@ TEST_CASE( } tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({}); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + 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); - const auto txid = store.current_txid(); + 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 c80a7d04709f..94170d50c75c 100644 --- a/src/node/test/history.cpp +++ b/src/node/test/history.cpp @@ -317,12 +317,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); } } @@ -510,7 +525,7 @@ TEST_CASE("Signing identity carries an ML-DSA key next to the classical key") primary_history->emit_signature(); REQUIRE(consensus->last_apply_result == ccf::kv::ApplyResult::PASS_SIGNATURE); - auto tx = backup_store.create_read_only_tx(); + auto tx = backup_store.create_read_only_tx_at_replicated_state(); auto* cose_signatures = tx.ro(ccf::Tables::COSE_SIGNATURES); const auto classical_signature = @@ -883,20 +898,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(); } }; @@ -928,7 +941,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(); @@ -937,11 +949,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()); @@ -1007,7 +1018,7 @@ TEST_CASE("Signatures are not emitted on demand until signing is enabled") MapT table("public:table"); auto get_signature = [&]() { - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); return tx.ro(ccf::Tables::SIGNATURES)->get(); }; @@ -1064,8 +1075,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({}); @@ -1096,7 +1107,6 @@ TEST_CASE( store.set_consensus(consensus); MapT table("public:table"); - MapT other_table("public:other_table"); INFO("Write first tx"); { @@ -1117,8 +1127,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); } @@ -1375,15 +1384,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 @@ -1409,22 +1421,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/network_identity_subsystem.cpp b/src/node/test/network_identity_subsystem.cpp index fc8e00557b53..d2ae384f28b7 100644 --- a/src/node/test/network_identity_subsystem.cpp +++ b/src/node/test/network_identity_subsystem.cpp @@ -2131,13 +2131,14 @@ namespace keys.pq_key->self_sign("CN=test", valid_from, valid_to); auto tx = node_state->store->create_tx(); - if (count != 0) - { - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put(tree.serialise()); - } ccf::InternalTablesAccess::create_service( - tx, cert, pq_cert, create_txid, nullptr, count != 0); + tx, + cert, + pq_cert, + create_txid, + nullptr, + count != 0, + count != 0 ? std::make_optional(tree.get_root()) : std::nullopt); if (!with_pq) { auto* service = tx.rw(ccf::Tables::SERVICE); diff --git a/src/node/test/snapshot.cpp b/src/node/test/snapshot.cpp index c817b08e9758..01eb77869cb6 100644 --- a/src/node/test/snapshot.cpp +++ b/src/node/test/snapshot.cpp @@ -140,7 +140,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 8f22d0088b25..a73e341e34ee 100644 --- a/src/node/test/snapshotter.cpp +++ b/src/node/test/snapshotter.cpp @@ -1448,14 +1448,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 943c826c0e57..6e31ee5ae45b 100644 --- a/src/rust/app_bridge.cpp +++ b/src/rust/app_bridge.cpp @@ -8,6 +8,7 @@ #include "ccf/odata_error.h" #include "ccf/rust_ffi.h" #include "kv/compacted_version_conflict.h" +#include "kv/map_access_denied.h" #include #include @@ -311,6 +312,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 a1f1aa18d1bf..3894eaddc475 100644 --- a/tests/basic_rust.py +++ b/tests/basic_rust.py @@ -79,6 +79,19 @@ 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") +def test_signature_table_access_denied(network, args): + primary, _ = network.find_primary() + + with primary.client() as anonymous: + response = anonymous.post("/app/signature-table-access") + assert response.status_code == http.HTTPStatus.OK, response + assert response.body.text() == "denied" + + return network + + def test_compaction_conflict_is_retried(network, args): primary, _ = network.find_primary() @@ -135,6 +148,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 45cf7f355f49..792f944c5bf2 100644 --- a/tests/e2e_operations.py +++ b/tests/e2e_operations.py @@ -1859,6 +1859,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 6c611de4c69a..319fd2072c8b 100644 --- a/tests/governance.py +++ b/tests/governance.py @@ -15,6 +15,7 @@ import governance_api import governance_history import governance_js +import infra.clients import infra.crypto import infra.e2e_args import infra.interfaces @@ -341,6 +342,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 b4815227471e..8e609bc74262 100644 --- a/tests/infra/network.py +++ b/tests/infra/network.py @@ -2104,7 +2104,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 74e3899b7a9e..8fbb7a292904 100644 --- a/tests/programmability.py +++ b/tests/programmability.py @@ -272,6 +272,11 @@ 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", + ) endpoints = { "/try_read": { @@ -305,6 +310,12 @@ def test_custom_endpoints_kv_restrictions(network, args): js_function="try_read_current_via_historical_handle", ) }, + "/read_historical_signature_tables": { + "post": endpoint_properties( + js_module=module_name, + js_function="read_historical_signature_tables", + ) + }, } with open( @@ -409,6 +420,30 @@ 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 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("Neighboring public internal tables remain read-only") + for table in ( + "public:ccf.internal.signatures_other", + "public:ccf.internal.cose_signatures_other", + "public:ccf.internal.tree.nested", + ): + 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"}) assert r.status_code == http.HTTPStatus.BAD_REQUEST.value, r.status_code @@ -469,6 +504,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, @@ -477,6 +519,37 @@ 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"], (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) + return network diff --git a/tests/programmability/restrictions.js b/tests/programmability/restrictions.js index 8cb6286161b6..d3ca125e8c51 100644 --- a/tests/programmability/restrictions.js +++ b/tests/programmability/restrictions.js @@ -1,5 +1,10 @@ const FIXED_KEY = ccf.strToBuf("hello"); const FIXED_VALUE = ccf.strToBuf("world"); +const SIGNATURE_TABLES = [ + "public:ccf.internal.signatures", + "public:ccf.internal.cose_signatures", + "public:ccf.internal.tree", +]; export function try_read(request) { const table_name = request.body.json().table; @@ -141,3 +146,60 @@ export function try_read_current_via_historical_handle(request) { 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(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 state = states[0]; + const tables = {}; + for (const table of SIGNATURE_TABLES) { + const handle = state.kv[table]; + let entries = 0; + handle.forEach((value, 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++; + }); + 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 }; + } + + 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}`, + }; + } +}