use serde_json::Value;
pub const CALLER_EXT_KEY: &str = "caller";
pub fn caller_block(payload: &Value) -> Option<&Value> {
payload
.get("extensions")?
.get(CALLER_EXT_KEY)
.filter(|block| block.is_object())
}
pub const ATTR_CALLER_SUB: &str = "caller.sub";
pub const ATTR_CALLER_TEAM: &str = "caller.team";
pub const ATTR_CALLER_GROUPS: &str = "caller.groups";
pub const ATTR_CALLER_ROLE: &str = "caller.role";
pub const ATTR_CALLER_VERIFIED: &str = "caller.user_verified";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ComponentCaller {
pub sub: Option<String>,
pub team: Option<String>,
pub groups: Vec<String>,
pub role: Option<String>,
}
#[derive(serde::Deserialize)]
struct CallerWire {
#[serde(default)]
user_verified: bool,
#[serde(default)]
sub: Option<String>,
#[serde(default)]
groups: Vec<String>,
#[serde(default)]
team: Option<String>,
#[serde(default)]
role: Option<String>,
}
fn non_empty(value: Option<String>) -> Option<String> {
value
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
}
impl ComponentCaller {
pub fn from_block(block: &Value) -> Option<Self> {
let wire = match serde_json::from_value::<CallerWire>(block.clone()) {
Ok(wire) => wire,
Err(error) => {
tracing::warn!(
%error,
"provider stamped a caller block this runtime cannot decode; \
the component invocation runs without a caller"
);
return None;
}
};
if !wire.user_verified {
return None;
}
let caller = Self {
sub: non_empty(wire.sub),
team: non_empty(wire.team),
groups: wire
.groups
.into_iter()
.map(|g| g.trim().to_string())
.filter(|g| !g.is_empty())
.collect(),
role: non_empty(wire.role),
};
if caller.sub.is_none() && caller.team.is_none() {
return None;
}
Some(caller)
}
pub fn attributes(&self) -> Vec<(String, String)> {
let mut attrs = vec![(ATTR_CALLER_VERIFIED.to_string(), "true".to_string())];
if let Some(sub) = &self.sub {
attrs.push((ATTR_CALLER_SUB.to_string(), sub.clone()));
}
if let Some(team) = &self.team {
attrs.push((ATTR_CALLER_TEAM.to_string(), team.clone()));
}
if !self.groups.is_empty() {
attrs.push((
ATTR_CALLER_GROUPS.to_string(),
Value::from(self.groups.clone()).to_string(),
));
}
if let Some(role) = &self.role {
attrs.push((ATTR_CALLER_ROLE.to_string(), role.clone()));
}
attrs
}
pub fn metadata_cbor(&self) -> Option<Vec<u8>> {
let attrs = self.attributes();
if attrs.is_empty() {
return None;
}
let map: std::collections::BTreeMap<String, String> = attrs.into_iter().collect();
serde_cbor::to_vec(&map).ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_verified_block_becomes_a_component_caller() {
let caller = ComponentCaller::from_block(&json!({
"user_verified": true,
"sub": "u-1@acme",
"team": "sales",
"groups": ["employee", " ", "admins"],
"role": "member"
}))
.expect("caller");
assert_eq!(caller.sub.as_deref(), Some("u-1@acme"));
assert_eq!(caller.team.as_deref(), Some("sales"));
assert_eq!(caller.groups, vec!["employee", "admins"]);
assert_eq!(caller.role.as_deref(), Some("member"));
assert_eq!(
caller.attributes(),
vec![
("caller.user_verified".to_string(), "true".to_string()),
("caller.sub".to_string(), "u-1@acme".to_string()),
("caller.team".to_string(), "sales".to_string()),
(
"caller.groups".to_string(),
r#"["employee","admins"]"#.to_string()
),
("caller.role".to_string(), "member".to_string()),
]
);
}
#[test]
fn an_unverified_or_malformed_block_is_no_caller() {
assert!(ComponentCaller::from_block(&json!({ "sub": "u-1@acme" })).is_none());
assert!(
ComponentCaller::from_block(&json!({ "user_verified": false, "sub": "u-1" })).is_none()
);
assert!(
ComponentCaller::from_block(&json!({ "user_verified": "yes", "sub": "u-1" })).is_none()
);
assert!(ComponentCaller::from_block(&json!({ "user_verified": true })).is_none());
assert!(
ComponentCaller::from_block(&json!({ "user_verified": true, "sub": " " })).is_none()
);
}
fn envelope_with(extensions: Value) -> Value {
json!({ "id": "m-1", "text": "hello", "extensions": extensions })
}
#[test]
fn a_provider_stamped_block_is_found() {
let payload = envelope_with(json!({
"caller": { "user_verified": true, "sub": "u-1@acme" }
}));
let block = caller_block(&payload).expect("block");
assert_eq!(block["sub"], "u-1@acme");
}
#[test]
fn an_envelope_without_one_yields_none() {
assert!(caller_block(&envelope_with(json!({}))).is_none());
assert!(caller_block(&json!({ "text": "hello" })).is_none());
}
#[test]
fn a_root_level_caller_is_ignored() {
let payload = json!({
"text": "hello",
"caller": { "user_verified": true, "sub": "root@evil" }
});
assert!(
caller_block(&payload).is_none(),
"only the provider-owned extensions map establishes a caller"
);
}
#[test]
fn a_non_object_block_is_not_a_caller() {
for bad in [json!("yes"), json!(true), json!(["a"]), json!(7)] {
let payload = envelope_with(json!({ "caller": bad }));
assert!(caller_block(&payload).is_none());
}
}
}