forked from microsoft/CCF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.cpp
1960 lines (1743 loc) · 66.4 KB
/
logging.cpp
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.
// This app's includes
#include "logging_schema.h"
// CCF
#include "ccf/app_interface.h"
#include "ccf/common_auth_policies.h"
#include "ccf/crypto/verifier.h"
#include "ccf/ds/hash.h"
#include "ccf/endpoints/authentication/all_of_auth.h"
#include "ccf/historical_queries_adapter.h"
#include "ccf/http_etag.h"
#include "ccf/http_query.h"
#include "ccf/indexing/strategies/seqnos_by_key_bucketed.h"
#include "ccf/indexing/strategy.h"
#include "ccf/json_handler.h"
#include "ccf/version.h"
#include <charconv>
#define FMT_HEADER_ONLY
#include <fmt/format.h>
using namespace std;
using namespace nlohmann;
namespace loggingapp
{
// SNIPPET: table_definition
using RecordsMap = ccf::kv::Map<size_t, string>;
static constexpr auto PUBLIC_RECORDS = "public:records";
static constexpr auto PRIVATE_RECORDS = "records";
// SNIPPET_START: indexing_strategy_definition
using RecordsIndexingStrategy = ccf::indexing::LazyStrategy<
ccf::indexing::strategies::SeqnosByKey_Bucketed<RecordsMap>>;
// SNIPPET_END: indexing_strategy_definition
// SNIPPET_START: custom_identity
struct CustomIdentity : public ccf::AuthnIdentity
{
std::string name;
size_t age;
};
// SNIPPET_END: custom_identity
struct MatchHeaders
{
std::optional<std::string> if_match;
std::optional<std::string> if_none_match;
MatchHeaders(const std::shared_ptr<ccf::RpcContext>& rpc_ctx) :
if_match(rpc_ctx->get_request_header("if-match")),
if_none_match(rpc_ctx->get_request_header("if-none-match"))
{}
bool conflict() const
{
return if_match.has_value() && if_none_match.has_value();
}
bool empty() const
{
return !if_match.has_value() && !if_none_match.has_value();
}
};
// SNIPPET_START: custom_auth_policy
class CustomAuthPolicy : public ccf::AuthnPolicy
{
public:
std::unique_ptr<ccf::AuthnIdentity> authenticate(
ccf::kv::ReadOnlyTx&,
const std::shared_ptr<ccf::RpcContext>& ctx,
std::string& error_reason) override
{
const auto& headers = ctx->get_request_headers();
{
// If a specific header is present, throw an exception to simulate a
// dangerously implemented auth policy
constexpr auto explode_header_key = "x-custom-auth-explode";
const auto explode_header_it = headers.find(explode_header_key);
if (explode_header_it != headers.end())
{
throw std::logic_error(explode_header_it->second);
}
}
constexpr auto name_header_key = "x-custom-auth-name";
const auto name_header_it = headers.find(name_header_key);
if (name_header_it == headers.end())
{
error_reason =
fmt::format("Missing required header {}", name_header_key);
return nullptr;
}
const auto& name = name_header_it->second;
if (name.empty())
{
error_reason = "Name must not be empty";
return nullptr;
}
constexpr auto age_header_key = "x-custom-auth-age";
const auto age_header_it = headers.find(age_header_key);
if (age_header_it == headers.end())
{
error_reason =
fmt::format("Missing required header {}", age_header_key);
return nullptr;
}
const auto& age_s = age_header_it->second;
size_t age;
const auto [p, ec] =
std::from_chars(age_s.data(), age_s.data() + age_s.size(), age);
if (ec != std::errc())
{
error_reason =
fmt::format("Unable to parse age header as a number: {}", age_s);
return nullptr;
}
constexpr auto min_age = 16;
if (age < min_age)
{
error_reason = fmt::format("Caller age must be at least {}", min_age);
return nullptr;
}
auto ident = std::make_unique<CustomIdentity>();
ident->name = name;
ident->age = age;
return ident;
}
std::optional<ccf::OpenAPISecuritySchema> get_openapi_security_schema()
const override
{
// There is no OpenAPI-compliant way to describe this auth scheme, so we
// return nullopt
return std::nullopt;
}
std::string get_security_scheme_name() override
{
return "CustomAuthPolicy";
}
};
// SNIPPET_END: custom_auth_policy
class CommittedRecords : public ccf::indexing::Strategy
{
private:
std::string map_name;
std::map<size_t, std::string> records;
std::mutex txid_lock;
ccf::TxID current_txid = {};
public:
CommittedRecords(
const std::string& map_name_, const ccf::TxID& initial_txid = {}) :
ccf::indexing::Strategy(fmt::format("CommittedRecords {}", map_name_)),
map_name(map_name_),
current_txid(initial_txid)
{}
void handle_committed_transaction(
const ccf::TxID& tx_id, const ccf::kv::ReadOnlyStorePtr& store)
{
std::lock_guard<std::mutex> lock(txid_lock);
auto tx_diff = store->create_tx_diff();
auto m = tx_diff.template diff<RecordsMap>(map_name);
m->foreach([this](const size_t& k, std::optional<std::string> v) -> bool {
if (v.has_value())
{
std::string val = v.value();
records[k] = val;
}
else
{
records.erase(k);
}
return true;
});
current_txid = tx_id;
}
std::optional<ccf::SeqNo> next_requested()
{
std::lock_guard<std::mutex> lock(txid_lock);
return current_txid.seqno + 1;
}
std::optional<std::string> get(size_t id)
{
auto search = records.find(id);
if (search == records.end())
{
return std::nullopt;
}
return search->second;
}
ccf::TxID get_current_txid()
{
std::lock_guard<std::mutex> lock(txid_lock);
return current_txid;
}
};
// SNIPPET: inherit_frontend
class LoggerHandlers : public ccf::UserEndpointRegistry
{
private:
const nlohmann::json record_public_params_schema;
const nlohmann::json record_public_result_schema;
const nlohmann::json get_public_params_schema;
const nlohmann::json get_public_result_schema;
std::shared_ptr<RecordsIndexingStrategy> index_per_public_key = nullptr;
std::shared_ptr<CommittedRecords> committed_records = nullptr;
std::string describe_identity(
ccf::endpoints::EndpointContext& ctx,
const std::unique_ptr<ccf::AuthnIdentity>& caller)
{
if (
auto user_cert_ident =
dynamic_cast<const ccf::UserCertAuthnIdentity*>(caller.get()))
{
auto response = std::string("User TLS cert");
response += fmt::format(
"\nThe caller is a user with ID: {}", user_cert_ident->user_id);
ccf::crypto::Pem user_cert;
if (
get_user_cert_v1(ctx.tx, user_cert_ident->user_id, user_cert) ==
ccf::ApiResult::OK)
{
response +=
fmt::format("\nThe caller's cert is:\n{}", user_cert.str());
}
nlohmann::json user_data = nullptr;
if (
get_user_data_v1(ctx.tx, user_cert_ident->user_id, user_data) ==
ccf::ApiResult::OK)
{
response +=
fmt::format("\nThe caller's user data is: {}", user_data.dump());
}
return response;
}
else if (
auto member_cert_ident =
dynamic_cast<const ccf::MemberCertAuthnIdentity*>(caller.get()))
{
auto response = std::string("Member TLS cert");
response += fmt::format(
"\nThe caller is a member with ID: {}", member_cert_ident->member_id);
ccf::crypto::Pem member_cert;
if (
get_member_cert_v1(
ctx.tx, member_cert_ident->member_id, member_cert) ==
ccf::ApiResult::OK)
{
response +=
fmt::format("\nThe caller's cert is:\n{}", member_cert.str());
}
nlohmann::json member_data = nullptr;
if (
get_member_data_v1(
ctx.tx, member_cert_ident->member_id, member_data) ==
ccf::ApiResult::OK)
{
response += fmt::format(
"\nThe caller's member data is: {}", member_data.dump());
}
return response;
}
else if (
auto jwt_ident =
dynamic_cast<const ccf::JwtAuthnIdentity*>(caller.get()))
{
auto response = std::string("JWT");
response += fmt::format(
"\nThe caller is identified by a JWT issued by: {}",
jwt_ident->key_issuer);
response +=
fmt::format("\nThe JWT header is:\n{}", jwt_ident->header.dump(2));
response +=
fmt::format("\nThe JWT payload is:\n{}", jwt_ident->payload.dump(2));
return response;
}
else if (
auto cose_ident =
dynamic_cast<const ccf::UserCOSESign1AuthnIdentity*>(caller.get()))
{
auto response = std::string("User COSE Sign1");
response += fmt::format(
"\nThe caller is identified by a COSE Sign1 signed by kid: {}",
cose_ident->user_id);
response += fmt::format(
"\nThe caller is identified by a COSE Sign1 with content of size: "
"{}",
cose_ident->content.size());
return response;
}
else if (
auto no_ident =
dynamic_cast<const ccf::EmptyAuthnIdentity*>(caller.get()))
{
return "Unauthenticated";
}
else if (
auto all_of_ident =
dynamic_cast<const ccf::AllOfAuthnIdentity*>(caller.get()))
{
auto response = fmt::format(
"Conjoined auth policy: {}", all_of_ident->get_conjoined_name());
for (const auto& [name, sub_ident] : all_of_ident->identities)
{
response += fmt::format("\n\n{}:\n", name);
response += describe_identity(ctx, sub_ident);
}
return response;
}
else
{
return "";
}
}
std::optional<ccf::TxStatus> get_tx_status(ccf::SeqNo seqno)
{
ccf::ApiResult result;
ccf::View view_of_seqno;
result = get_view_for_seqno_v1(seqno, view_of_seqno);
if (result == ccf::ApiResult::OK)
{
ccf::TxStatus status;
result = get_status_for_txid_v1(view_of_seqno, seqno, status);
if (result == ccf::ApiResult::OK)
{
return status;
}
}
return std::nullopt;
}
static std::optional<std::string> get_scope(auto& ctx)
{
const auto parsed_query =
ccf::http::parse_query(ctx.rpc_ctx->get_request_query());
std::string error_string;
return ccf::http::get_query_value_opt<std::string>(
parsed_query, "scope", error_string);
}
static std::string private_records(auto& ctx)
{
return private_records(get_scope(ctx));
}
static std::string public_records(auto& ctx)
{
return public_records(get_scope(ctx));
}
static std::string private_records(const std::optional<std::string>& scope)
{
return scope.has_value() ? fmt::format("{}-{}", PRIVATE_RECORDS, *scope) :
PRIVATE_RECORDS;
}
static std::string public_records(const std::optional<std::string>& scope)
{
return scope.has_value() ? fmt::format("{}-{}", PUBLIC_RECORDS, *scope) :
PUBLIC_RECORDS;
}
// Wrap all endpoints with trace logging of their invocation
ccf::endpoints::Endpoint make_endpoint(
const std::string& method,
ccf::RESTVerb verb,
const ccf::endpoints::EndpointFunction& f,
const ccf::AuthnPolicies& ap) override
{
return ccf::UserEndpointRegistry::make_endpoint(
method,
verb,
[method, verb, f](ccf::endpoints::EndpointContext& args) {
CCF_APP_TRACE("BEGIN {} {}", verb.c_str(), method);
f(args);
CCF_APP_TRACE("END {} {}", verb.c_str(), method);
},
ap);
}
// Wrap all endpoints with trace logging of their invocation
ccf::endpoints::Endpoint make_endpoint_with_local_commit_handler(
const std::string& method,
ccf::RESTVerb verb,
const ccf::endpoints::EndpointFunction& f,
const ccf::endpoints::LocallyCommittedEndpointFunction& lcf,
const ccf::AuthnPolicies& ap) override
{
return ccf::UserEndpointRegistry::make_endpoint_with_local_commit_handler(
method,
verb,
[method, verb, f](ccf::endpoints::EndpointContext& args) {
CCF_APP_TRACE("BEGIN {} {}", verb.c_str(), method);
f(args);
CCF_APP_TRACE("END {} {}", verb.c_str(), method);
},
[method, verb, lcf](
ccf::endpoints::CommandEndpointContext& args, const ccf::TxID& txid) {
CCF_APP_TRACE(
"BEGIN LOCAL COMMIT HANDLER {} {}", verb.c_str(), method);
lcf(args, txid);
CCF_APP_TRACE(
"END LOCAL COMMIT HANDLER {} {}", verb.c_str(), method);
},
ap);
}
public:
LoggerHandlers(ccf::AbstractNodeContext& context) :
ccf::UserEndpointRegistry(context),
record_public_params_schema(nlohmann::json::parse(j_record_public_in)),
record_public_result_schema(nlohmann::json::parse(j_record_public_out)),
get_public_params_schema(nlohmann::json::parse(j_get_public_in)),
get_public_result_schema(nlohmann::json::parse(j_get_public_out))
{
openapi_info.title = "CCF Sample Logging App";
openapi_info.description =
"This CCF sample app implements a simple logging application, securely "
"recording messages at client-specified IDs. It demonstrates most of "
"the features available to CCF apps.";
openapi_info.document_version = "2.3.1";
index_per_public_key = std::make_shared<RecordsIndexingStrategy>(
PUBLIC_RECORDS, context, 10000, 20);
context.get_indexing_strategies().install_strategy(index_per_public_key);
// According to manual obvervation it's enough to start evicting old
// requests on historical perf test, but not too small to get stuck
// because of a single request being larget than the cache.
constexpr size_t cache_limit = 1024 * 1024 * 10; // MB
context.get_historical_state().set_soft_cache_limit(cache_limit);
const ccf::AuthnPolicies auth_policies = {
ccf::jwt_auth_policy,
ccf::user_cert_auth_policy,
ccf::user_cose_sign1_auth_policy};
// SNIPPET_START: record
auto record = [this](auto& ctx, nlohmann::json&& params) {
// SNIPPET_START: macro_validation_record
const auto in = params.get<LoggingRecord::In>();
// SNIPPET_END: macro_validation_record
if (in.msg.empty())
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidInput,
"Cannot record an empty log message.");
}
// SNIPPET: private_table_access
auto records_handle =
ctx.tx.template rw<RecordsMap>(private_records(ctx));
// SNIPPET_END: private_table_access
records_handle->put(in.id, in.msg);
return ccf::make_success(true);
};
// SNIPPET_END: record
// SNIPPET_START: install_record
make_endpoint(
"/log/private", HTTP_POST, ccf::json_adapter(record), auth_policies)
.set_auto_schema<LoggingRecord::In, bool>()
.install();
// SNIPPET_END: install_record
auto add_txid_in_body_put = [](auto& ctx, const auto& tx_id) {
static constexpr auto CCF_TX_ID = "x-ms-ccf-transaction-id";
ctx.rpc_ctx->set_response_header(CCF_TX_ID, tx_id.to_str());
ctx.rpc_ctx->set_response_status(HTTP_STATUS_OK);
auto out = static_cast<LoggingPut::Out*>(ctx.rpc_ctx->get_user_data());
if (out == nullptr)
{
throw std::runtime_error("didn't set user_data!");
}
out->tx_id = tx_id.to_str();
ctx.rpc_ctx->set_response_body(nlohmann::json(*out).dump());
};
auto record_v2 = [this](auto& ctx, nlohmann::json&& params) {
const auto in = params.get<LoggingRecord::In>();
if (in.msg.empty())
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidInput,
"Cannot record an empty log message.");
}
auto records_handle =
ctx.tx.template rw<RecordsMap>(private_records(ctx));
records_handle->put(in.id, in.msg);
const auto parsed_query =
ccf::http::parse_query(ctx.rpc_ctx->get_request_query());
std::string error_reason;
std::string fail;
ccf::http::get_query_value(parsed_query, "fail", fail, error_reason);
auto out = std::make_shared<LoggingPut::Out>();
out->success = true;
if (fail != "true")
{
ctx.rpc_ctx->set_user_data(out);
}
// return a default value as we'll set the response in the post-commit
// handler
return ccf::make_success(nullptr);
};
make_endpoint_with_local_commit_handler(
"/log/private/anonymous/v2",
HTTP_POST,
ccf::json_adapter(record_v2),
add_txid_in_body_put,
ccf::no_auth_required)
.set_auto_schema<LoggingRecord::In, LoggingPut::Out>()
.install();
// SNIPPET_START: get
auto get = [this](auto& ctx, nlohmann::json&&) {
// Parse id from query
const auto parsed_query =
ccf::http::parse_query(ctx.rpc_ctx->get_request_query());
std::string error_reason;
size_t id;
if (!ccf::http::get_query_value(parsed_query, "id", id, error_reason))
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidQueryParameterValue,
std::move(error_reason));
}
auto records_handle =
ctx.tx.template ro<RecordsMap>(private_records(ctx));
auto record = records_handle->get(id);
if (record.has_value())
{
return ccf::make_success(LoggingGet::Out{record.value()});
}
return ccf::make_error(
HTTP_STATUS_NOT_FOUND,
ccf::errors::ResourceNotFound,
fmt::format("No such record: {}.", id));
};
// SNIPPET_END: get
// SNIPPET_START: install_get
make_read_only_endpoint(
"/log/private",
HTTP_GET,
ccf::json_read_only_adapter(get),
auth_policies)
.set_auto_schema<void, LoggingGet::Out>()
.add_query_parameter<size_t>("id")
.install();
// SNIPPET_END: install_get
make_read_only_endpoint(
"/log/private/backup",
HTTP_GET,
ccf::json_read_only_adapter(get),
auth_policies)
.set_redirection_strategy(ccf::endpoints::RedirectionStrategy::ToBackup)
.set_auto_schema<void, LoggingGet::Out>()
.add_query_parameter<size_t>("id")
.install();
// install the committed index and tell the historical fetcher to keep
// track of deleted keys too, so that the index can observe the deleted
// keys.
auto install_committed_index = [this, &context](auto& ctx) {
if (committed_records != nullptr)
{
ctx.rpc_ctx->set_response_status(HTTP_STATUS_PRECONDITION_FAILED);
ctx.rpc_ctx->set_response_body("Already installed");
return;
}
ccf::View view;
ccf::SeqNo seqno;
auto result = get_last_committed_txid_v1(view, seqno);
if (result != ccf::ApiResult::OK)
{
ctx.rpc_ctx->set_response_status(HTTP_STATUS_INTERNAL_SERVER_ERROR);
ctx.rpc_ctx->set_response_body(fmt::format(
"Failed to retrieve current committed TxID: {}", result));
return;
}
// tracking committed records also wants to track deletes so enable that
// in the historical queries too
context.get_historical_state().track_deletes_on_missing_keys(true);
// Indexing from the start of time may be expensive. Since this is a
// locally-targetted sample, we only index from the _currently_
// committed TxID
committed_records = std::make_shared<CommittedRecords>(
PRIVATE_RECORDS, ccf::TxID{view, seqno});
context.get_indexing_strategies().install_strategy(committed_records);
};
make_command_endpoint(
"/log/private/install_committed_index",
HTTP_POST,
install_committed_index,
ccf::no_auth_required)
.set_auto_schema<void, void>()
.install();
auto uninstall_committed_index = [this, &context](auto& ctx) {
if (committed_records == nullptr)
{
ctx.rpc_ctx->set_response_status(HTTP_STATUS_PRECONDITION_FAILED);
ctx.rpc_ctx->set_response_body("Not currently installed");
return;
}
context.get_indexing_strategies().uninstall_strategy(committed_records);
committed_records = nullptr;
};
make_command_endpoint(
"/log/private/uninstall_committed_index",
HTTP_POST,
uninstall_committed_index,
ccf::no_auth_required)
.set_auto_schema<void, void>()
.install();
auto get_committed = [this](auto& ctx) {
// Parse id from query
const auto parsed_query =
ccf::http::parse_query(ctx.rpc_ctx->get_request_query());
std::string error_reason;
size_t id;
if (!ccf::http::get_query_value(parsed_query, "id", id, error_reason))
{
auto response = nlohmann::json{{
"error",
{
{"code", ccf::errors::InvalidQueryParameterValue},
{"message", std::move(error_reason)},
},
}};
ctx.rpc_ctx->set_response_json(response, HTTP_STATUS_BAD_REQUEST);
return;
}
auto record = committed_records->get(id);
if (record.has_value())
{
nlohmann::json response = LoggingGet::Out{record.value()};
ctx.rpc_ctx->set_response_json(response, HTTP_STATUS_OK);
return;
}
auto response = nlohmann::json{{
"error",
{
{"code", ccf::errors::ResourceNotFound},
{"message", fmt::format("No such record: {}.", id)},
{"current_txid", committed_records->get_current_txid().to_str()},
},
}};
ctx.rpc_ctx->set_response_json(response, HTTP_STATUS_BAD_REQUEST);
};
make_read_only_endpoint(
"/log/private/committed",
HTTP_GET,
get_committed,
ccf::no_auth_required)
.set_auto_schema<void, LoggingGet::Out>()
.add_query_parameter<size_t>("id")
.install();
auto remove = [this](auto& ctx, nlohmann::json&&) {
// Parse id from query
const auto parsed_query =
ccf::http::parse_query(ctx.rpc_ctx->get_request_query());
std::string error_reason;
size_t id;
if (!ccf::http::get_query_value(parsed_query, "id", id, error_reason))
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidQueryParameterValue,
std::move(error_reason));
}
auto records_handle =
ctx.tx.template rw<RecordsMap>(private_records(ctx));
auto had = records_handle->has(id);
records_handle->remove(id);
return ccf::make_success(LoggingRemove::Out{had});
};
make_endpoint(
"/log/private", HTTP_DELETE, ccf::json_adapter(remove), auth_policies)
.set_auto_schema<void, LoggingRemove::Out>()
.add_query_parameter<size_t>("id")
.install();
auto clear = [this](auto& ctx, nlohmann::json&&) {
auto records_handle =
ctx.tx.template rw<RecordsMap>(private_records(ctx));
records_handle->clear();
return ccf::make_success(true);
};
make_endpoint(
"/log/private/all",
HTTP_DELETE,
ccf::json_adapter(clear),
auth_policies)
.set_auto_schema<void, bool>()
.install();
auto count = [this](auto& ctx, nlohmann::json&&) {
auto records_handle =
ctx.tx.template ro<RecordsMap>(private_records(ctx));
return ccf::make_success(records_handle->size());
};
make_endpoint(
"/log/private/count", HTTP_GET, ccf::json_adapter(count), auth_policies)
.set_auto_schema<void, size_t>()
.install();
// SNIPPET_START: record_public
auto record_public = [this](auto& ctx, nlohmann::json&& params) {
const auto in = params.get<LoggingRecord::In>();
if (in.msg.empty())
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidInput,
"Cannot record an empty log message.");
}
// SNIPPET: public_table_access
auto records_handle =
ctx.tx.template rw<RecordsMap>(public_records(ctx));
// SNIPPET_END: public_table_access
const auto id = params["id"].get<size_t>();
// SNIPPET_START: public_table_post_match
MatchHeaders match_headers(ctx.rpc_ctx);
if (match_headers.conflict())
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidHeaderValue,
"Cannot have both If-Match and If-None-Match headers.");
}
// The presence of a Match header requires a read dependency
// to check the value matches the constraint
if (!match_headers.empty())
{
auto current_value = records_handle->get(id);
if (current_value.has_value())
{
ccf::crypto::Sha256Hash value_digest(current_value.value());
auto etag = value_digest.hex_str();
// On a POST operation, If-Match failing or If-None-Match passing
// both return a 412 Precondition Failed to be returned, and no
// side-effect.
if (match_headers.if_match.has_value())
{
ccf::http::Matcher matcher(match_headers.if_match.value());
if (!matcher.matches(etag))
{
return ccf::make_error(
HTTP_STATUS_PRECONDITION_FAILED,
ccf::errors::PreconditionFailed,
"Resource has changed.");
}
}
if (match_headers.if_none_match.has_value())
{
ccf::http::Matcher matcher(match_headers.if_none_match.value());
if (matcher.matches(etag))
{
return ccf::make_error(
HTTP_STATUS_PRECONDITION_FAILED,
ccf::errors::PreconditionFailed,
"Resource has changed.");
}
}
}
}
// SNIPPET_END: public_table_post_match
records_handle->put(id, in.msg);
// SNIPPET_START: set_claims_digest
if (in.record_claim)
{
ctx.rpc_ctx->set_claims_digest(ccf::ClaimsDigest::Digest(in.msg));
}
// SNIPPET_END: set_claims_digest
CCF_APP_INFO("Storing {} = {}", id, in.msg);
// SNIPPET_START: public_table_post_etag
ccf::crypto::Sha256Hash value_digest(in.msg);
// Succesful calls set an ETag
ctx.rpc_ctx->set_response_header("ETag", value_digest.hex_str());
// SNIPPET_END: public_table_post_etag
return ccf::make_success(true);
};
// SNIPPET_END: record_public
make_endpoint(
"/log/public",
HTTP_POST,
ccf::json_adapter(record_public),
auth_policies)
.set_auto_schema<LoggingRecord::In, bool>()
.install();
// SNIPPET_START: get_public
auto get_public = [this](auto& ctx, nlohmann::json&&) {
// Parse id from query
const auto parsed_query =
ccf::http::parse_query(ctx.rpc_ctx->get_request_query());
std::string error_reason;
size_t id;
if (!ccf::http::get_query_value(parsed_query, "id", id, error_reason))
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidQueryParameterValue,
std::move(error_reason));
}
auto public_records_handle =
ctx.tx.template ro<RecordsMap>(public_records(ctx));
auto record = public_records_handle->get(id);
// SNIPPET_START: public_table_get_match
// If there is not value, the response is always Not Found
// regardless of Match headers
if (record.has_value())
{
MatchHeaders match_headers(ctx.rpc_ctx);
if (match_headers.conflict())
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidHeaderValue,
"Cannot have both If-Match and If-None-Match headers.");
}
// If a record is present, compute an Entity Tag, and apply
// If-Match and If-None-Match.
ccf::crypto::Sha256Hash value_digest(record.value());
const auto etag = value_digest.hex_str();
if (match_headers.if_match.has_value())
{
ccf::http::Matcher matcher(match_headers.if_match.value());
if (!matcher.matches(etag))
{
return ccf::make_error(
HTTP_STATUS_PRECONDITION_FAILED,
ccf::errors::PreconditionFailed,
"Resource has changed.");
}
}
// On a GET, If-None-Match passing returns 304 Not Modified
if (match_headers.if_none_match.has_value())
{
ccf::http::Matcher matcher(match_headers.if_none_match.value());
if (matcher.matches(etag))
{
return ccf::make_redirect(HTTP_STATUS_NOT_MODIFIED);
}
}
// Succesful calls set an ETag
ctx.rpc_ctx->set_response_header("ETag", etag);
CCF_APP_INFO("Fetching {} = {}", id, record.value());
return ccf::make_success(LoggingGet::Out{record.value()});
}
// SNIPPET_END: public_table_get_match
CCF_APP_INFO("Fetching - no entry for {}", id);
return ccf::make_error(
HTTP_STATUS_NOT_FOUND,
ccf::errors::ResourceNotFound,
fmt::format("No such record: {}.", id));
};
// SNIPPET_END: get_public
make_read_only_endpoint(
"/log/public",
HTTP_GET,
ccf::json_read_only_adapter(get_public),
auth_policies)
.set_auto_schema<void, LoggingGet::Out>()
.add_query_parameter<size_t>("id")
.install();
make_read_only_endpoint(
"/log/public/backup",
HTTP_GET,
ccf::json_read_only_adapter(get_public),
auth_policies)
.set_redirection_strategy(ccf::endpoints::RedirectionStrategy::ToBackup)
.set_auto_schema<void, LoggingGet::Out>()
.add_query_parameter<size_t>("id")
.install();
auto remove_public = [this](auto& ctx, nlohmann::json&&) {
// Parse id from query
const auto parsed_query =
ccf::http::parse_query(ctx.rpc_ctx->get_request_query());
std::string error_reason;
size_t id;
if (!ccf::http::get_query_value(parsed_query, "id", id, error_reason))
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,
ccf::errors::InvalidQueryParameterValue,
std::move(error_reason));
}
auto records_handle =
ctx.tx.template rw<RecordsMap>(public_records(ctx));
auto current_value = records_handle->get(id);
// SNIPPET_START: public_table_delete_match
// If there is no value, we don't need to look at the Match
// headers to report that the value is deleted (200 OK)
if (current_value.has_value())
{
MatchHeaders match_headers(ctx.rpc_ctx);
if (match_headers.conflict())
{
return ccf::make_error(
HTTP_STATUS_BAD_REQUEST,