Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring for external auth, vol 1 #63

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 135 additions & 5 deletions src/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use crate::envoy::{RateLimitDescriptor, RateLimitDescriptor_Entry};
use crate::filter::http_context::Filter;
use crate::glob::GlobPattern;
use crate::policy_index::PolicyIndex;
use log::warn;
use crate::utils::tokenize_with_escaping;
use log::{debug, warn};
use proxy_wasm::traits::Context;
use serde::Deserialize;

#[derive(Deserialize, Debug, Clone)]
Expand Down Expand Up @@ -101,15 +105,15 @@ pub struct Rule {

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RateLimitPolicy {
pub struct Policy {
pub name: String,
pub domain: String,
pub service: String,
pub hostnames: Vec<String>,
pub rules: Vec<Rule>,
}

impl RateLimitPolicy {
impl Policy {
#[cfg(test)]
pub fn new(
name: String,
Expand All @@ -118,14 +122,140 @@ impl RateLimitPolicy {
hostnames: Vec<String>,
rules: Vec<Rule>,
) -> Self {
RateLimitPolicy {
Policy {
name,
domain,
service,
hostnames,
rules,
}
}

pub fn build_descriptors(
&self,
filter: &Filter,
) -> protobuf::RepeatedField<RateLimitDescriptor> {
self.rules
.iter()
.filter(|rule: &&Rule| self.filter_rule_by_conditions(filter, &rule.conditions))
// Mapping 1 Rule -> 1 Descriptor
// Filter out empty descriptors
.filter_map(|rule| self.build_single_descriptor(filter, &rule.data))
.collect()
}

fn filter_rule_by_conditions(&self, filter: &Filter, conditions: &[Condition]) -> bool {
if conditions.is_empty() {
// no conditions means matching all the requests.
return true;
}

conditions
.iter()
.any(|condition| self.condition_applies(filter, condition))
}

fn condition_applies(&self, filter: &Filter, condition: &Condition) -> bool {
condition
.all_of
.iter()
.all(|pattern_expression| self.pattern_expression_applies(filter, pattern_expression))
}

fn pattern_expression_applies(&self, filter: &Filter, p_e: &PatternExpression) -> bool {
let attribute_path = tokenize_with_escaping(&p_e.selector, '.', '\\');
// convert a Vec<String> to Vec<&str>
// attribute_path.iter().map(AsRef::as_ref).collect()
let attribute_value = match filter
.get_property(attribute_path.iter().map(AsRef::as_ref).collect())
{
None => {
debug!(
"#{} pattern_expression_applies: selector not found: {}, defaulting to ``",
filter.context_id, p_e.selector
);
"".to_string()
}
// TODO(eastizle): not all fields are strings
// https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes
Some(attribute_bytes) => match String::from_utf8(attribute_bytes) {
Err(e) => {
debug!(
"#{} pattern_expression_applies: failed to parse selector value: {}, error: {}",
filter.context_id, p_e.selector, e
);
return false;
}
Ok(attribute_value) => attribute_value,
},
};
p_e.operator
.eval(p_e.value.as_str(), attribute_value.as_str())
}

fn build_single_descriptor(
&self,
filter: &Filter,
data_list: &[DataItem],
) -> Option<RateLimitDescriptor> {
let mut entries = ::protobuf::RepeatedField::default();

// iterate over data items to allow any data item to skip the entire descriptor
for data in data_list.iter() {
match &data.item {
DataType::Static(static_item) => {
let mut descriptor_entry = RateLimitDescriptor_Entry::new();
descriptor_entry.set_key(static_item.key.to_owned());
descriptor_entry.set_value(static_item.value.to_owned());
entries.push(descriptor_entry);
}
DataType::Selector(selector_item) => {
let descriptor_key = match &selector_item.key {
None => selector_item.selector.to_owned(),
Some(key) => key.to_owned(),
};

let attribute_path = tokenize_with_escaping(&selector_item.selector, '.', '\\');
// convert a Vec<String> to Vec<&str>
// attribute_path.iter().map(AsRef::as_ref).collect()
let value = match filter
.get_property(attribute_path.iter().map(AsRef::as_ref).collect())
{
None => {
debug!(
"#{} build_single_descriptor: selector not found: {}",
filter.context_id, selector_item.selector
);
match &selector_item.default {
None => return None, // skipping the entire descriptor
Some(default_value) => default_value.clone(),
}
}
// TODO(eastizle): not all fields are strings
// https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes
Some(attribute_bytes) => match String::from_utf8(attribute_bytes) {
Err(e) => {
debug!(
"#{} build_single_descriptor: failed to parse selector value: {}, error: {}",
filter.context_id, selector_item.selector, e
);
return None;
}
Ok(attribute_value) => attribute_value,
},
};
let mut descriptor_entry = RateLimitDescriptor_Entry::new();
descriptor_entry.set_key(descriptor_key);
descriptor_entry.set_value(value);
entries.push(descriptor_entry);
}
}
}

let mut res = RateLimitDescriptor::new();
res.set_entries(entries);
Some(res)
}
}

pub struct FilterConfig {
Expand Down Expand Up @@ -168,7 +298,7 @@ pub enum FailureMode {
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PluginConfiguration {
pub rate_limit_policies: Vec<RateLimitPolicy>,
pub rate_limit_policies: Vec<Policy>,
// Deny/Allow request when faced with an irrecoverable failure.
pub failure_mode: FailureMode,
}
Expand Down
2 changes: 1 addition & 1 deletion src/filter.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
mod http_context;
pub(crate) mod http_context;
mod root_context;

#[cfg_attr(
Expand Down
137 changes: 4 additions & 133 deletions src/filter/http_context.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
use crate::configuration::{
Condition, DataItem, DataType, FailureMode, FilterConfig, PatternExpression, RateLimitPolicy,
Rule,
};
use crate::envoy::{
RateLimitDescriptor, RateLimitDescriptor_Entry, RateLimitRequest, RateLimitResponse,
RateLimitResponse_Code,
};
use crate::configuration::{FailureMode, FilterConfig, Policy};
use crate::envoy::{RateLimitRequest, RateLimitResponse, RateLimitResponse_Code};
use crate::filter::http_context::TracingHeader::{Baggage, Traceparent, Tracestate};
use crate::utils::tokenize_with_escaping;
use log::{debug, warn};
use protobuf::Message;
use proxy_wasm::traits::{Context, HttpContext};
Expand Down Expand Up @@ -60,8 +53,8 @@ impl Filter {
}
}

fn process_rate_limit_policy(&self, rlp: &RateLimitPolicy) -> Action {
let descriptors = self.build_descriptors(rlp);
fn process_rate_limit_policy(&self, rlp: &Policy) -> Action {
let descriptors = rlp.build_descriptors(self);
if descriptors.is_empty() {
debug!(
"#{} process_rate_limit_policy: empty descriptors",
Expand Down Expand Up @@ -108,128 +101,6 @@ impl Filter {
}
}

fn build_descriptors(
&self,
rlp: &RateLimitPolicy,
) -> protobuf::RepeatedField<RateLimitDescriptor> {
rlp.rules
.iter()
.filter(|rule: &&Rule| self.filter_rule_by_conditions(&rule.conditions))
// Mapping 1 Rule -> 1 Descriptor
// Filter out empty descriptors
.filter_map(|rule| self.build_single_descriptor(&rule.data))
.collect()
}

fn filter_rule_by_conditions(&self, conditions: &[Condition]) -> bool {
if conditions.is_empty() {
// no conditions is equivalent to matching all the requests.
return true;
}

conditions
.iter()
.any(|condition| self.condition_applies(condition))
}

fn condition_applies(&self, condition: &Condition) -> bool {
condition
.all_of
.iter()
.all(|pattern_expression| self.pattern_expression_applies(pattern_expression))
}

fn pattern_expression_applies(&self, p_e: &PatternExpression) -> bool {
let attribute_path = tokenize_with_escaping(&p_e.selector, '.', '\\');
// convert a Vec<String> to Vec<&str>
// attribute_path.iter().map(AsRef::as_ref).collect()
let attribute_value = match self
.get_property(attribute_path.iter().map(AsRef::as_ref).collect())
{
None => {
debug!(
"#{} pattern_expression_applies: selector not found: {}, defaulting to ``",
self.context_id, p_e.selector
);
"".to_string()
}
// TODO(eastizle): not all fields are strings
// https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes
Some(attribute_bytes) => match String::from_utf8(attribute_bytes) {
Err(e) => {
debug!(
"#{} pattern_expression_applies: failed to parse selector value: {}, error: {}",
self.context_id, p_e.selector, e
);
return false;
}
Ok(attribute_value) => attribute_value,
},
};
p_e.operator
.eval(p_e.value.as_str(), attribute_value.as_str())
}

fn build_single_descriptor(&self, data_list: &[DataItem]) -> Option<RateLimitDescriptor> {
let mut entries = ::protobuf::RepeatedField::default();

// iterate over data items to allow any data item to skip the entire descriptor
for data in data_list.iter() {
match &data.item {
DataType::Static(static_item) => {
let mut descriptor_entry = RateLimitDescriptor_Entry::new();
descriptor_entry.set_key(static_item.key.to_owned());
descriptor_entry.set_value(static_item.value.to_owned());
entries.push(descriptor_entry);
}
DataType::Selector(selector_item) => {
let descriptor_key = match &selector_item.key {
None => selector_item.selector.to_owned(),
Some(key) => key.to_owned(),
};

let attribute_path = tokenize_with_escaping(&selector_item.selector, '.', '\\');
// convert a Vec<String> to Vec<&str>
// attribute_path.iter().map(AsRef::as_ref).collect()
let value = match self
.get_property(attribute_path.iter().map(AsRef::as_ref).collect())
{
None => {
debug!(
"#{} build_single_descriptor: selector not found: {}",
self.context_id, selector_item.selector
);
match &selector_item.default {
None => return None, // skipping the entire descriptor
Some(default_value) => default_value.clone(),
}
}
// TODO(eastizle): not all fields are strings
// https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes
Some(attribute_bytes) => match String::from_utf8(attribute_bytes) {
Err(e) => {
debug!(
"#{} build_single_descriptor: failed to parse selector value: {}, error: {}",
self.context_id, selector_item.selector, e
);
return None;
}
Ok(attribute_value) => attribute_value,
},
};
let mut descriptor_entry = RateLimitDescriptor_Entry::new();
descriptor_entry.set_key(descriptor_key);
descriptor_entry.set_value(value);
entries.push(descriptor_entry);
}
}
}

let mut res = RateLimitDescriptor::new();
res.set_entries(entries);
Some(res)
}

fn handle_error_on_grpc_response(&self) {
match &self.config.failure_mode {
FailureMode::Deny => {
Expand Down
14 changes: 7 additions & 7 deletions src/policy_index.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use radix_trie::Trie;

use crate::configuration::RateLimitPolicy;
use crate::configuration::Policy;

pub struct PolicyIndex {
raw_tree: Trie<String, RateLimitPolicy>,
raw_tree: Trie<String, Policy>,
}

impl PolicyIndex {
Expand All @@ -13,12 +13,12 @@ impl PolicyIndex {
}
}

pub fn insert(&mut self, subdomain: &str, policy: RateLimitPolicy) {
pub fn insert(&mut self, subdomain: &str, policy: Policy) {
let rev = Self::reverse_subdomain(subdomain);
self.raw_tree.insert(rev, policy);
}

pub fn get_longest_match_policy(&self, subdomain: &str) -> Option<&RateLimitPolicy> {
pub fn get_longest_match_policy(&self, subdomain: &str) -> Option<&Policy> {
let rev = Self::reverse_subdomain(subdomain);
self.raw_tree.get_ancestor_value(&rev)
}
Expand All @@ -37,11 +37,11 @@ impl PolicyIndex {

#[cfg(test)]
mod tests {
use crate::configuration::RateLimitPolicy;
use crate::configuration::Policy;
use crate::policy_index::PolicyIndex;

fn build_ratelimit_policy(name: &str) -> RateLimitPolicy {
RateLimitPolicy::new(
fn build_ratelimit_policy(name: &str) -> Policy {
Policy::new(
name.to_owned(),
"".to_owned(),
"".to_owned(),
Expand Down
Loading