-
Notifications
You must be signed in to change notification settings - Fork 217
/
Copy pathnode_frontend.h
2140 lines (1931 loc) · 72.2 KB
/
node_frontend.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "ccf/common_auth_policies.h"
#include "ccf/common_endpoint_registry.h"
#include "ccf/http_query.h"
#include "ccf/js/core/context.h"
#include "ccf/json_handler.h"
#include "ccf/node/quote.h"
#include "ccf/odata_error.h"
#include "ccf/pal/attestation.h"
#include "ccf/pal/mem.h"
#include "ccf/service/reconfiguration_type.h"
#include "ccf/version.h"
#include "crypto/certs.h"
#include "crypto/csr.h"
#include "ds/files.h"
#include "ds/std_formatters.h"
#include "frontend.h"
#include "node/network_state.h"
#include "node/rpc/jwt_management.h"
#include "node/rpc/no_create_tx_claims_digest.cpp"
#include "node/rpc/serialization.h"
#include "node/session_metrics.h"
#include "node_interface.h"
#include "service/internal_tables_access.h"
#include "service/tables/previous_service_identity.h"
#include "snapshots/filenames.h"
namespace ccf
{
struct Quote
{
NodeId node_id = {};
std::vector<uint8_t> raw;
std::vector<uint8_t> endorsements;
QuoteFormat format;
std::string mrenclave = {}; // < Hex-encoded
std::optional<std::vector<uint8_t>> uvm_endorsements =
std::nullopt; // SNP only
};
DECLARE_JSON_TYPE_WITH_OPTIONAL_FIELDS(Quote);
DECLARE_JSON_REQUIRED_FIELDS(Quote, node_id, raw, endorsements, format);
DECLARE_JSON_OPTIONAL_FIELDS(Quote, mrenclave, uvm_endorsements);
struct GetQuotes
{
using In = void;
struct Out
{
std::vector<Quote> quotes;
};
};
DECLARE_JSON_TYPE(GetQuotes::Out);
DECLARE_JSON_REQUIRED_FIELDS(GetQuotes::Out, quotes);
struct NodeMetrics
{
ccf::SessionMetrics sessions;
};
DECLARE_JSON_TYPE(NodeMetrics);
DECLARE_JSON_REQUIRED_FIELDS(NodeMetrics, sessions);
struct JavaScriptMetrics
{
uint64_t bytecode_size;
bool bytecode_used;
uint64_t max_heap_size;
uint64_t max_stack_size;
uint64_t max_execution_time;
uint64_t max_cached_interpreters = 10;
};
DECLARE_JSON_TYPE(JavaScriptMetrics);
DECLARE_JSON_REQUIRED_FIELDS(
JavaScriptMetrics,
bytecode_size,
bytecode_used,
max_heap_size,
max_stack_size,
max_execution_time,
max_cached_interpreters);
struct JWTRefreshMetrics
{
size_t attempts = 0;
size_t successes = 0;
size_t failures = 0;
};
DECLARE_JSON_TYPE(JWTRefreshMetrics)
DECLARE_JSON_REQUIRED_FIELDS(JWTRefreshMetrics, attempts, successes, failures)
struct SetJwtPublicSigningKeys
{
std::string issuer;
JsonWebKeySet jwks;
};
DECLARE_JSON_TYPE(SetJwtPublicSigningKeys);
DECLARE_JSON_REQUIRED_FIELDS(SetJwtPublicSigningKeys, issuer, jwks);
struct ConsensusNodeConfig
{
std::string address;
};
DECLARE_JSON_TYPE(ConsensusNodeConfig);
DECLARE_JSON_REQUIRED_FIELDS(ConsensusNodeConfig, address);
using ConsensusConfig = std::map<std::string, ConsensusNodeConfig>;
struct ConsensusConfigDetails
{
ccf::kv::ConsensusDetails details;
};
DECLARE_JSON_TYPE(ConsensusConfigDetails);
DECLARE_JSON_REQUIRED_FIELDS(ConsensusConfigDetails, details);
struct SelfSignedNodeCertificateInfo
{
ccf::crypto::Pem self_signed_certificate;
};
DECLARE_JSON_TYPE(SelfSignedNodeCertificateInfo);
DECLARE_JSON_REQUIRED_FIELDS(
SelfSignedNodeCertificateInfo, self_signed_certificate);
struct GetServicePreviousIdentity
{
struct Out
{
ccf::crypto::Pem previous_service_identity;
};
};
DECLARE_JSON_TYPE(GetServicePreviousIdentity::Out);
DECLARE_JSON_REQUIRED_FIELDS(
GetServicePreviousIdentity::Out, previous_service_identity);
class NodeEndpoints : public CommonEndpointRegistry
{
public:
// The node frontend is exempt from backpressure rules to enable an operator
// to access a node that is not making progress.
bool apply_uncommitted_tx_backpressure() const override
{
return false;
}
private:
NetworkState& network;
ccf::AbstractNodeOperation& node_operation;
static std::pair<http_status, std::string> quote_verification_error(
QuoteVerificationResult result)
{
switch (result)
{
case QuoteVerificationResult::Failed:
return std::make_pair(
HTTP_STATUS_UNAUTHORIZED, "Quote could not be verified");
case QuoteVerificationResult::FailedMeasurementNotFound:
return std::make_pair(
HTTP_STATUS_UNAUTHORIZED,
"Quote does not contain known enclave measurement");
case QuoteVerificationResult::FailedInvalidQuotedPublicKey:
return std::make_pair(
HTTP_STATUS_UNAUTHORIZED,
"Quote report data does not contain node's public key hash");
case QuoteVerificationResult::FailedHostDataDigestNotFound:
return std::make_pair(
HTTP_STATUS_UNAUTHORIZED,
"Quote does not contain trusted host data");
case QuoteVerificationResult::FailedInvalidHostData:
return std::make_pair(
HTTP_STATUS_UNAUTHORIZED, "Quote host data is not authorised");
case ccf::QuoteVerificationResult::FailedUVMEndorsementsNotFound:
return std::make_pair(
HTTP_STATUS_UNAUTHORIZED, "UVM endorsements are not authorised");
default:
return std::make_pair(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
"Unknown quote verification error");
}
}
struct ExistingNodeInfo
{
NodeId node_id;
std::optional<ccf::kv::Version> ledger_secret_seqno = std::nullopt;
std::optional<ccf::crypto::Pem> endorsed_certificate = std::nullopt;
};
std::optional<ExistingNodeInfo> check_node_exists(
ccf::kv::Tx& tx,
const std::vector<uint8_t>& self_signed_node_der,
std::optional<NodeStatus> node_status = std::nullopt)
{
// Check that a node exists by looking up its public key in the nodes
// table.
auto nodes = tx.ro(network.nodes);
auto endorsed_node_certificates =
tx.ro(network.node_endorsed_certificates);
LOG_DEBUG_FMT(
"Check node exists with certificate [{}]", self_signed_node_der);
auto pk_pem = ccf::crypto::public_key_pem_from_cert(self_signed_node_der);
std::optional<ExistingNodeInfo> existing_node_info = std::nullopt;
nodes->foreach([&existing_node_info,
&pk_pem,
&node_status,
&endorsed_node_certificates](
const NodeId& nid, const NodeInfo& ni) {
if (
ni.public_key == pk_pem &&
(!node_status.has_value() || ni.status == node_status.value()))
{
existing_node_info = {
nid, ni.ledger_secret_seqno, endorsed_node_certificates->get(nid)};
return false;
}
return true;
});
return existing_node_info;
}
std::optional<NodeId> check_conflicting_node_network(
ccf::kv::Tx& tx, const NodeInfoNetwork& node_info_network)
{
auto nodes = tx.rw(network.nodes);
std::optional<NodeId> duplicate_node_id = std::nullopt;
nodes->foreach([&node_info_network, &duplicate_node_id](
const NodeId& nid, const NodeInfo& ni) {
if (
node_info_network.node_to_node_interface.published_address ==
ni.node_to_node_interface.published_address &&
ni.status != NodeStatus::RETIRED)
{
duplicate_node_id = nid;
return false;
}
return true;
});
return duplicate_node_id;
}
bool is_taking_part_in_acking(NodeStatus node_status)
{
return node_status == NodeStatus::TRUSTED;
}
auto add_node(
ccf::kv::Tx& tx,
const std::vector<uint8_t>& node_der,
const JoinNetworkNodeToNode::In& in,
NodeStatus node_status,
ServiceStatus service_status,
ccf::ReconfigurationType reconfiguration_type)
{
auto nodes = tx.rw(network.nodes);
auto node_endorsed_certificates =
tx.rw(network.node_endorsed_certificates);
auto conflicting_node_id =
check_conflicting_node_network(tx, in.node_info_network);
if (conflicting_node_id.has_value())
{
return make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::NodeAlreadyExists,
fmt::format(
"A node with the same published node address {} already exists "
"(node id: {}).",
in.node_info_network.node_to_node_interface.published_address,
conflicting_node_id.value()));
}
auto pubk_der = ccf::crypto::public_key_der_from_cert(node_der);
NodeId joining_node_id = compute_node_id_from_pubk_der(pubk_der);
pal::PlatformAttestationMeasurement measurement;
QuoteVerificationResult verify_result = this->node_operation.verify_quote(
tx, in.quote_info, pubk_der, measurement);
if (verify_result != QuoteVerificationResult::Verified)
{
const auto [code, message] = quote_verification_error(verify_result);
return make_error(code, ccf::errors::InvalidQuote, message);
}
std::optional<ccf::kv::Version> ledger_secret_seqno = std::nullopt;
if (node_status == NodeStatus::TRUSTED)
{
ledger_secret_seqno =
this->network.ledger_secrets->get_latest(tx).first;
}
// Note: All new nodes should specify a CSR from 2.x
auto client_public_key_pem =
ccf::crypto::public_key_pem_from_cert(node_der);
if (in.certificate_signing_request.has_value())
{
// Verify that client's public key matches the one specified in the CSR
auto csr_public_key_pem = ccf::crypto::public_key_pem_from_csr(
in.certificate_signing_request.value());
if (client_public_key_pem != csr_public_key_pem)
{
return make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::CSRPublicKeyInvalid,
"Public key in CSR does not match TLS client identity.");
}
}
NodeInfo node_info = {
in.node_info_network,
in.quote_info,
in.public_encryption_key,
node_status,
ledger_secret_seqno,
measurement.hex_str(),
in.certificate_signing_request,
client_public_key_pem,
in.node_data};
nodes->put(joining_node_id, node_info);
LOG_INFO_FMT("Node {} added as {}", joining_node_id, node_status);
JoinNetworkNodeToNode::Out rep;
rep.node_status = node_status;
rep.node_id = joining_node_id;
if (node_status == NodeStatus::TRUSTED)
{
// Joining node only submit a CSR from 2.x
std::optional<ccf::crypto::Pem> endorsed_certificate = std::nullopt;
if (in.certificate_signing_request.has_value())
{
// For a pre-open service, extract the validity period of self-signed
// node certificate and use it verbatim in endorsed certificate
auto [valid_from, valid_to] =
ccf::crypto::make_verifier(node_der)->validity_period();
endorsed_certificate = ccf::crypto::create_endorsed_cert(
in.certificate_signing_request.value(),
valid_from,
valid_to,
this->network.identity->priv_key,
this->network.identity->cert);
node_endorsed_certificates->put(
joining_node_id, {endorsed_certificate.value()});
}
rep.network_info = JoinNetworkNodeToNode::Out::NetworkInfo{
node_operation.is_part_of_public_network(),
node_operation.get_last_recovered_signed_idx(),
this->network.ledger_secrets->get(tx),
*this->network.identity.get(),
service_status,
endorsed_certificate,
node_operation.get_cose_signatures_config()};
}
return make_success(rep);
}
JWTRefreshMetrics jwt_refresh_metrics;
void handle_event_request_completed(
const ccf::endpoints::RequestCompletedEvent& event) override
{
if (event.method == "POST" && event.dispatch_path == "/jwt_keys/refresh")
{
jwt_refresh_metrics.attempts += 1;
int status_category = event.status / 100;
if (status_category >= 4)
{
jwt_refresh_metrics.failures += 1;
}
else if (status_category == 2)
{
jwt_refresh_metrics.successes += 1;
}
}
}
public:
NodeEndpoints(NetworkState& network_, ccf::AbstractNodeContext& context_) :
CommonEndpointRegistry(get_actor_prefix(ActorsType::nodes), context_),
network(network_),
node_operation(*context_.get_subsystem<ccf::AbstractNodeOperation>())
{
openapi_info.title = "CCF Public Node API";
openapi_info.description =
"This API provides public, uncredentialed access to service and node "
"state.";
openapi_info.document_version = "4.11.0";
}
void init_handlers() override
{
CommonEndpointRegistry::init_handlers();
auto accept = [this](auto& args, const nlohmann::json& params) {
const auto in = params.get<JoinNetworkNodeToNode::In>();
if (
!this->node_operation.is_part_of_network() &&
!this->node_operation.is_part_of_public_network() &&
!this->node_operation.is_reading_private_ledger())
{
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InternalError,
"Target node should be part of network to accept new nodes.");
}
// Make sure that the joiner's snapshot is more recent than this node's
// snapshot. Otherwise, the joiner may not be given all the ledger
// secrets required to replay historical transactions.
auto this_startup_seqno =
this->node_operation.get_startup_snapshot_seqno();
if (
in.startup_seqno.has_value() &&
this_startup_seqno > in.startup_seqno.value())
{
return make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::StartupSeqnoIsOld,
fmt::format(
"Node requested to join from seqno {} which is older than this "
"node startup seqno {}. A snapshot at least as recent as {} must "
"be used instead.",
in.startup_seqno.value(),
this_startup_seqno,
this_startup_seqno));
}
auto nodes = args.tx.rw(this->network.nodes);
auto service = args.tx.rw(this->network.service);
auto active_service = service->get();
if (!active_service.has_value())
{
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InternalError,
"No service is available to accept new node.");
}
auto config = args.tx.ro(network.config);
auto service_config = config->get();
if (
active_service->status == ServiceStatus::OPENING ||
active_service->status == ServiceStatus::RECOVERING)
{
// If the service is opening, new nodes are trusted straight away
NodeStatus joining_node_status = NodeStatus::TRUSTED;
// If the node is already trusted, return network secrets
auto existing_node_info = check_node_exists(
args.tx,
args.rpc_ctx->get_session_context()->caller_cert,
joining_node_status);
if (existing_node_info.has_value())
{
JoinNetworkNodeToNode::Out rep;
rep.node_status = joining_node_status;
rep.network_info = JoinNetworkNodeToNode::Out::NetworkInfo(
node_operation.is_part_of_public_network(),
node_operation.get_last_recovered_signed_idx(),
this->network.ledger_secrets->get(
args.tx, existing_node_info->ledger_secret_seqno),
*this->network.identity.get(),
active_service->status,
existing_node_info->endorsed_certificate,
node_operation.get_cose_signatures_config());
return make_success(rep);
}
if (consensus != nullptr && !this->node_operation.can_replicate())
{
auto primary_id = consensus->primary();
if (primary_id.has_value())
{
auto info = nodes->get(primary_id.value());
if (info)
{
auto& interface_id =
args.rpc_ctx->get_session_context()->interface_id;
if (!interface_id.has_value())
{
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InternalError,
"Cannot redirect non-RPC request.");
}
const auto& address =
info->rpc_interfaces[interface_id.value()].published_address;
args.rpc_ctx->set_response_header(
http::headers::LOCATION,
fmt::format("https://{}/node/join", address));
return make_error(
HTTP_STATUS_PERMANENT_REDIRECT,
ccf::errors::NodeCannotHandleRequest,
"Node is not primary; cannot handle write");
}
}
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InternalError,
"Primary unknown");
}
return add_node(
args.tx,
args.rpc_ctx->get_session_context()->caller_cert,
in,
joining_node_status,
active_service->status,
ccf::ReconfigurationType::ONE_TRANSACTION);
}
// If the service is open, new nodes are first added as pending and
// then only trusted via member governance. It is expected that a new
// node polls the network to retrieve the network secrets until it is
// trusted
auto existing_node_info = check_node_exists(
args.tx, args.rpc_ctx->get_session_context()->caller_cert);
if (existing_node_info.has_value())
{
JoinNetworkNodeToNode::Out rep;
// If the node already exists, return network secrets if is already
// trusted. Otherwise, only return its status
auto node_info = nodes->get(existing_node_info->node_id);
auto node_status = node_info->status;
rep.node_status = node_status;
if (is_taking_part_in_acking(node_status))
{
rep.network_info = JoinNetworkNodeToNode::Out::NetworkInfo(
node_operation.is_part_of_public_network(),
node_operation.get_last_recovered_signed_idx(),
this->network.ledger_secrets->get(
args.tx, existing_node_info->ledger_secret_seqno),
*this->network.identity.get(),
active_service->status,
existing_node_info->endorsed_certificate,
node_operation.get_cose_signatures_config());
return make_success(rep);
}
else if (node_status == NodeStatus::PENDING)
{
// Only return node status and ID
return make_success(rep);
}
else
{
return make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidNodeState,
fmt::format(
"Joining node is not in expected state ({}).", node_status));
}
}
else
{
if (consensus != nullptr && !this->node_operation.can_replicate())
{
auto primary_id = consensus->primary();
if (primary_id.has_value())
{
auto info = nodes->get(primary_id.value());
if (info)
{
auto& interface_id =
args.rpc_ctx->get_session_context()->interface_id;
if (!interface_id.has_value())
{
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InternalError,
"Cannot redirect non-RPC request.");
}
const auto& address =
info->rpc_interfaces[interface_id.value()].published_address;
args.rpc_ctx->set_response_header(
http::headers::LOCATION,
fmt::format("https://{}/node/join", address));
return make_error(
HTTP_STATUS_PERMANENT_REDIRECT,
ccf::errors::NodeCannotHandleRequest,
"Node is not primary; cannot handle write");
}
}
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InternalError,
"Primary unknown");
}
// If the node does not exist, add it to the KV in state pending
return add_node(
args.tx,
args.rpc_ctx->get_session_context()->caller_cert,
in,
NodeStatus::PENDING,
active_service->status,
ccf::ReconfigurationType::ONE_TRANSACTION);
}
};
make_endpoint("/join", HTTP_POST, json_adapter(accept), no_auth_required)
.set_forwarding_required(endpoints::ForwardingRequired::Never)
.set_openapi_hidden(true)
.install();
auto set_retired_committed = [this](auto& ctx, nlohmann::json&&) {
auto nodes = ctx.tx.rw(network.nodes);
nodes->foreach([this, &nodes](const auto& node_id, auto node_info) {
auto gc_node = nodes->get_globally_committed(node_id);
if (
gc_node.has_value() &&
gc_node->status == ccf::NodeStatus::RETIRED &&
!node_info.retired_committed)
{
// Set retired_committed on nodes for which RETIRED status
// has been committed.
node_info.retired_committed = true;
nodes->put(node_id, node_info);
LOG_DEBUG_FMT("Setting retired_committed on node {}", node_id);
}
return true;
});
return make_success();
};
make_endpoint(
"network/nodes/set_retired_committed",
HTTP_POST,
json_adapter(set_retired_committed),
{std::make_shared<NodeCertAuthnPolicy>()})
.set_openapi_hidden(true)
.install();
auto get_state = [this](auto& args, nlohmann::json&&) {
GetState::Out result;
auto [s, rts, lrs] = this->node_operation.state();
result.node_id = this->context.get_node_id();
result.state = s;
result.recovery_target_seqno = rts;
result.last_recovered_seqno = lrs;
result.startup_seqno =
this->node_operation.get_startup_snapshot_seqno();
auto signatures = args.tx.template ro<Signatures>(Tables::SIGNATURES);
auto sig = signatures->get();
if (!sig.has_value())
{
result.last_signed_seqno = 0;
}
else
{
result.last_signed_seqno = sig.value().seqno;
}
auto node_configuration_subsystem =
this->context.get_subsystem<NodeConfigurationSubsystem>();
if (!node_configuration_subsystem)
{
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InternalError,
"NodeConfigurationSubsystem is not available");
}
result.stop_notice =
node_configuration_subsystem->has_received_stop_notice();
return make_success(result);
};
make_read_only_endpoint(
"/state", HTTP_GET, json_read_only_adapter(get_state), no_auth_required)
.set_auto_schema<GetState>()
.set_forwarding_required(endpoints::ForwardingRequired::Never)
.install();
auto get_quote = [this](auto& args, nlohmann::json&&) {
QuoteInfo node_quote_info;
const auto result =
get_quote_for_this_node_v1(args.tx, node_quote_info);
if (result == ApiResult::OK)
{
Quote q;
q.node_id = context.get_node_id();
q.raw = node_quote_info.quote;
q.endorsements = node_quote_info.endorsements;
q.format = node_quote_info.format;
q.uvm_endorsements = node_quote_info.uvm_endorsements;
// get_measurement attempts to re-validate the quote to extract
// mrenclave and the Open Enclave is insufficiently flexible to allow
// quotes with expired collateral to be parsed at all. Recent nodes
// therefore cache their code digest on startup, and this code
// attempts to fetch that value when possible and only call the
// unreliable get_measurement otherwise.
auto nodes = args.tx.ro(network.nodes);
auto node_info = nodes->get(context.get_node_id());
if (node_info.has_value() && node_info->code_digest.has_value())
{
q.mrenclave = node_info->code_digest.value();
}
else
{
auto measurement =
AttestationProvider::get_measurement(node_quote_info);
if (measurement.has_value())
{
q.mrenclave = measurement.value().hex_str();
}
else
{
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InvalidQuote,
"Failed to extract code id from node quote.");
}
}
return make_success(q);
}
else if (result == ApiResult::NotFound)
{
return make_error(
HTTP_STATUS_NOT_FOUND,
ccf::errors::ResourceNotFound,
"Could not find node quote.");
}
else
{
return make_error(
HTTP_STATUS_INTERNAL_SERVER_ERROR,
ccf::errors::InternalError,
fmt::format("Error code: {}", ccf::api_result_to_str(result)));
}
};
make_read_only_endpoint(
"/quotes/self",
HTTP_GET,
json_read_only_adapter(get_quote),
no_auth_required)
.set_auto_schema<void, Quote>()
.set_forwarding_required(endpoints::ForwardingRequired::Never)
.install();
auto get_quotes = [this](auto& args, nlohmann::json&&) {
GetQuotes::Out result;
auto nodes = args.tx.ro(network.nodes);
nodes->foreach(["es = result.quotes](
const auto& node_id, const auto& node_info) {
if (node_info.status == ccf::NodeStatus::TRUSTED)
{
Quote q;
q.node_id = node_id;
q.raw = node_info.quote_info.quote;
q.endorsements = node_info.quote_info.endorsements;
q.format = node_info.quote_info.format;
// get_measurement attempts to re-validate the quote to extract
// mrenclave and the Open Enclave is insufficiently flexible to
// allow quotes with expired collateral to be parsed at all. Recent
// nodes therefore cache their code digest on startup, and this code
// attempts to fetch that value when possible and only call the
// unreliable get_measurement otherwise.
if (node_info.code_digest.has_value())
{
q.mrenclave = node_info.code_digest.value();
}
else
{
auto measurement =
AttestationProvider::get_measurement(node_info.quote_info);
if (measurement.has_value())
{
q.mrenclave = measurement.value().hex_str();
}
}
quotes.emplace_back(q);
}
return true;
});
return make_success(result);
};
make_read_only_endpoint(
"/quotes",
HTTP_GET,
json_read_only_adapter(get_quotes),
no_auth_required)
.set_auto_schema<GetQuotes>()
.install();
auto network_status = [this](auto& args, nlohmann::json&&) {
GetNetworkInfo::Out out;
auto service = args.tx.ro(network.service);
auto service_state = service->get();
if (service_state.has_value())
{
const auto& service_value = service_state.value();
out.service_status = service_value.status;
out.service_certificate = service_value.cert;
out.recovery_count = service_value.recovery_count.value_or(0);
out.service_data = service_value.service_data;
out.current_service_create_txid =
service_value.current_service_create_txid;
if (consensus != nullptr)
{
out.current_view = consensus->get_view();
auto primary_id = consensus->primary();
if (primary_id.has_value())
{
out.primary_id = primary_id.value();
}
}
return make_success(out);
}
return make_error(
HTTP_STATUS_NOT_FOUND,
ccf::errors::ResourceNotFound,
"Service state not available.");
};
make_read_only_endpoint(
"/network",
HTTP_GET,
json_read_only_adapter(network_status),
no_auth_required)
.set_auto_schema<void, GetNetworkInfo::Out>()
.install();
auto service_previous_identity = [this](auto& args, nlohmann::json&&) {
auto psi_handle = args.tx.template ro<ccf::PreviousServiceIdentity>(
ccf::Tables::PREVIOUS_SERVICE_IDENTITY);
const auto psi = psi_handle->get();
if (psi.has_value())
{
GetServicePreviousIdentity::Out out;
out.previous_service_identity = psi.value();
return make_success(out);
}
else
{
return make_error(
HTTP_STATUS_NOT_FOUND,
ccf::errors::ResourceNotFound,
"This service is not a recovery of a previous service.");
}
};
make_read_only_endpoint(
"/service/previous_identity",
HTTP_GET,
json_read_only_adapter(service_previous_identity),
no_auth_required)
.set_auto_schema<void, GetServicePreviousIdentity::Out>()
.install();
auto get_nodes = [this](auto& args, nlohmann::json&&) {
const auto parsed_query =
http::parse_query(args.rpc_ctx->get_request_query());
std::string error_string; // Ignored - all params are optional
const auto host = http::get_query_value_opt<std::string>(
parsed_query, "host", error_string);
const auto port = http::get_query_value_opt<std::string>(
parsed_query, "port", error_string);
const auto status_str = http::get_query_value_opt<std::string>(
parsed_query, "status", error_string);
std::optional<NodeStatus> status;
if (status_str.has_value())
{
// Convert the query argument to a JSON string, try to parse it as
// a NodeStatus, return an error if this doesn't work
try
{
status = nlohmann::json(status_str.value()).get<NodeStatus>();
}
catch (const ccf::JsonParseError& e)
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidQueryParameterValue,
fmt::format(
"Query parameter '{}' is not a valid node status",
status_str.value()));
}
}
GetNodes::Out out;
auto nodes = args.tx.ro(this->network.nodes);
nodes->foreach([this, host, port, status, &out, nodes](
const NodeId& nid, const NodeInfo& ni) {
if (status.has_value() && status.value() != ni.status)
{
return true;
}
// Match on any interface
bool is_matched = false;
for (auto const& interface : ni.rpc_interfaces)
{
const auto& [pub_host, pub_port] =
split_net_address(interface.second.published_address);
if (
(!host.has_value() || host.value() == pub_host) &&
(!port.has_value() || port.value() == pub_port))
{
is_matched = true;
break;
}
}
if (!is_matched)
{
return true;
}
bool is_primary = false;
if (consensus != nullptr)
{
is_primary = consensus->primary() == nid;
}
out.nodes.push_back(
{nid,
ni.status,
is_primary,
ni.rpc_interfaces,
ni.node_data,
nodes->get_version_of_previous_write(nid).value_or(0)});
return true;
});
return make_success(out);
};
make_read_only_endpoint(
"/network/nodes",
HTTP_GET,
json_read_only_adapter(get_nodes),
no_auth_required)
.set_auto_schema<void, GetNodes::Out>()
.add_query_parameter<std::string>(
"host", ccf::endpoints::OptionalParameter)
.add_query_parameter<std::string>(
"port", ccf::endpoints::OptionalParameter)
.add_query_parameter<std::string>(
"status", ccf::endpoints::OptionalParameter)
.install();
auto get_removable_nodes = [this](auto& args, nlohmann::json&&) {
GetNodes::Out out;
auto nodes = args.tx.ro(this->network.nodes);
nodes->foreach(
[this, &out, nodes](const NodeId& node_id, const NodeInfo& ni) {
// Only nodes whose retire_committed status is committed can be
// safely removed, because any primary elected from here on would
// consider them retired, and would consequently not need their
// input in any quorum. We must therefore read the KV at its
// globally committed watermark, for the purpose of this RPC. Since
// this transaction does not perform a write, it is safe to do this.
auto node = nodes->get_globally_committed(node_id);
if (
node.has_value() && node->status == ccf::NodeStatus::RETIRED &&
node->retired_committed)
{
out.nodes.push_back(
{node_id,
node->status,