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
// Copyright 2020 Tetrate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! `Envoy` `Stream Info API`.

use core::convert::{TryFrom, TryInto};
use std::time::{Duration, SystemTime};

use self::property::{
    Cluster, Connection, Destination, Listener, Plugin, Property, Request, Response, Route, Source,
    Upstream,
};
use crate::error::format_err;
use crate::host::error::function;
use crate::host::{self, ByteString};

pub use self::types::{ResponseFlags, TrafficDirection};

mod property;
mod proxy_wasm;
mod types;

/// An interface of the `Envoy` `Stream Info API`.
///
/// Basic usage of [`StreamInfo`]:
///
/// ```
/// # use envoy_sdk as envoy;
/// # use envoy::host::Result;
/// # fn action() -> Result<()> {
/// use envoy::host::StreamInfo;
///
/// let stream_info = StreamInfo::default();
///
/// let connection_id = stream_info.connection().id()?;
/// let request_id = stream_info.request().id()?;
/// let plugin_name = stream_info.plugin().name()?;
///
/// stream_info.set_stream_property(&["my_extension", "output"], b"property value")?;
/// # Ok(())
/// # }
/// ```
///
/// [`StreamInfo`]: trait.StreamInfo.html
pub trait StreamInfo {
    /// Evaluates value of a given property in the enclosing context.
    ///
    /// * In case [`HttpFilter`], the value will be evaluated in the context of HTTP stream.
    /// * In case [`NetworkFilter`], the value will be evaluated in the context of TCP connection.
    /// * In case [`AccessLogger`], the value will be evaluated in the context of HTTP stream
    ///   or TCP connection that is being logged.
    ///
    /// # Arguments
    ///
    /// * `path` - property path as an array of path segments
    ///
    /// [`HttpFilter`]: ../../extension/filter/http/trait.HttpFilter.html
    /// [`NetworkFilter`]: ../../extension/filter/network/trait.NetworkFilter.html
    /// [`AccessLogger`]: ../../extension/access_logger/trait.AccessLogger.html
    fn stream_property(&self, path: &[&str]) -> host::Result<Option<ByteString>>;

    /// Saves a value in the enclosing context.
    ///
    /// The value will be accessible to other filters on that HTTP stream or TCP connection.
    ///
    /// # Arguments
    ///
    /// * `path`  - property path as an array of path segments
    /// * `value` - an opaque blob of bytes
    fn set_stream_property(&self, path: &[&str], value: &[u8]) -> host::Result<()>;
}

impl dyn StreamInfo {
    /// Returns the default implementation that interacts with `Envoy`
    /// through its [`ABI`].
    ///
    /// [`ABI`]: https://github.com/proxy-wasm/spec
    pub fn default() -> &'static dyn StreamInfo {
        &impls::Host
    }
}

