-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathcontext.cc
2026 lines (1874 loc) · 71.7 KB
/
context.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
#include "source/extensions/common/wasm/context.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <ctime>
#include <limits>
#include <memory>
#include <string>
#include "envoy/common/exception.h"
#include "envoy/extensions/wasm/v3/wasm.pb.validate.h"
#include "envoy/grpc/status.h"
#include "envoy/http/codes.h"
#include "envoy/local_info/local_info.h"
#include "envoy/network/filter.h"
#include "envoy/stats/sink.h"
#include "envoy/thread_local/thread_local.h"
#include "source/common/buffer/buffer_impl.h"
#include "source/common/common/assert.h"
#include "source/common/common/empty_string.h"
#include "source/common/common/enum_to_int.h"
#include "source/common/common/logger.h"
#include "source/common/common/safe_memcpy.h"
#include "source/common/http/header_map_impl.h"
#include "source/common/http/message_impl.h"
#include "source/common/http/utility.h"
#include "source/common/tracing/http_tracer_impl.h"
#include "source/extensions/common/wasm/plugin.h"
#include "source/extensions/common/wasm/wasm.h"
#include "source/extensions/filters/common/expr/context.h"
#include "absl/base/casts.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/node_hash_map.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/mutex.h"
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#endif
#include "eval/public/cel_value.h"
#include "eval/public/containers/field_access.h"
#include "eval/public/containers/field_backed_list_impl.h"
#include "eval/public/containers/field_backed_map_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#include "include/proxy-wasm/pairs_util.h"
#include "openssl/bytestring.h"
#include "openssl/hmac.h"
#include "openssl/sha.h"
using proxy_wasm::MetricType;
using proxy_wasm::Word;
namespace Envoy {
namespace Extensions {
namespace Common {
namespace Wasm {
namespace {
// FilterState prefix for CelState values.
constexpr absl::string_view CelStateKeyPrefix = "wasm.";
using HashPolicy = envoy::config::route::v3::RouteAction::HashPolicy;
using CelState = Filters::Common::Expr::CelState;
using CelStatePrototype = Filters::Common::Expr::CelStatePrototype;
Http::RequestTrailerMapPtr buildRequestTrailerMapFromPairs(const Pairs& pairs) {
auto map = Http::RequestTrailerMapImpl::create();
for (auto& p : pairs) {
// Note: because of the lack of a string_view interface for addCopy and
// the lack of an interface to add an entry with an empty value and return
// the entry, there is no efficient way to prevent either a double copy
// of the value or a double lookup of the entry.
map->addCopy(Http::LowerCaseString(std::string(p.first)), std::string(p.second));
}
return map;
}
Http::RequestHeaderMapPtr buildRequestHeaderMapFromPairs(const Pairs& pairs) {
auto map = Http::RequestHeaderMapImpl::create();
for (auto& p : pairs) {
// Note: because of the lack of a string_view interface for addCopy and
// the lack of an interface to add an entry with an empty value and return
// the entry, there is no efficient way to prevent either a double copy
// of the value or a double lookup of the entry.
map->addCopy(Http::LowerCaseString(std::string(p.first)), std::string(p.second));
}
return map;
}
template <typename P> static uint32_t headerSize(const P& p) { return p ? p->size() : 0; }
Upstream::HostDescriptionConstSharedPtr getHost(const StreamInfo::StreamInfo* info) {
if (info && info->upstreamInfo() && info->upstreamInfo().value().get().upstreamHost()) {
return info->upstreamInfo().value().get().upstreamHost();
}
return nullptr;
}
} // namespace
// Test support.
size_t Buffer::size() const {
if (const_buffer_instance_) {
return const_buffer_instance_->length();
}
return proxy_wasm::BufferBase::size();
}
WasmResult Buffer::copyTo(WasmBase* wasm, size_t start, size_t length, uint64_t ptr_ptr,
uint64_t size_ptr) const {
if (const_buffer_instance_) {
uint64_t pointer;
auto p = wasm->allocMemory(length, &pointer);
if (!p) {
return WasmResult::InvalidMemoryAccess;
}
const_buffer_instance_->copyOut(start, length, p);
if (!wasm->wasm_vm()->setWord(ptr_ptr, Word(pointer))) {
return WasmResult::InvalidMemoryAccess;
}
if (!wasm->wasm_vm()->setWord(size_ptr, Word(length))) {
return WasmResult::InvalidMemoryAccess;
}
return WasmResult::Ok;
}
return proxy_wasm::BufferBase::copyTo(wasm, start, length, ptr_ptr, size_ptr);
}
WasmResult Buffer::copyFrom(size_t start, size_t length, std::string_view data) {
if (buffer_instance_) {
if (start == 0) {
if (length != 0) {
buffer_instance_->drain(length);
}
buffer_instance_->prepend(toAbslStringView(data));
return WasmResult::Ok;
} else if (start >= buffer_instance_->length()) {
buffer_instance_->add(toAbslStringView(data));
return WasmResult::Ok;
} else {
return WasmResult::BadArgument;
}
}
if (const_buffer_instance_) { // This buffer is immutable.
return WasmResult::BadArgument;
}
return proxy_wasm::BufferBase::copyFrom(start, length, data);
}
Context::Context() = default;
Context::Context(Wasm* wasm) : ContextBase(wasm) {}
Context::Context(Wasm* wasm, const PluginSharedPtr& plugin) : ContextBase(wasm, plugin) {
root_local_info_ = &std::static_pointer_cast<Plugin>(plugin)->localInfo();
}
Context::Context(Wasm* wasm, uint32_t root_context_id, PluginHandleSharedPtr plugin_handle)
: ContextBase(wasm, root_context_id, plugin_handle), plugin_handle_(plugin_handle) {}
Wasm* Context::wasm() const { return static_cast<Wasm*>(wasm_); }
Plugin* Context::plugin() const { return static_cast<Plugin*>(plugin_.get()); }
Context* Context::rootContext() const { return static_cast<Context*>(root_context()); }
Upstream::ClusterManager& Context::clusterManager() const { return wasm()->clusterManager(); }
void Context::error(std::string_view message) { ENVOY_LOG(trace, message); }
uint64_t Context::getCurrentTimeNanoseconds() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
wasm()->time_source_.systemTime().time_since_epoch())
.count();
}
uint64_t Context::getMonotonicTimeNanoseconds() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
wasm()->time_source_.monotonicTime().time_since_epoch())
.count();
}
void Context::onCloseTCP() {
if (tcp_connection_closed_ || !in_vm_context_created_) {
return;
}
tcp_connection_closed_ = true;
onDone();
onLog();
onDelete();
}
void Context::onResolveDns(uint32_t token, Envoy::Network::DnsResolver::ResolutionStatus status,
std::list<Envoy::Network::DnsResponse>&& response) {
proxy_wasm::DeferAfterCallActions actions(this);
if (wasm()->isFailed() || !wasm()->on_resolve_dns_) {
return;
}
if (status != Network::DnsResolver::ResolutionStatus::Success) {
buffer_.set("");
wasm()->on_resolve_dns_(this, id_, token, 0);
return;
}
// buffer format:
// 4 bytes number of entries = N
// N * 4 bytes TTL for each entry
// N * null-terminated addresses
uint32_t s = 4; // length
for (auto& e : response) {
s += 4; // for TTL
s += e.addrInfo().address_->asStringView().size() + 1; // null terminated.
}
auto buffer = std::unique_ptr<char[]>(new char[s]);
char* b = buffer.get();
uint32_t n = response.size();
safeMemcpyUnsafeDst(b, &n);
b += sizeof(uint32_t);
for (auto& e : response) {
uint32_t ttl = e.addrInfo().ttl_.count();
safeMemcpyUnsafeDst(b, &ttl);
b += sizeof(uint32_t);
};
for (auto& e : response) {
memcpy(b, e.addrInfo().address_->asStringView().data(), // NOLINT(safe-memcpy)
e.addrInfo().address_->asStringView().size());
b += e.addrInfo().address_->asStringView().size();
*b++ = 0;
};
buffer_.set(std::move(buffer), s);
wasm()->on_resolve_dns_(this, id_, token, s);
}
template <typename I> inline uint32_t align(uint32_t i) {
return (i + sizeof(I) - 1) & ~(sizeof(I) - 1);
}
template <typename I> inline char* align(char* p) {
return reinterpret_cast<char*>((reinterpret_cast<uintptr_t>(p) + sizeof(I) - 1) &
~(sizeof(I) - 1));
}
void Context::onStatsUpdate(Envoy::Stats::MetricSnapshot& snapshot) {
proxy_wasm::DeferAfterCallActions actions(this);
if (wasm()->isFailed() || !wasm()->on_stats_update_) {
return;
}
// buffer format:
// uint32 size of block of this type
// uint32 type
// uint32 count
// uint32 length of name
// name
// 8 byte alignment padding
// 8 bytes of absolute value
// 8 bytes of delta (if appropriate, e.g. for counters)
// uint32 size of block of this type
uint32_t counter_block_size = 3 * sizeof(uint32_t); // type of stat
uint32_t num_counters = snapshot.counters().size();
uint32_t counter_type = 1;
uint32_t gauge_block_size = 3 * sizeof(uint32_t); // type of stat
uint32_t num_gauges = snapshot.gauges().size();
uint32_t gauge_type = 2;
uint32_t n = 0;
uint64_t v = 0;
for (const auto& counter : snapshot.counters()) {
if (counter.counter_.get().used()) {
counter_block_size += sizeof(uint32_t) + counter.counter_.get().name().size();
counter_block_size = align<uint64_t>(counter_block_size + 2 * sizeof(uint64_t));
}
}
for (const auto& gauge : snapshot.gauges()) {
if (gauge.get().used()) {
gauge_block_size += sizeof(uint32_t) + gauge.get().name().size();
gauge_block_size += align<uint64_t>(gauge_block_size + sizeof(uint64_t));
}
}
auto buffer = std::unique_ptr<char[]>(new char[counter_block_size + gauge_block_size]);
char* b = buffer.get();
safeMemcpyUnsafeDst(b, &counter_block_size);
b += sizeof(uint32_t);
safeMemcpyUnsafeDst(b, &counter_type);
b += sizeof(uint32_t);
safeMemcpyUnsafeDst(b, &num_counters);
b += sizeof(uint32_t);
for (const auto& counter : snapshot.counters()) {
if (counter.counter_.get().used()) {
n = counter.counter_.get().name().size();
safeMemcpyUnsafeDst(b, &n);
b += sizeof(uint32_t);
memcpy(b, counter.counter_.get().name().data(), // NOLINT(safe-memcpy)
counter.counter_.get().name().size());
b = align<uint64_t>(b + counter.counter_.get().name().size());
v = counter.counter_.get().value();
safeMemcpyUnsafeDst(b, &v);
b += sizeof(uint64_t);
v = counter.delta_;
safeMemcpyUnsafeDst(b, &v);
b += sizeof(uint64_t);
}
}
safeMemcpyUnsafeDst(b, &gauge_block_size);
b += sizeof(uint32_t);
safeMemcpyUnsafeDst(b, &gauge_type);
b += sizeof(uint32_t);
safeMemcpyUnsafeDst(b, &num_gauges);
b += sizeof(uint32_t);
for (const auto& gauge : snapshot.gauges()) {
if (gauge.get().used()) {
n = gauge.get().name().size();
safeMemcpyUnsafeDst(b, &n);
b += sizeof(uint32_t);
memcpy(b, gauge.get().name().data(), gauge.get().name().size()); // NOLINT(safe-memcpy)
b = align<uint64_t>(b + gauge.get().name().size());
v = gauge.get().value();
safeMemcpyUnsafeDst(b, &v);
b += sizeof(uint64_t);
}
}
buffer_.set(std::move(buffer), counter_block_size + gauge_block_size);
wasm()->on_stats_update_(this, id_, counter_block_size + gauge_block_size);
}
// Native serializer carrying over bit representation from CEL value to the extension.
// This implementation assumes that the value type is static and known to the consumer.
WasmResult serializeValue(Filters::Common::Expr::CelValue value, std::string* result) {
using Filters::Common::Expr::CelValue;
int64_t out_int64;
uint64_t out_uint64;
double out_double;
bool out_bool;
const Protobuf::Message* out_message;
switch (value.type()) {
case CelValue::Type::kString:
result->assign(value.StringOrDie().value().data(), value.StringOrDie().value().size());
return WasmResult::Ok;
case CelValue::Type::kBytes:
result->assign(value.BytesOrDie().value().data(), value.BytesOrDie().value().size());
return WasmResult::Ok;
case CelValue::Type::kInt64:
out_int64 = value.Int64OrDie();
result->assign(reinterpret_cast<const char*>(&out_int64), sizeof(int64_t));
return WasmResult::Ok;
case CelValue::Type::kUint64:
out_uint64 = value.Uint64OrDie();
result->assign(reinterpret_cast<const char*>(&out_uint64), sizeof(uint64_t));
return WasmResult::Ok;
case CelValue::Type::kDouble:
out_double = value.DoubleOrDie();
result->assign(reinterpret_cast<const char*>(&out_double), sizeof(double));
return WasmResult::Ok;
case CelValue::Type::kBool:
out_bool = value.BoolOrDie();
result->assign(reinterpret_cast<const char*>(&out_bool), sizeof(bool));
return WasmResult::Ok;
case CelValue::Type::kDuration:
// Warning: loss of precision to nanoseconds
out_int64 = absl::ToInt64Nanoseconds(value.DurationOrDie());
result->assign(reinterpret_cast<const char*>(&out_int64), sizeof(int64_t));
return WasmResult::Ok;
case CelValue::Type::kTimestamp:
// Warning: loss of precision to nanoseconds
out_int64 = absl::ToUnixNanos(value.TimestampOrDie());
result->assign(reinterpret_cast<const char*>(&out_int64), sizeof(int64_t));
return WasmResult::Ok;
case CelValue::Type::kMessage:
out_message = value.MessageOrDie();
result->clear();
if (!out_message || out_message->SerializeToString(result)) {
return WasmResult::Ok;
}
return WasmResult::SerializationFailure;
case CelValue::Type::kMap: {
const auto& map = *value.MapOrDie();
auto keys_list = map.ListKeys();
if (!keys_list.ok()) {
return WasmResult::SerializationFailure;
}
const auto& keys = *keys_list.value();
std::vector<std::pair<std::string, std::string>> pairs(map.size(), std::make_pair("", ""));
for (auto i = 0; i < map.size(); i++) {
if (serializeValue(keys[i], &pairs[i].first) != WasmResult::Ok) {
return WasmResult::SerializationFailure;
}
if (serializeValue(map[keys[i]].value(), &pairs[i].second) != WasmResult::Ok) {
return WasmResult::SerializationFailure;
}
}
auto size = proxy_wasm::PairsUtil::pairsSize(pairs);
// prevent string inlining which violates byte alignment
result->resize(std::max(size, static_cast<size_t>(30)));
if (!proxy_wasm::PairsUtil::marshalPairs(pairs, result->data(), size)) {
return WasmResult::SerializationFailure;
}
result->resize(size);
return WasmResult::Ok;
}
case CelValue::Type::kList: {
const auto& list = *value.ListOrDie();
std::vector<std::pair<std::string, std::string>> pairs(list.size(), std::make_pair("", ""));
for (auto i = 0; i < list.size(); i++) {
if (serializeValue(list[i], &pairs[i].first) != WasmResult::Ok) {
return WasmResult::SerializationFailure;
}
}
auto size = proxy_wasm::PairsUtil::pairsSize(pairs);
// prevent string inlining which violates byte alignment
if (size < 30) {
result->reserve(30);
}
result->resize(size);
if (!proxy_wasm::PairsUtil::marshalPairs(pairs, result->data(), size)) {
return WasmResult::SerializationFailure;
}
return WasmResult::Ok;
}
default:
break;
}
return WasmResult::SerializationFailure;
}
#define PROPERTY_TOKENS(_f) \
_f(NODE) _f(LISTENER_DIRECTION) _f(LISTENER_METADATA) _f(CLUSTER_NAME) _f(CLUSTER_METADATA) \
_f(ROUTE_NAME) _f(ROUTE_METADATA) _f(PLUGIN_NAME) _f(UPSTREAM_HOST_METADATA) \
_f(PLUGIN_ROOT_ID) _f(PLUGIN_VM_ID) _f(CONNECTION_ID)
static inline std::string downCase(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
return s;
}
#define _DECLARE(_t) _t,
enum class PropertyToken { PROPERTY_TOKENS(_DECLARE) };
#undef _DECLARE
#define _PAIR(_t) {downCase(#_t), PropertyToken::_t},
static absl::flat_hash_map<std::string, PropertyToken> property_tokens = {PROPERTY_TOKENS(_PAIR)};
#undef _PAIR
absl::optional<google::api::expr::runtime::CelValue>
Context::FindValue(absl::string_view name, Protobuf::Arena* arena) const {
return findValue(name, arena, false);
}
absl::optional<google::api::expr::runtime::CelValue>
Context::findValue(absl::string_view name, Protobuf::Arena* arena, bool last) const {
using google::api::expr::runtime::CelProtoWrapper;
using google::api::expr::runtime::CelValue;
const StreamInfo::StreamInfo* info = getConstRequestStreamInfo();
// In order to delegate to the StreamActivation method, we have to set the
// context properties to match the Wasm context properties in all callbacks
// (e.g. onLog or onEncodeHeaders) for the duration of the call.
if (root_local_info_) {
local_info_ = root_local_info_;
} else if (plugin_) {
local_info_ = &plugin()->localInfo();
}
activation_info_ = info;
activation_request_headers_ = request_headers_ ? request_headers_ : access_log_request_headers_;
activation_response_headers_ =
response_headers_ ? response_headers_ : access_log_response_headers_;
activation_response_trailers_ =
response_trailers_ ? response_trailers_ : access_log_response_trailers_;
auto value = StreamActivation::FindValue(name, arena);
resetActivation();
if (value) {
return value;
}
// Convert into a dense token to enable a jump table implementation.
auto part_token = property_tokens.find(name);
if (part_token == property_tokens.end()) {
if (info) {
std::string key = absl::StrCat(CelStateKeyPrefix, name);
const CelState* state = info->filterState().getDataReadOnly<CelState>(key);
if (state == nullptr) {
if (info->upstreamInfo().has_value() &&
info->upstreamInfo().value().get().upstreamFilterState() != nullptr) {
state =
info->upstreamInfo().value().get().upstreamFilterState()->getDataReadOnly<CelState>(
key);
}
}
if (state != nullptr) {
return state->exprValue(arena, last);
}
}
return {};
}
switch (part_token->second) {
case PropertyToken::CONNECTION_ID: {
auto conn = getConnection();
if (conn) {
return CelValue::CreateUint64(conn->id());
}
break;
}
case PropertyToken::NODE:
if (root_local_info_) {
return CelProtoWrapper::CreateMessage(&root_local_info_->node(), arena);
} else if (plugin_) {
return CelProtoWrapper::CreateMessage(&plugin()->localInfo().node(), arena);
}
break;
case PropertyToken::LISTENER_DIRECTION:
if (plugin_) {
return CelValue::CreateInt64(plugin()->direction());
}
break;
case PropertyToken::LISTENER_METADATA:
if (plugin_) {
return CelProtoWrapper::CreateMessage(plugin()->listenerMetadata(), arena);
}
break;
case PropertyToken::CLUSTER_NAME:
if (getHost(info)) {
return CelValue::CreateString(&getHost(info)->cluster().name());
} else if (info && info->route() && info->route()->routeEntry()) {
return CelValue::CreateString(&info->route()->routeEntry()->clusterName());
} else if (info && info->upstreamClusterInfo().has_value() &&
info->upstreamClusterInfo().value()) {
return CelValue::CreateString(&info->upstreamClusterInfo().value()->name());
}
break;
case PropertyToken::CLUSTER_METADATA:
if (getHost(info)) {
return CelProtoWrapper::CreateMessage(&getHost(info)->cluster().metadata(), arena);
} else if (info && info->upstreamClusterInfo().has_value() &&
info->upstreamClusterInfo().value()) {
return CelProtoWrapper::CreateMessage(&info->upstreamClusterInfo().value()->metadata(),
arena);
}
break;
case PropertyToken::UPSTREAM_HOST_METADATA:
if (getHost(info)) {
return CelProtoWrapper::CreateMessage(getHost(info)->metadata().get(), arena);
}
break;
case PropertyToken::ROUTE_NAME:
if (info) {
return CelValue::CreateString(&info->getRouteName());
}
break;
case PropertyToken::ROUTE_METADATA:
if (info && info->route()) {
return CelProtoWrapper::CreateMessage(&info->route()->metadata(), arena);
}
break;
case PropertyToken::PLUGIN_NAME:
if (plugin_) {
return CelValue::CreateStringView(plugin()->name_);
}
break;
case PropertyToken::PLUGIN_ROOT_ID:
return CelValue::CreateStringView(toAbslStringView(root_id()));
case PropertyToken::PLUGIN_VM_ID:
return CelValue::CreateStringView(toAbslStringView(wasm()->vm_id()));
}
return {};
}
WasmResult Context::getProperty(std::string_view path, std::string* result) {
using google::api::expr::runtime::CelValue;
bool first = true;
CelValue value;
Protobuf::Arena arena;
size_t start = 0;
while (true) {
if (start >= path.size()) {
break;
}
size_t end = path.find('\0', start);
if (end == absl::string_view::npos) {
end = start + path.size();
}
auto part = path.substr(start, end - start);
start = end + 1;
if (first) {
// top-level identifier
first = false;
auto top_value = findValue(toAbslStringView(part), &arena, start >= path.size());
if (!top_value.has_value()) {
return WasmResult::NotFound;
}
value = top_value.value();
} else if (value.IsMap()) {
auto& map = *value.MapOrDie();
auto field = map[CelValue::CreateStringView(toAbslStringView(part))];
if (!field.has_value()) {
return WasmResult::NotFound;
}
value = field.value();
} else if (value.IsMessage()) {
auto msg = value.MessageOrDie();
if (msg == nullptr) {
return WasmResult::NotFound;
}
const Protobuf::Descriptor* desc = msg->GetDescriptor();
const Protobuf::FieldDescriptor* field_desc = desc->FindFieldByName(std::string(part));
if (field_desc == nullptr) {
return WasmResult::NotFound;
}
if (field_desc->is_map()) {
value = CelValue::CreateMap(
Protobuf::Arena::Create<google::api::expr::runtime::FieldBackedMapImpl>(
&arena, msg, field_desc, &arena));
} else if (field_desc->is_repeated()) {
value = CelValue::CreateList(
Protobuf::Arena::Create<google::api::expr::runtime::FieldBackedListImpl>(
&arena, msg, field_desc, &arena));
} else {
auto status =
google::api::expr::runtime::CreateValueFromSingleField(msg, field_desc, &arena, &value);
if (!status.ok()) {
return WasmResult::InternalFailure;
}
}
} else if (value.IsList()) {
auto& list = *value.ListOrDie();
int idx = 0;
if (!absl::SimpleAtoi(toAbslStringView(part), &idx)) {
return WasmResult::NotFound;
}
if (idx < 0 || idx >= list.size()) {
return WasmResult::NotFound;
}
value = list[idx];
} else {
return WasmResult::NotFound;
}
}
return serializeValue(value, result);
}
// Header/Trailer/Metadata Maps.
Http::HeaderMap* Context::getMap(WasmHeaderMapType type) {
switch (type) {
case WasmHeaderMapType::RequestHeaders:
return request_headers_;
case WasmHeaderMapType::RequestTrailers:
if (request_trailers_ == nullptr && request_body_buffer_ && end_of_stream_ &&
decoder_callbacks_) {
request_trailers_ = &decoder_callbacks_->addDecodedTrailers();
}
return request_trailers_;
case WasmHeaderMapType::ResponseHeaders:
return response_headers_;
case WasmHeaderMapType::ResponseTrailers:
if (response_trailers_ == nullptr && response_body_buffer_ && end_of_stream_ &&
encoder_callbacks_) {
response_trailers_ = &encoder_callbacks_->addEncodedTrailers();
}
return response_trailers_;
default:
return nullptr;
}
}
const Http::HeaderMap* Context::getConstMap(WasmHeaderMapType type) {
switch (type) {
case WasmHeaderMapType::RequestHeaders:
if (access_log_phase_) {
return access_log_request_headers_;
}
return request_headers_;
case WasmHeaderMapType::RequestTrailers:
if (access_log_phase_) {
return nullptr;
}
return request_trailers_;
case WasmHeaderMapType::ResponseHeaders:
if (access_log_phase_) {
return access_log_response_headers_;
}
return response_headers_;
case WasmHeaderMapType::ResponseTrailers:
if (access_log_phase_) {
return access_log_response_trailers_;
}
return response_trailers_;
case WasmHeaderMapType::GrpcReceiveInitialMetadata:
return rootContext()->grpc_receive_initial_metadata_.get();
case WasmHeaderMapType::GrpcReceiveTrailingMetadata:
return rootContext()->grpc_receive_trailing_metadata_.get();
case WasmHeaderMapType::HttpCallResponseHeaders: {
Envoy::Http::ResponseMessagePtr* response = rootContext()->http_call_response_;
if (response) {
return &(*response)->headers();
}
return nullptr;
}
case WasmHeaderMapType::HttpCallResponseTrailers: {
Envoy::Http::ResponseMessagePtr* response = rootContext()->http_call_response_;
if (response) {
return (*response)->trailers();
}
return nullptr;
}
}
IS_ENVOY_BUG("unexpected");
return nullptr;
}
WasmResult Context::addHeaderMapValue(WasmHeaderMapType type, std::string_view key,
std::string_view value) {
auto map = getMap(type);
if (!map) {
return WasmResult::BadArgument;
}
const Http::LowerCaseString lower_key{std::string(key)};
map->addCopy(lower_key, std::string(value));
if (type == WasmHeaderMapType::RequestHeaders) {
clearRouteCache();
}
return WasmResult::Ok;
}
WasmResult Context::getHeaderMapValue(WasmHeaderMapType type, std::string_view key,
std::string_view* value) {
auto map = getConstMap(type);
if (!map) {
if (access_log_phase_) {
// Maps might point to nullptr in the access log phase.
if (wasm()->abiVersion() == proxy_wasm::AbiVersion::ProxyWasm_0_1_0) {
*value = "";
return WasmResult::Ok;
} else {
return WasmResult::NotFound;
}
}
// Requested map type is not currently available.
return WasmResult::BadArgument;
}
const Http::LowerCaseString lower_key{std::string(key)};
const auto entry = map->get(lower_key);
if (entry.empty()) {
if (wasm()->abiVersion() == proxy_wasm::AbiVersion::ProxyWasm_0_1_0) {
*value = "";
return WasmResult::Ok;
} else {
return WasmResult::NotFound;
}
}
// TODO(kyessenov, PiotrSikora): This needs to either return a concatenated list of values, or
// the ABI needs to be changed to return multiple values. This is a potential security issue.
*value = toStdStringView(entry[0]->value().getStringView());
return WasmResult::Ok;
}
Pairs headerMapToPairs(const Http::HeaderMap* map) {
if (!map) {
return {};
}
Pairs pairs;
pairs.reserve(map->size());
map->iterate([&pairs](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
pairs.push_back(std::make_pair(toStdStringView(header.key().getStringView()),
toStdStringView(header.value().getStringView())));
return Http::HeaderMap::Iterate::Continue;
});
return pairs;
}
WasmResult Context::getHeaderMapPairs(WasmHeaderMapType type, Pairs* result) {
*result = headerMapToPairs(getConstMap(type));
return WasmResult::Ok;
}
WasmResult Context::setHeaderMapPairs(WasmHeaderMapType type, const Pairs& pairs) {
auto map = getMap(type);
if (!map) {
return WasmResult::BadArgument;
}
std::vector<std::string> keys;
map->iterate([&keys](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
keys.push_back(std::string(header.key().getStringView()));
return Http::HeaderMap::Iterate::Continue;
});
for (auto& k : keys) {
const Http::LowerCaseString lower_key{k};
map->remove(lower_key);
}
for (auto& p : pairs) {
const Http::LowerCaseString lower_key{std::string(p.first)};
map->addCopy(lower_key, std::string(p.second));
}
if (type == WasmHeaderMapType::RequestHeaders) {
clearRouteCache();
}
return WasmResult::Ok;
}
WasmResult Context::removeHeaderMapValue(WasmHeaderMapType type, std::string_view key) {
auto map = getMap(type);
if (!map) {
return WasmResult::BadArgument;
}
const Http::LowerCaseString lower_key{std::string(key)};
map->remove(lower_key);
if (type == WasmHeaderMapType::RequestHeaders) {
clearRouteCache();
}
return WasmResult::Ok;
}
WasmResult Context::replaceHeaderMapValue(WasmHeaderMapType type, std::string_view key,
std::string_view value) {
auto map = getMap(type);
if (!map) {
return WasmResult::BadArgument;
}
const Http::LowerCaseString lower_key{std::string(key)};
map->setCopy(lower_key, toAbslStringView(value));
if (type == WasmHeaderMapType::RequestHeaders) {
clearRouteCache();
}
return WasmResult::Ok;
}
WasmResult Context::getHeaderMapSize(WasmHeaderMapType type, uint32_t* result) {
auto map = getMap(type);
if (!map) {
return WasmResult::BadArgument;
}
*result = map->byteSize();
return WasmResult::Ok;
}
// Buffer
BufferInterface* Context::getBuffer(WasmBufferType type) {
Envoy::Http::ResponseMessagePtr* response = nullptr;
switch (type) {
case WasmBufferType::CallData:
// Set before the call.
return &buffer_;
case WasmBufferType::VmConfiguration:
return buffer_.set(wasm()->vm_configuration());
case WasmBufferType::PluginConfiguration:
if (temp_plugin_) {
return buffer_.set(temp_plugin_->plugin_configuration_);
}
return nullptr;
case WasmBufferType::HttpRequestBody:
if (buffering_request_body_ && decoder_callbacks_) {
// We need the mutable version, so capture it using a callback.
// TODO: consider adding a mutableDecodingBuffer() interface.
::Envoy::Buffer::Instance* buffer_instance{};
decoder_callbacks_->modifyDecodingBuffer(
[&buffer_instance](::Envoy::Buffer::Instance& buffer) { buffer_instance = &buffer; });
return buffer_.set(buffer_instance);
}
return buffer_.set(request_body_buffer_);
case WasmBufferType::HttpResponseBody:
if (buffering_response_body_ && encoder_callbacks_) {
// TODO: consider adding a mutableDecodingBuffer() interface.
::Envoy::Buffer::Instance* buffer_instance{};
encoder_callbacks_->modifyEncodingBuffer(
[&buffer_instance](::Envoy::Buffer::Instance& buffer) { buffer_instance = &buffer; });
return buffer_.set(buffer_instance);
}
return buffer_.set(response_body_buffer_);
case WasmBufferType::NetworkDownstreamData:
return buffer_.set(network_downstream_data_buffer_);
case WasmBufferType::NetworkUpstreamData:
return buffer_.set(network_upstream_data_buffer_);
case WasmBufferType::HttpCallResponseBody:
response = rootContext()->http_call_response_;
if (response) {
auto& body = (*response)->body();
return buffer_.set(
std::string_view(static_cast<const char*>(body.linearize(body.length())), body.length()));
}
return nullptr;
case WasmBufferType::GrpcReceiveBuffer:
return buffer_.set(rootContext()->grpc_receive_buffer_.get());
default:
return nullptr;
}
}
void Context::onDownstreamConnectionClose(CloseType close_type) {
ContextBase::onDownstreamConnectionClose(close_type);
downstream_closed_ = true;
onCloseTCP();
}
void Context::onUpstreamConnectionClose(CloseType close_type) {
ContextBase::onUpstreamConnectionClose(close_type);
upstream_closed_ = true;
if (downstream_closed_) {
onCloseTCP();
}
}
// Async call via HTTP
WasmResult Context::httpCall(std::string_view cluster, const Pairs& request_headers,
std::string_view request_body, const Pairs& request_trailers,
int timeout_milliseconds, uint32_t* token_ptr) {
if (timeout_milliseconds < 0) {
return WasmResult::BadArgument;
}
auto cluster_string = std::string(cluster);
const auto thread_local_cluster = clusterManager().getThreadLocalCluster(cluster_string);
if (thread_local_cluster == nullptr) {
return WasmResult::BadArgument;
}
Http::RequestMessagePtr message(
new Http::RequestMessageImpl(buildRequestHeaderMapFromPairs(request_headers)));
// Check that we were provided certain headers.
if (message->headers().Path() == nullptr || message->headers().Method() == nullptr ||
message->headers().Host() == nullptr) {
return WasmResult::BadArgument;
}
if (!request_body.empty()) {
message->body().add(toAbslStringView(request_body));
message->headers().setContentLength(request_body.size());
}
if (!request_trailers.empty()) {
message->trailers(buildRequestTrailerMapFromPairs(request_trailers));
}
absl::optional<std::chrono::milliseconds> timeout;
if (timeout_milliseconds > 0) {
timeout = std::chrono::milliseconds(timeout_milliseconds);
}
uint32_t token = wasm()->nextHttpCallId();
auto& handler = http_request_[token];
handler.context_ = this;
handler.token_ = token;
// set default hash policy to be based on :authority to enable consistent hash
Http::AsyncClient::RequestOptions options;
options.setTimeout(timeout);
Protobuf::RepeatedPtrField<HashPolicy> hash_policy;
hash_policy.Add()->mutable_header()->set_header_name(Http::Headers::get().Host.get());
options.setHashPolicy(hash_policy);
options.setSendXff(false);
auto http_request =
thread_local_cluster->httpAsyncClient().send(std::move(message), handler, options);
if (!http_request) {
http_request_.erase(token);
return WasmResult::InternalFailure;
}
handler.request_ = http_request;
*token_ptr = token;
return WasmResult::Ok;
}
WasmResult Context::grpcCall(std::string_view grpc_service, std::string_view service_name,
std::string_view method_name, const Pairs& initial_metadata,
std::string_view request, std::chrono::milliseconds timeout,
uint32_t* token_ptr) {
GrpcService service_proto;
if (!service_proto.ParseFromArray(grpc_service.data(), grpc_service.size())) {
auto cluster_name = std::string(grpc_service.substr(0, grpc_service.size()));
const auto thread_local_cluster = clusterManager().getThreadLocalCluster(cluster_name);
if (thread_local_cluster == nullptr) {
// TODO(shikugawa): The reason to keep return status as `BadArgument` is not to force
// callers to change their own codebase with ABI 0.1.x. We should treat this failure as
// `BadArgument` after ABI 0.2.x will have released.
return WasmResult::ParseFailure;
}
service_proto.mutable_envoy_grpc()->set_cluster_name(cluster_name);
}
uint32_t token = wasm()->nextGrpcCallId();
auto& handler = grpc_call_request_[token];
handler.context_ = this;
handler.token_ = token;
auto client_or_error = clusterManager().grpcAsyncClientManager().getOrCreateRawAsyncClient(
service_proto, *wasm()->scope_, true /* skip_cluster_check */);
if (!client_or_error.status().ok()) {