-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathattribute.rs
277 lines (254 loc) · 9.42 KB
/
attribute.rs
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
use crate::data::property::Path;
use crate::data::PropertyPath;
use chrono::{DateTime, FixedOffset};
use log::{debug, error};
use protobuf::well_known_types::Struct;
use proxy_wasm::hostcalls;
pub const KUADRANT_NAMESPACE: &str = "kuadrant";
pub trait AttributeValue {
fn parse(raw_attribute: Vec<u8>) -> Result<Self, String>
where
Self: Sized;
}
impl AttributeValue for String {
fn parse(raw_attribute: Vec<u8>) -> Result<Self, String> {
String::from_utf8(raw_attribute).map_err(|err| {
format!(
"parse: failed to parse selector String value, error: {}",
err
)
})
}
}
impl AttributeValue for i64 {
fn parse(raw_attribute: Vec<u8>) -> Result<Self, String> {
if raw_attribute.len() != 8 {
return Err(format!(
"parse: Int value expected to be 8 bytes, but got {}",
raw_attribute.len()
));
}
Ok(i64::from_le_bytes(
raw_attribute[..8]
.try_into()
.expect("This has to be 8 bytes long!"),
))
}
}
impl AttributeValue for u64 {
fn parse(raw_attribute: Vec<u8>) -> Result<Self, String> {
if raw_attribute.len() != 8 {
return Err(format!(
"parse: UInt value expected to be 8 bytes, but got {}",
raw_attribute.len()
));
}
Ok(u64::from_le_bytes(
raw_attribute[..8]
.try_into()
.expect("This has to be 8 bytes long!"),
))
}
}
impl AttributeValue for f64 {
fn parse(raw_attribute: Vec<u8>) -> Result<Self, String> {
if raw_attribute.len() != 8 {
return Err(format!(
"parse: Float value expected to be 8 bytes, but got {}",
raw_attribute.len()
));
}
Ok(f64::from_le_bytes(
raw_attribute[..8]
.try_into()
.expect("This has to be 8 bytes long!"),
))
}
}
impl AttributeValue for Vec<u8> {
fn parse(raw_attribute: Vec<u8>) -> Result<Self, String> {
Ok(raw_attribute)
}
}
impl AttributeValue for bool {
fn parse(raw_attribute: Vec<u8>) -> Result<Self, String> {
if raw_attribute.len() != 1 {
return Err(format!(
"parse: Bool value expected to be 1 byte, but got {}",
raw_attribute.len()
));
}
Ok(raw_attribute[0] & 1 == 1)
}
}
impl AttributeValue for DateTime<FixedOffset> {
fn parse(raw_attribute: Vec<u8>) -> Result<Self, String> {
if raw_attribute.len() != 8 {
return Err(format!(
"parse: Timestamp expected to be 8 bytes, but got {}",
raw_attribute.len()
));
}
let nanos = i64::from_le_bytes(
raw_attribute.as_slice()[..8]
.try_into()
.expect("This has to be 8 bytes long!"),
);
Ok(DateTime::from_timestamp_nanos(nanos).into())
}
}
pub fn get_attribute<T>(path: &PropertyPath) -> Result<Option<T>, String>
where
T: AttributeValue,
{
match crate::data::property::get_property(path) {
Ok(Some(attribute_bytes)) => Ok(Some(T::parse(attribute_bytes)?)),
Ok(None) => Ok(None),
Err(e) => Err(format!("get_attribute: error: {e:?}")),
}
}
pub fn set_attribute(attr: &str, value: &[u8]) {
match hostcalls::set_property(Path::from(attr).tokens(), Some(value)) {
Ok(_) => (),
Err(_) => error!("set_attribute: failed to set property {attr}"),
};
}
pub fn store_metadata(metastruct: &Struct) {
let metadata = process_metadata(metastruct, String::new());
for (key, value) in metadata {
let attr = format!("{KUADRANT_NAMESPACE}\\.{key}");
// stored into host_property: wasm.kuadrant.{key}
// example: wasm.kuadrant.identity.anonymous is how it's stored!
// but users would write the predicate: !auth.identity.anonymous
// two problems:
// - 1/ auth.identity doesn't resolve
// - 2/ the value is the string "true"
// struct User {
// foo: bool,
// bar: float, // 1 != 1.0
// name: String,
// }
//
// Admin can store this:
// authorino: export auth.identity.user.foo = expression("auth.user != null") // {"foo": true, "bar": 123, "name": "dd"}
// Or that:
// authorino: export auth.identity.foo = expression("auth.user.long.ass.path.to.some.member.within.foo")
// authorino: export auth.identity.user.bar = 123
// authorino: export auth.identity.user.name = "dd"
// predicate: !auth.identity.user.foo && auth.identity.user.bar != 443.0
// => properties [["auth", "identity", "user", "foo"], ["destination", "port"]]
// known part ["auth", "identity"] + "user", resolves the key wasm.kuadrant.identity.user ? to lookup the value
// value is a string, "{"foo": true, "bar": 123, "name": "dd"}"
// value is json literal... string "true" is the Bool(true), we need to unmarshal that value form json
// then evaluate the rest of the path against that structure and resolve the type from the value itself
// e.g. : user.foo, .foo is that part that we don't know about, .foo => what's the value?
// value is true, i.e. a boolean, so the value is cel_interpreter.Value::Bool(true)
// within the value, we need to access the member "foo"
//
// Split the work in 2:
// - deal with scalar json values in the attribute: bool, number, string, null
// - deal with: list, map, object
// e.g. support auth.identity.groups[0] == "foo"
debug!("set_attribute: {attr} = {value}");
// value is actually a json literal, e.g. 'true' != '"true"'
set_attribute(attr.as_str(), value.into_bytes().as_slice());
}
}
fn process_metadata(s: &Struct, prefix: String) -> Vec<(String, String)> {
let mut result = Vec::new();
for (key, value) in s.get_fields() {
let current_prefix = if prefix.is_empty() {
key.clone()
} else {
format!("{prefix}\\.{key}")
};
if value.has_string_value() {
result.push((current_prefix, value.get_string_value().to_string()));
} else if value.has_struct_value() {
let nested_struct = value.get_struct_value();
result.extend(process_metadata(nested_struct, current_prefix));
}
}
result
}
#[cfg(test)]
mod tests {
use crate::data::attribute::process_metadata;
use protobuf::well_known_types::{Struct, Value, Value_oneof_kind};
use std::collections::HashMap;
pub fn struct_from(values: Vec<(String, Value)>) -> Struct {
let mut hm = HashMap::new();
for (key, value) in values {
hm.insert(key, value);
}
Struct {
fields: hm,
unknown_fields: Default::default(),
cached_size: Default::default(),
}
}
pub fn string_value_from(value: String) -> Value {
Value {
kind: Some(Value_oneof_kind::string_value(value)),
unknown_fields: Default::default(),
cached_size: Default::default(),
}
}
pub fn struct_value_from(value: Struct) -> Value {
Value {
kind: Some(Value_oneof_kind::struct_value(value)),
unknown_fields: Default::default(),
cached_size: Default::default(),
}
}
#[test]
fn get_metadata_one() {
let metadata = struct_from(vec![(
"identity".to_string(),
struct_value_from(struct_from(vec![(
"userid".to_string(),
string_value_from("bob".to_string()),
)])),
)]);
let output = process_metadata(&metadata, String::new());
assert_eq!(output.len(), 1);
assert_eq!(
output,
vec![("identity\\.userid".to_string(), "bob".to_string())]
);
}
#[test]
fn get_metadata_two() {
let metadata = struct_from(vec![(
"identity".to_string(),
struct_value_from(struct_from(vec![
("userid".to_string(), string_value_from("bob".to_string())),
("type".to_string(), string_value_from("test".to_string())),
])),
)]);
let output = process_metadata(&metadata, String::new());
assert_eq!(output.len(), 2);
assert!(output.contains(&("identity\\.userid".to_string(), "bob".to_string())));
assert!(output.contains(&("identity\\.type".to_string(), "test".to_string())));
}
#[test]
fn get_metadata_three() {
let metadata = struct_from(vec![
(
"identity".to_string(),
struct_value_from(struct_from(vec![(
"userid".to_string(),
string_value_from("bob".to_string()),
)])),
),
(
"other_data".to_string(),
string_value_from("other_value".to_string()),
),
]);
let output = process_metadata(&metadata, String::new());
assert_eq!(output.len(), 2);
assert!(output.contains(&("identity\\.userid".to_string(), "bob".to_string())));
assert!(output.contains(&("other_data".to_string(), "other_value".to_string())));
}
}