impl<'a> dyn StreamInfo + 'a {
    /// Provides access to `request` properties.
    pub fn request(&'a self) -> RequestInfo<'a> {
        RequestInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `response` properties.
    pub fn response(&'a self) -> ResponseInfo<'a> {
        ResponseInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `connection` properties.
    pub fn connection(&'a self) -> ConnectionInfo<'a> {
        ConnectionInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `upstream` properties.
    pub fn upstream(&'a self) -> UpstreamInfo<'a> {
        UpstreamInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `source` properties.
    pub fn source(&'a self) -> SourceInfo<'a> {
        SourceInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `destination` properties.
    pub fn destination(&'a self) -> DestinationInfo<'a> {
        DestinationInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `listener` properties.
    pub fn listener(&'a self) -> ListenerInfo<'a> {
        ListenerInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `route` properties.
    pub fn route(&'a self) -> RouteInfo<'a> {
        RouteInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `cluster` properties.
    pub fn cluster(&'a self) -> ClusterInfo<'a> {
        ClusterInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }

    /// Provides access to `plugin` properties.
    pub fn plugin(&'a self) -> PluginInfo<'a> {
        PluginInfo {
            stream: StreamInfoAccessor { stream_info: self },
        }
    }
}

/// Provides access to properties of a stream.
struct StreamInfoAccessor<'a> {
    stream_info: &'a dyn StreamInfo,
}

impl<'a> StreamInfoAccessor<'a> {
    fn property<T, W>(&self, prop: &Property<T, W>) -> host::Result<Option<T>>
    where
        T: TryFrom<proxy_wasm::Value<W>, Error = host::Error>,
    {
        if let Some(bytes) = self.stream_info.stream_property(prop.path())? {
            let encoded = proxy_wasm::Value::<W>::new(bytes.into_bytes());
            let decoded: host::Result<T> = encoded.try_into();
            decoded.map(Option::from).map_err(|err| {
                function("env", "proxy_get_property")
                    .into_parse_error(format_err!(
                        "value of property \"{:?}\" is not valid: {:?}",
                        prop.path(),
                        err
                    ))
                    .into()
            })
        } else {
            Ok(None)
        }
    }
}

/// Provides access to `request` properties.
pub struct RequestInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> RequestInfo<'a> {
    /// Returns request header by name.
    pub fn header<K>(&self, name: K) -> host::Result<Option<ByteString>>
    where
        K: AsRef<str>,
    {
        self.stream.property(&Request::header(name.as_ref()))
    }

    /// Returns request ID.
    pub fn id(&self) -> host::Result<Option<String>> {
        self.stream.property(Request::ID)
    }

    /// Returns time of the first byte received.
    pub fn time(&self) -> host::Result<Option<SystemTime>> {
        self.stream.property(Request::TIME)
    }

    /// Returns total duration of the request.
    pub fn duration(&self) -> host::Result<Option<Duration>> {
        self.stream.property(Request::DURATION)
    }

    /// Returns size of the request body.
    pub fn size(&self) -> host::Result<Option<u64>> {
        self.stream.property(Request::SIZE)
    }

    /// Returns total size of the request including the headers.
    pub fn total_size(&self) -> host::Result<Option<u64>> {
        self.stream.property(Request::TOTAL_SIZE)
    }

    /// Returns request protocol e.g. "HTTP/2".
    pub fn protocol(&self) -> host::Result<Option<String>> {
        self.stream.property(Request::PROTOCOL)
    }

    /// Returns the path portion of the URL.
    pub fn path(&self) -> host::Result<Option<String>> {
        self.stream.property(Request::PATH)
    }

    /// Returns the path portion of the URL without the query string.
    pub fn url_path(&self) -> host::Result<Option<String>> {
        self.stream.property(Request::URL_PATH)
    }

    /// Returns the host portion of the URL.
    pub fn host(&self) -> host::Result<Option<String>> {
        self.stream.property(Request::HOST)
    }

    /// Returns request method.
    pub fn method(&self) -> host::Result<Option<String>> {
        self.stream.property(Request::METHOD)
    }

    /// Returns the scheme portion of the URL.
    pub fn scheme(&self) -> host::Result<Option<String>> {
        self.stream.property(Request::SCHEME)
    }

    /// Returns referer request header.
    pub fn referer(&self) -> host::Result<Option<ByteString>> {
        self.stream.property(Request::REFERER)
    }

    /// Returns user agent request header.
    pub fn user_agent(&self) -> host::Result<Option<ByteString>> {
        self.stream.property(Request::USER_AGENT)
    }
}

/// Provides access to `response` properties.
pub struct ResponseInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> ResponseInfo<'a> {
    /// Returns response header by name.
    pub fn header<K>(&self, name: K) -> host::Result<Option<ByteString>>
    where
        K: AsRef<str>,
    {
        self.stream.property(&Response::header(name.as_ref()))
    }

    /// Returns response trailer by name.
    pub fn trailer<K>(&self, name: K) -> host::Result<Option<ByteString>>
    where
        K: AsRef<str>,
    {
        self.stream.property(&Response::trailer(name.as_ref()))
    }

    /// Returns response HTTP status code.
    pub fn status_code(&self) -> host::Result<Option<u16>> {
        self.stream.property(Response::STATUS_CODE)
    }

    /// Returns size of the response body.
    pub fn size(&self) -> host::Result<Option<u64>> {
        self.stream.property(Response::SIZE)
    }

    /// Returns total size of the response including the approximate uncompressed size of the headers and the trailers.
    pub fn total_size(&self) -> host::Result<Option<u64>> {
        self.stream.property(Response::TOTAL_SIZE)
    }

    /// Returns additional details about the response beyond the standard response code.
    pub fn flags(&self) -> host::Result<Option<ResponseFlags>> {
        self.stream.property(Response::FLAGS)
    }

    /// Returns response gRPC status code.
    pub fn grpc_status(&self) -> host::Result<Option<i32>> {
        self.stream.property(Response::GRPC_STATUS)
    }
}

/// Provides access to `connection` properties.
pub struct ConnectionInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

/// Provides access to `TLS` properties of the downstream connection.
pub struct DownstreamConnectionTlsInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> ConnectionInfo<'a> {
    /// Returns connection ID.
    pub fn id(&self) -> host::Result<Option<u64>> {
        self.stream.property(Connection::ID)
    }

    /// Returns whether TLS is applied to the downstream connection and the peer ceritificate is presented.
    pub fn is_mtls(&self) -> host::Result<Option<bool>> {
        self.stream.property(Connection::IS_MTLS)
    }

    /// Returns requested server name in the downstream TLS connection.
    pub fn requested_server_name(&self) -> host::Result<Option<String>> {
        self.stream.property(Connection::REQUESTED_SERVER_NAME)
    }

    /// Provides access to `TLS` properties of the downstream connection.
    pub fn tls(&'a self) -> DownstreamConnectionTlsInfo<'a> {
        DownstreamConnectionTlsInfo {
            stream: StreamInfoAccessor {
                stream_info: self.stream.stream_info,
            },
        }
    }
}

impl<'a> DownstreamConnectionTlsInfo<'a> {
    /// Returns TLS version of the downstream TLS connection.
    pub fn version(&self) -> host::Result<Option<String>> {
        self.stream.property(Connection::TLS_VERSION)
    }

    /// Returns the subject field of the local certificate in the downstream TLS connection..
    pub fn subject_local_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Connection::SUBJECT_LOCAL_CERTIFICATE)
    }

    /// Returns the subject field of the peer certificate in the downstream TLS connection.
    pub fn subject_peer_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Connection::SUBJECT_PEER_CERTIFICATE)
    }

    /// Returns the first URI entry in the SAN field of the local certificate in the downstream TLS connection.
    pub fn uri_san_local_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Connection::URI_SAN_LOCAL_CERTIFICATE)
    }

    /// Returns the first URI entry in the SAN field of the peer certificate in the downstream TLS connection.
    pub fn uri_san_peer_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Connection::URI_SAN_PEER_CERTIFICATE)
    }

    /// Returns the first DNS entry in the SAN field of the local certificate in the downstream TLS connection.
    pub fn dns_san_local_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Connection::DNS_SAN_LOCAL_CERTIFICATE)
    }

    /// Returns the first DNS entry in the SAN field of the peer certificate in the downstream TLS connection.
    pub fn dns_san_peer_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Connection::DNS_SAN_PEER_CERTIFICATE)
    }
}

/// Provides access to `upstream` properties.
pub struct UpstreamInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

/// Provides access to `TLS` properties of the upstream connection.
pub struct UpstreamConnectionTlsInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> UpstreamInfo<'a> {
    /// Returns upstream connection remote address.
    pub fn address(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::ADDRESS)
    }

    /// Returns upstream connection remote port.
    pub fn port(&self) -> host::Result<Option<u32>> {
        self.stream.property(Upstream::PORT)
    }

    /// Returns the local address of the upstream connection.
    pub fn local_address(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::LOCAL_ADDRESS)
    }

