/
mcbp_validators.cc
2479 lines (2227 loc) · 98.1 KB
/
mcbp_validators.cc
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
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2019-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include "mcbp_validators.h"
#include "buckets.h"
#include "connection.h"
#include "cookie.h"
#include "enginemap.h"
#include "memcached.h"
#include "network_interface_description.h"
#include "subdocument_validators.h"
#include "tls_configuration.h"
#include "xattr/utils.h"
#include <logger/logger.h>
#include <mcbp/protocol/header.h>
#include <memcached/collections.h>
#include <memcached/dcp.h>
#include <memcached/durability_spec.h>
#include <memcached/protocol_binary.h>
#include <nlohmann/json.hpp>
#include <platform/string_hex.h>
#include <utilities/engine_errc_2_mcbp.h>
using cb::mcbp::Status;
static bool is_valid_xattr_blob(Cookie& cookie,
const cb::mcbp::Request& request) {
if (!mcbp::datatype::is_xattr(uint8_t(request.getDatatype()))) {
// no xattr segment
return true;
}
return cb::xattr::validate(cookie.getInflatedInputPayload());
}
bool is_document_key_valid(Cookie& cookie) {
const auto& req = cookie.getRequest();
const auto& key = req.getKey();
if (!cookie.getConnection().isCollectionsSupported()) {
return true;
}
// Note:: key maximum length is checked in McbpValidator::verify_header
// A document key must be 2 bytes minimum
if (key.size() <= 1) {
cookie.setErrorContext("Key length must be >= 2");
return false; // 0 and 1 are invalid
}
// Next the validation depends on the collection-ID, default collection
// has legacy data so has different rules.
auto leb =
cb::mcbp::unsigned_leb128<CollectionIDType>::decodeCanonical(key);
// Failed to decode
if (!leb.second.data()) {
// To get detailed error context, decode via the version which tolerates
// non-canonical encodings but will fail for bad input (no stop-byte)
auto check =
cb::mcbp::unsigned_leb128<CollectionIDType>::decodeNoThrow(key);
// If the decode was fine, the issue is no-stop byte found
if (check.second.data()) {
cookie.setErrorContext("Key contains non-canonical leb128");
} else {
cookie.setErrorContext("No stop-byte found");
}
return false;
}
if (leb.second.empty()) {
cookie.setErrorContext("No logical key found");
return false;
}
// The range of collections permissible on the wire is restricted (no
// internally reserved values are allowed)
if (CollectionID::isReserved(leb.first)) {
cookie.setErrorContext("Invalid collection-id:" +
std::to_string(leb.first));
return false;
}
// The maximum length depends on the collection-ID
const auto maxLen = ((leb.first == CollectionID::Default)
? KEY_MAX_LENGTH
: MaxCollectionsLogicalKeyLen);
bool rv = leb.second.size() <= maxLen;
if (!rv) {
cookie.setErrorContext("Logical key exceeds " + std::to_string(maxLen));
}
return rv;
}
static inline bool may_accept_dcp_deleteV2(const Cookie& cookie) {
return cookie.getConnection().isDcpDeleteV2();
}
static inline std::string get_peer_description(const Cookie& cookie) {
return cookie.getConnection().getDescription();
}
using ExpectedKeyLen = McbpValidator::ExpectedKeyLen;
using ExpectedValueLen = McbpValidator::ExpectedValueLen;
using ExpectedCas = McbpValidator::ExpectedCas;
/**
* Verify the header meets basic sanity checks and fields length
* match the provided expected lengths.
*
* NOTE: the packet framing is already verified _before_ this method
* is called (in Connection::isPacketAvailable())
*/
Status McbpValidator::verify_header(Cookie& cookie,
uint8_t expected_extlen,
ExpectedKeyLen expected_keylen,
ExpectedValueLen expected_valuelen,
ExpectedCas expected_cas,
uint8_t expected_datatype_mask) {
const auto& header = cookie.getHeader();
auto& connection = cookie.getConnection();
if (!mcbp::datatype::is_valid(header.getDatatype())) {
cookie.setErrorContext("Request datatype invalid");
return Status::Einval;
}
if ((expected_extlen == 0) && (header.getExtlen() != 0)) {
cookie.setErrorContext("Request must not include extras");
return Status::Einval;
}
if ((expected_extlen != 0) && (header.getExtlen() != expected_extlen)) {
cookie.setErrorContext("Request must include extras of length " +
std::to_string(expected_extlen));
return Status::Einval;
}
switch (expected_keylen) {
case ExpectedKeyLen::Zero:
if (header.getKeylen() != 0) {
cookie.setErrorContext("Request must not include key");
return Status::Einval;
}
break;
case ExpectedKeyLen::NonZero:
if (header.getKeylen() == 0) {
cookie.setErrorContext("Request must include key");
return Status::Einval;
}
// Fall-through to check against max key length
case ExpectedKeyLen::Any:
const auto maxKeyLen = connection.isCollectionsSupported()
? MaxCollectionsKeyLen
: KEY_MAX_LENGTH;
if (header.getKeylen() > maxKeyLen) {
cookie.setErrorContext("Key length exceeds " +
std::to_string(maxKeyLen));
return cb::mcbp::Status::Einval;
}
break;
}
const auto& request = header.getRequest();
const auto value = request.getValue();
switch (expected_valuelen) {
case ExpectedValueLen::Zero:
if (!value.empty()) {
cookie.setErrorContext("Request must not include value");
return Status::Einval;
}
break;
case ExpectedValueLen::NonZero:
if (value.empty()) {
cookie.setErrorContext("Request must include value");
return Status::Einval;
}
break;
case ExpectedValueLen::Any:
break;
}
switch (expected_cas) {
case ExpectedCas::NotSet:
if (header.getCas() != 0) {
cookie.setErrorContext("Request CAS must not be set");
return Status::Einval;
}
break;
case ExpectedCas::Set:
if (header.getCas() == 0) {
cookie.setErrorContext("Request CAS must be set");
return Status::Einval;
}
break;
case ExpectedCas::Any:
break;
}
if ((~expected_datatype_mask) & header.getDatatype()) {
cookie.setErrorContext("Request datatype invalid");
return Status::Einval;
}
if (!connection.isDatatypeEnabled(header.getDatatype())) {
uint8_t result = 0;
const auto datatypes = header.getDatatype();
for (int ii = 0; ii < 8; ++ii) {
const auto bit = uint8_t(1 << ii);
if ((bit & datatypes) != bit) {
continue;
}
if (mcbp::datatype::is_valid(protocol_binary_datatype_t(ii))) {
if (!connection.isDatatypeEnabled(bit)) {
result |= bit;
}
}
}
cookie.setErrorContext(
"Datatype (" +
mcbp::datatype::to_string(protocol_binary_datatype_t(result)) +
") not enabled for the connection");
return Status::Einval;
}
if (!cookie.inflateInputPayload(header)) {
// Error reason already set
return Status::Einval;
}
if (!is_valid_xattr_blob(cookie, request)) {
cookie.setErrorContext("The provided xattr segment is not valid");
return Status::XattrEinval;
}
// Validate the frame id's
auto status = Status::Success;
auto opcode = request.getClientOpcode();
try {
request.parseFrameExtras([&status, &cookie, &opcode](
cb::mcbp::request::FrameInfoId id,
cb::const_byte_buffer data) -> bool {
switch (id) {
case cb::mcbp::request::FrameInfoId::Barrier:
if (!data.empty()) {
cookie.setErrorContext("Barrier should not contain value");
status = Status::Einval;
// terminate parsing
return false;
} else {
cookie.setBarrier();
}
return true;
case cb::mcbp::request::FrameInfoId::DurabilityRequirement:
try {
cb::durability::Requirements req(data);
if (!cb::mcbp::is_durability_supported(opcode)) {
status = Status::Einval;
cookie.setErrorContext(
R"(The requested command does not support durability requirements)");
// terminate parsing
return false;
}
return true;
} catch (const std::exception& exception) {
// According to the spec the size may be 1 byte
// indicating the level and 2 optional bytes indicating
// the timeout.
if (data.size() == 1 || data.size() == 3) {
status = Status::DurabilityInvalidLevel;
} else {
status = Status::Einval;
}
std::string msg(exception.what());
// trim off the exception prefix
const std::string prefix{"Requirements(): "};
if (msg.find(prefix) == 0) {
msg = msg.substr(prefix.size());
}
cookie.setErrorContext(msg);
return false;
}
case cb::mcbp::request::FrameInfoId::DcpStreamId:
if (data.size() != sizeof(cb::mcbp::DcpStreamId)) {
status = Status::Einval;
cookie.setErrorContext("DcpStreamId invalid size:" +
std::to_string(data.size()));
return false;
}
return true;
case cb::mcbp::request::FrameInfoId::OpenTracingContext:
if (data.empty()) {
status = Status::Einval;
cookie.setErrorContext("OpenTracingContext cannot be empty");
return false;
} else {
// Ideally we should only validate the packet here,
// but given that we've parsed the packet and found all
// the data I need I can might as well store it to avoid
// having to parse it again just to pick out the value
cookie.setOpenTracingContext(data);
}
return true;
case cb::mcbp::request::FrameInfoId::Impersonate:
if (data.empty()) {
cookie.setErrorContext("Impersonated user must be set");
status = Status::Einval;
// terminate parsing
return false;
}
if (data.front() == '^') {
status = cookie.setEffectiveUser(
{std::string{reinterpret_cast<const char*>(
data.data() + 1),
data.size() - 1},
cb::rbac::Domain::External});
} else {
status = cookie.setEffectiveUser(
{std::string{
reinterpret_cast<const char*>(data.data()),
data.size()},
cb::rbac::Domain::Local});
}
return status == Status::Success;
case cb::mcbp::request::FrameInfoId::PreserveTtl:
if (data.empty()) {
if (cb::mcbp::is_preserve_ttl_supported(opcode)) {
cookie.setPreserveTtl(true);
} else {
status = Status::NotSupported;
cookie.setErrorContext(
"This command does not support PreserveTtl");
}
} else {
status = Status::Einval;
cookie.setErrorContext(
"PreserveTtl should not contain value");
}
return status == Status::Success;
case cb::mcbp::request::FrameInfoId::ImpersonateExtraPrivilege:
if (data.empty()) {
cookie.setErrorContext("Privilege name must be set");
status = Status::Einval;
return false;
}
try {
cookie.addImposedUserExtraPrivilege(
cb::rbac::to_privilege(std::string{
reinterpret_cast<const char*>(data.data()),
data.size()}));
} catch (const std::invalid_argument&) {
cookie.setErrorContext("Failed to look up the privilege");
status = Status ::Einval;
return false;
}
return true; // continue parsing
} // switch (id)
status = Status::UnknownFrameInfo;
return false;
});
} catch (const std::overflow_error&) {
status = Status::Einval;
cookie.setErrorContext("Invalid encoding in FrameExtras");
}
if (status != Status::Success) {
return status;
}
// We need to look up SID and CID if this command is related to a
// collection. Looking up the SID caused a perf regression (MB-39594) and
// we don't really need to look up the SID if the privilege context
// include all scopes and collections. If the command is executed with
// a different user we don't have that users privilege context yet, so
// we would have to look up SID and CID (MB-47904)
if (connection.getBucket().type != BucketType::NoBucket &&
cb::mcbp::is_collection_command(request.getClientOpcode()) &&
connection.getBucket().supports(cb::engine::Feature::Collections) &&
(cookie.getPrivilegeContext().hasScopePrivileges() ||
cookie.getEffectiveUser().has_value())) {
// verify that we can map the connection to sid. To make our
// unit tests easier lets go through the connection
auto key = cookie.getRequestKey();
ScopeID sid;
uint64_t manifestUid = 0;
if (key.getCollectionID().isDefaultCollection()) {
sid = ScopeID{ScopeID::Default};
} else {
auto vbid = request.getVBucket();
auto res = connection.getBucket().getEngine().get_scope_id(
cookie, key, vbid);
if (res.result == cb::engine_errc::success) {
manifestUid = res.getManifestId();
sid = res.getScopeId();
} else if (res.result == cb::engine_errc::unknown_collection) {
// Could not get the collection's scope - an unknown collection
// against the manifest with id stored in res.first.
cookie.setUnknownCollectionErrorContext(res.getManifestId());
return Status::UnknownCollection;
} else {
return cb::mcbp::to_status(res.result);
}
}
cookie.setCurrentCollectionInfo(
sid, key.getCollectionID(), manifestUid);
}
return Status::Success;
}
/******************************************************************************
* Package validators *
*****************************************************************************/
/**
* Verify that the cookie meets the common DCP restrictions:
*
* a) The connected engine supports DCP
* b) The connection cannot be set into the unordered execution mode.
*
* @param cookie The command cookie
*/
static Status verify_common_dcp_restrictions(Cookie& cookie) {
const auto& connection = cookie.getConnection();
auto* dcp = connection.getBucket().getDcpIface();
if (!dcp) {
cookie.setErrorContext("Attached bucket does not support DCP");
return Status::NotSupported;
}
if (connection.allowUnorderedExecution()) {
LOG_WARNING(
"DCP on a connection with unordered execution is currently "
"not supported: {}",
get_peer_description(cookie));
cookie.setErrorContext(
"DCP on connections with unordered execution is not supported");
return Status::NotSupported;
}
using cb::mcbp::ClientOpcode;
const auto opcode = cookie.getRequest().getClientOpcode();
if (opcode == ClientOpcode::DcpOpen) {
if (connection.isDCP()) {
LOG_DEBUG("{}: Can't do DCP OPEN twice", cookie.getConnectionId());
cookie.setErrorContext(
"The connection is already opened as a DCP connection");
return Status::Einval;
}
} else if (opcode != ClientOpcode::GetFailoverLog) {
if (!connection.isDCP()) {
LOG_DEBUG("{}: Can't send {} on connection before DCP open",
cookie.getConnectionId(),
to_string(cookie.getRequest().getClientOpcode()));
cookie.setErrorContext(
"The command can only be sent on a DCP connection");
return Status::Einval;
}
}
return Status::Success;
}
static Status dcp_open_validator(Cookie& cookie) {
using cb::mcbp::request::DcpOpenPayload;
auto status = McbpValidator::verify_header(
cookie,
sizeof(DcpOpenPayload),
ExpectedKeyLen::NonZero,
ExpectedValueLen::Any,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES | PROTOCOL_BINARY_DATATYPE_JSON);
if (status != Status::Success) {
return status;
}
// Validate the flags.
const auto mask =
DcpOpenPayload::Producer | DcpOpenPayload::IncludeXattrs |
DcpOpenPayload::NoValue | DcpOpenPayload::IncludeDeleteTimes |
DcpOpenPayload::NoValueWithUnderlyingDatatype |
DcpOpenPayload::PiTR | DcpOpenPayload::IncludeDeletedUserXattrs;
const auto& payload =
cookie.getRequest().getCommandSpecifics<DcpOpenPayload>();
const auto flags = payload.getFlags();
if (flags & ~mask) {
LOG_INFO(
"Client trying to open dcp stream with unknown flags ({:x}) {}",
flags,
get_peer_description(cookie));
cookie.setErrorContext("Request contains invalid flags");
return Status::Einval;
}
if ((flags & DcpOpenPayload::Producer) == 0 &&
(flags & DcpOpenPayload::PiTR) == DcpOpenPayload::PiTR) {
cookie.setErrorContext("PiTR require Producer to be set");
return Status::Einval;
}
if ((flags & DcpOpenPayload::NoValue) &&
(flags & DcpOpenPayload::NoValueWithUnderlyingDatatype)) {
LOG_INFO(
"Invalid flags combination ({:x}) specified for a DCP "
"consumer {} - cannot specify NO_VALUE with "
"NO_VALUE_WITH_UNDERLYING_DATATYPE",
flags,
get_peer_description(cookie));
cookie.setErrorContext(
"Request contains invalid flags combination (NO_VALUE && "
"NO_VALUE_WITH_UNDERLYING_DATATYPE)");
return Status::Einval;
}
if ((flags & DcpOpenPayload::IncludeDeletedUserXattrs) &&
!(flags & DcpOpenPayload::IncludeXattrs)) {
LOG_INFO(
"Invalid DcpOpen flags combination ({:x}) specified for {} - "
"Must specify IncludeXattrs for IncludeDeletedUserXattrs",
flags,
get_peer_description(cookie));
cookie.setErrorContext(
"Request contains invalid flags combination - "
"IncludeDeletedUserXattrs but not IncludeXattrs");
return Status::Einval;
}
// Validate the value. If non-empty must be a JSON payload.
const auto value = cookie.getHeader().getValueString();
const auto datatype = cookie.getHeader().getDatatype();
if (value.empty()) {
if (datatype != PROTOCOL_BINARY_RAW_BYTES) {
cookie.setErrorContext("datatype should be set to RAW");
return Status::Einval;
}
} else {
if (datatype != PROTOCOL_BINARY_DATATYPE_JSON) {
cookie.setErrorContext(
"datatype should be set to JSON for non-empty value");
return Status::Einval;
}
try {
auto json = nlohmann::json::parse(value);
if (!json.is_object()) {
cookie.setErrorContext("value must be JSON of type object");
return Status::Einval;
}
for (const auto& kv : json.items()) {
if (kv.key() == "consumer_name") {
if (flags & DcpOpenPayload::Producer) {
cookie.setErrorContext(
"consumer_name only valid for Consumer "
"connections");
return Status::Einval;
}
if (!kv.value().is_string()) {
cookie.setErrorContext(
"consumer_name must be a string");
return Status::Einval;
}
auto nm = kv.value().get<std::string>();
if (nm.size() > cb::limits::MaxDcpName) {
cookie.setErrorContext(
"consumer_name limit is " +
std::to_string(cb::limits::MaxDcpName) +
" characters");
return Status::Einval;
}
} else {
cookie.setErrorContext("Unsupported JSON property " +
kv.key());
return Status::Einval;
}
}
} catch (const std::exception&) {
cookie.setErrorContext("value is not valid JSON");
return Status::Einval;
}
}
if (size_t(cookie.getHeader().getKeylen()) > cb::limits::MaxDcpName) {
cookie.setErrorContext("Dcp name limit is " +
std::to_string(cb::limits::MaxDcpName) +
" characters");
return Status::Einval;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_add_stream_validator(Cookie& cookie) {
using cb::mcbp::request::DcpAddStreamPayload;
auto status = McbpValidator::verify_header(cookie,
sizeof(DcpAddStreamPayload),
ExpectedKeyLen::Zero,
ExpectedValueLen::Zero,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
auto& req = cookie.getRequest();
const auto& payload = req.getCommandSpecifics<DcpAddStreamPayload>();
const uint32_t flags = payload.getFlags();
const auto mask = DCP_ADD_STREAM_FLAG_TAKEOVER |
DCP_ADD_STREAM_FLAG_DISKONLY |
DCP_ADD_STREAM_FLAG_LATEST |
DCP_ADD_STREAM_ACTIVE_VB_ONLY;
if (flags & ~mask) {
if (flags & DCP_ADD_STREAM_FLAG_NO_VALUE) {
// MB-22525 The NO_VALUE flag should be passed to DCP_OPEN
LOG_INFO("Client trying to add stream with NO VALUE {}",
get_peer_description(cookie));
cookie.setErrorContext(
"DCP_ADD_STREAM_FLAG_NO_VALUE{8} flag is no longer used");
} else {
LOG_INFO("Client trying to add stream with unknown flags ({:x}) {}",
flags,
get_peer_description(cookie));
cookie.setErrorContext("Request contains invalid flags");
}
return Status::Einval;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_close_stream_validator(Cookie& cookie) {
auto status = McbpValidator::verify_header(cookie,
0,
ExpectedKeyLen::Zero,
ExpectedValueLen::Zero,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_get_failover_log_validator(Cookie& cookie) {
auto status = McbpValidator::verify_header(cookie,
0,
ExpectedKeyLen::Zero,
ExpectedValueLen::Zero,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_stream_req_validator(Cookie& cookie) {
auto vlen = cookie.getConnection().isCollectionsSupported()
? ExpectedValueLen::Any
: ExpectedValueLen::Zero;
auto status = McbpValidator::verify_header(
cookie,
sizeof(cb::mcbp::request::DcpStreamReqPayload),
ExpectedKeyLen::Zero,
vlen,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_stream_end_validator(Cookie& cookie) {
auto status = McbpValidator::verify_header(
cookie,
sizeof(cb::mcbp::request::DcpStreamEndPayload),
ExpectedKeyLen::Zero,
ExpectedValueLen::Zero,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_snapshot_marker_validator(Cookie& cookie) {
auto& header = cookie.getHeader();
using cb::mcbp::request::DcpSnapshotMarkerV1Payload;
using cb::mcbp::request::DcpSnapshotMarkerV2_0Value;
using cb::mcbp::request::DcpSnapshotMarkerV2xPayload;
using cb::mcbp::request::DcpSnapshotMarkerV2xVersion;
// Validate our extras length is correct
if (!(header.getExtlen() == sizeof(DcpSnapshotMarkerV1Payload) ||
header.getExtlen() == sizeof(DcpSnapshotMarkerV2xPayload))) {
return Status::Einval;
}
// If v2.x validate the value length is expected
auto expectedValueLen = ExpectedValueLen::Zero;
if (header.getExtlen() == sizeof(DcpSnapshotMarkerV2xPayload)) {
const auto& payload =
header.getRequest()
.getCommandSpecifics<DcpSnapshotMarkerV2xPayload>();
size_t expectedLen = sizeof(DcpSnapshotMarkerV2_0Value);
expectedValueLen = ExpectedValueLen::Any;
if (payload.getVersion() != DcpSnapshotMarkerV2xVersion::Zero) {
cookie.setErrorContext(
"Unsupported dcp snapshot version:" +
std::to_string(uint32_t(payload.getVersion())));
return Status::Einval;
}
if (header.getValue().size() != expectedLen) {
cookie.setErrorContext("valuelen not expected:" +
std::to_string(expectedLen));
return Status::Einval;
}
}
// Pass the extras len in because we will check it manually as it is
// variable length
auto status = McbpValidator::verify_header(cookie,
header.getExtlen(),
ExpectedKeyLen::Zero,
expectedValueLen,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_system_event_validator(Cookie& cookie) {
using cb::mcbp::request::DcpSystemEventPayload;
auto status =
McbpValidator::verify_header(cookie,
sizeof(DcpSystemEventPayload),
ExpectedKeyLen::Any,
ExpectedValueLen::Any,
ExpectedCas::Any,
McbpValidator::AllSupportedDatatypes);
if (status != Status::Success) {
return status;
}
const auto& payload =
cookie.getRequest().getCommandSpecifics<DcpSystemEventPayload>();
if (!payload.isValidEvent()) {
cookie.setErrorContext("Invalid system event id");
return Status::Einval;
}
if (!payload.isValidVersion()) {
cookie.setErrorContext("Invalid system event version");
return Status::Einval;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_mutation_validator(Cookie& cookie) {
using cb::mcbp::request::DcpMutationPayload;
auto status =
McbpValidator::verify_header(cookie,
sizeof(DcpMutationPayload),
ExpectedKeyLen::NonZero,
ExpectedValueLen::Any,
ExpectedCas::Any,
McbpValidator::AllSupportedDatatypes);
if (status != Status::Success) {
return status;
}
if (!is_document_key_valid(cookie)) {
return Status::Einval;
}
const auto& payload =
cookie.getRequest().getCommandSpecifics<DcpMutationPayload>();
if (payload.getBySeqno() == 0) {
cookie.setErrorContext("Invalid seqno(0) for DCP mutation");
return Status::Einval;
}
return verify_common_dcp_restrictions(cookie);
}
/// @return true if the datatype is valid for a deletion
static bool valid_dcp_delete_datatype(protocol_binary_datatype_t datatype) {
// MB-29040: Allowing xattr + JSON. A bug in the producer means
// it may send XATTR|JSON (with snappy possible). These are now allowed
// so rebalance won't be failed and the consumer will sanitise the faulty
// documents.
// MB-31141: Allowing RAW+Snappy. A bug in delWithMeta has allowed us to
// create deletes with a non-zero value tagged as RAW, which when snappy
// is enabled gets DCP shipped as RAW+Snappy.
std::array<const protocol_binary_datatype_t, 6> valid = {
{PROTOCOL_BINARY_RAW_BYTES,
PROTOCOL_BINARY_RAW_BYTES | PROTOCOL_BINARY_DATATYPE_SNAPPY,
PROTOCOL_BINARY_DATATYPE_XATTR,
PROTOCOL_BINARY_DATATYPE_XATTR | PROTOCOL_BINARY_DATATYPE_SNAPPY,
PROTOCOL_BINARY_DATATYPE_XATTR | PROTOCOL_BINARY_DATATYPE_JSON,
PROTOCOL_BINARY_DATATYPE_XATTR | PROTOCOL_BINARY_DATATYPE_SNAPPY |
PROTOCOL_BINARY_DATATYPE_JSON}};
for (auto d : valid) {
if (datatype == d) {
return true;
}
}
return false;
}
static Status dcp_deletion_validator(Cookie& cookie) {
const size_t expectedExtlen =
may_accept_dcp_deleteV2(cookie)
? sizeof(cb::mcbp::request::DcpDeletionV2Payload)
: sizeof(cb::mcbp::request::DcpDeletionV1Payload);
auto status =
McbpValidator::verify_header(cookie,
gsl::narrow<uint8_t>(expectedExtlen),
ExpectedKeyLen::NonZero,
ExpectedValueLen::Any,
ExpectedCas::Any,
McbpValidator::AllSupportedDatatypes);
if (status != Status::Success) {
return status;
}
if (!valid_dcp_delete_datatype(cookie.getHeader().getDatatype())) {
cookie.setErrorContext("Request datatype invalid");
return Status::Einval;
}
if (!is_document_key_valid(cookie)) {
return Status::Einval;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_expiration_validator(Cookie& cookie) {
auto status = McbpValidator::verify_header(
cookie,
sizeof(cb::mcbp::request::DcpExpirationPayload),
ExpectedKeyLen::NonZero,
ExpectedValueLen::Any,
ExpectedCas::Any,
McbpValidator::AllSupportedDatatypes);
if (status != Status::Success) {
return status;
}
if (!is_document_key_valid(cookie)) {
return Status::Einval;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_set_vbucket_state_validator(Cookie& cookie) {
using cb::mcbp::request::DcpSetVBucketState;
auto status = McbpValidator::verify_header(cookie,
sizeof(DcpSetVBucketState),
ExpectedKeyLen::Zero,
ExpectedValueLen::Zero,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
const auto& payload =
cookie.getRequest().getCommandSpecifics<DcpSetVBucketState>();
if (!payload.isValid()) {
cookie.setErrorContext("Request body state invalid");
return Status::Einval;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_noop_validator(Cookie& cookie) {
auto status = McbpValidator::verify_header(cookie,
0,
ExpectedKeyLen::Zero,
ExpectedValueLen::Zero,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_buffer_acknowledgement_validator(Cookie& cookie) {
auto status = McbpValidator::verify_header(
cookie,
sizeof(cb::mcbp::request::DcpBufferAckPayload),
ExpectedKeyLen::Zero,
ExpectedValueLen::Zero,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_control_validator(Cookie& cookie) {
auto status = McbpValidator::verify_header(cookie,
0,
ExpectedKeyLen::NonZero,
ExpectedValueLen::NonZero,
ExpectedCas::Any,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}
static bool isValidDurabilityLevel(cb::durability::Level lvl) {
switch (lvl) {
case cb::durability::Level::None:
return false;
case cb::durability::Level::Majority:
case cb::durability::Level::MajorityAndPersistOnMaster:
case cb::durability::Level::PersistToMajority:
return true;
}
return false;
}
static Status dcp_prepare_validator(Cookie& cookie) {
using cb::mcbp::request::DcpPreparePayload;
auto status =
McbpValidator::verify_header(cookie,
sizeof(DcpPreparePayload),
ExpectedKeyLen::NonZero,
ExpectedValueLen::Any,
ExpectedCas::Set,
McbpValidator::AllSupportedDatatypes);
if (status != Status::Success) {
return status;
}
if (!is_document_key_valid(cookie)) {
return Status::Einval;
}
const auto& payload =
cookie.getRequest().getCommandSpecifics<DcpPreparePayload>();
if (payload.getBySeqno() == 0) {
cookie.setErrorContext("Invalid seqno(0) for DCP prepare");
return Status::Einval;
}
if (!isValidDurabilityLevel(payload.getDurabilityLevel())) {
cookie.setErrorContext("Invalid durability specifier");
return Status::Einval;
}
return verify_common_dcp_restrictions(cookie);
}
static Status dcp_seqno_acknowledged_validator(Cookie& cookie) {
using cb::mcbp::request::DcpSeqnoAcknowledgedPayload;
auto status =
McbpValidator::verify_header(cookie,
sizeof(DcpSeqnoAcknowledgedPayload),
ExpectedKeyLen::Zero,
ExpectedValueLen::Zero,
ExpectedCas::NotSet,
PROTOCOL_BINARY_RAW_BYTES);
if (status != Status::Success) {
return status;
}
return verify_common_dcp_restrictions(cookie);
}