    /// Returns the upstream transport failure reason e.g. certificate validation failed.
    pub fn transport_failure_reason(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::TRANSPORT_FAILURE_REASON)
    }

    /// Provides access to `TLS` properties of the upstream connection.
    pub fn tls(&'a self) -> UpstreamConnectionTlsInfo<'a> {
        UpstreamConnectionTlsInfo {
            stream: StreamInfoAccessor {
                stream_info: self.stream.stream_info,
            },
        }
    }
}

impl<'a> UpstreamConnectionTlsInfo<'a> {
    /// Returns TLS version of the upstream TLS connection.
    pub fn version(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::TLS_VERSION)
    }

    /// Returns the subject field of the local certificate in the upstream TLS connection.
    pub fn subject_local_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::SUBJECT_LOCAL_CERTIFICATE)
    }

    /// Returns the subject field of the peer certificate in the upstream TLS connection.
    pub fn subject_peer_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::SUBJECT_PEER_CERTIFICATE)
    }

    /// Returns the first URI entry in the SAN field of the local certificate in the upstream TLS connection.
    pub fn uri_san_local_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::URI_SAN_LOCAL_CERTIFICATE)
    }

    /// Returns the first URI entry in the SAN field of the peer certificate in the upstream TLS connection.
    pub fn uri_san_peer_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::URI_SAN_PEER_CERTIFICATE)
    }

    /// Returns the first DNS entry in the SAN field of the local certificate in the upstream TLS connection.
    pub fn dns_san_local_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::DNS_SAN_LOCAL_CERTIFICATE)
    }

    /// Returns the first DNS entry in the SAN field of the peer certificate in the upstream TLS connection.
    pub fn dns_san_peer_certificate(&self) -> host::Result<Option<String>> {
        self.stream.property(Upstream::DNS_SAN_PEER_CERTIFICATE)
    }
}

/// Provides access to `source` properties.
pub struct SourceInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> SourceInfo<'a> {
    /// Returns downstream connection remote address.
    pub fn address(&self) -> host::Result<Option<String>> {
        self.stream.property(Source::ADDRESS)
    }

    /// Returns downstream connection remote port.
    pub fn port(&self) -> host::Result<Option<u32>> {
        self.stream.property(Source::PORT)
    }
}

/// Provides access to `destination` properties.
pub struct DestinationInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> DestinationInfo<'a> {
    /// Returns downstream connection local address.
    pub fn address(&self) -> host::Result<Option<String>> {
        self.stream.property(Destination::ADDRESS)
    }

    /// Returns downstream connection local port.
    pub fn port(&self) -> host::Result<Option<u32>> {
        self.stream.property(Destination::PORT)
    }
}

/// Provides access to `listener` properties.
pub struct ListenerInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> ListenerInfo<'a> {
    /// Returns traffic direction.
    pub fn traffic_direction(&self) -> host::Result<Option<TrafficDirection>> {
        self.stream.property(Listener::TRAFFIC_DIRECTION)
    }
}

/// Provides access to `cluster` properties.
pub struct ClusterInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> ClusterInfo<'a> {
    /// Returns cluster name.
    pub fn name(&self) -> host::Result<Option<String>> {
        self.stream.property(Cluster::NAME)
    }
}

/// Provides access to `route` properties.
pub struct RouteInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> RouteInfo<'a> {
    /// Returns route name.
    pub fn name(&self) -> host::Result<Option<String>> {
        self.stream.property(Route::NAME)
    }
}

/// Provides access to `plugin` properties.
pub struct PluginInfo<'a> {
    stream: StreamInfoAccessor<'a>,
}

impl<'a> PluginInfo<'a> {
    /// Returns plugin name.
    pub fn name(&self) -> host::Result<Option<String>> {
        self.stream.property(Plugin::NAME)
    }

    /// Returns plugin Root ID.
    pub fn root_id(&self) -> host::Result<Option<String>> {
        self.stream.property(Plugin::ROOT_ID)
    }

    /// Returns plugin VM ID.
    pub fn vm_id(&self) -> host::Result<Option<String>> {
        self.stream.property(Plugin::VM_ID)
    }
}

mod impls {
    use crate::abi::proxy_wasm::hostcalls;

    use super::StreamInfo;
    use crate::host::{self, ByteString};

    pub(super) struct Host;

    impl StreamInfo for Host {
        fn stream_property(&self, path: &[&str]) -> host::Result<Option<ByteString>> {
            hostcalls::get_property(path)
        }

        fn set_stream_property(&self, path: &[&str], value: &[u8]) -> host::Result<()> {
            hostcalls::set_property(path, value)
        }
    }
}