use serde::{Deserialize, Serialize};
use super::{ActionCallError, InvokeArgument, InvokeRequest, RemoteActionTarget};
use crate::api::ActionAddress;
pub const PROVIDER: &str = "tilo.own-device";
pub const RESOURCE: &str = "identity.device";
pub const INVOKE: &str = "invoke";
#[must_use]
pub fn target() -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, INVOKE),
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Invocation {
pub device: String,
pub app: String,
pub resource: String,
pub action: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub arguments: Option<serde_json::Map<String, serde_json::Value>>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Checked {
pub device: [u8; 32],
pub app: String,
pub address: ActionAddress,
pub argument: InvokeArgument,
}
impl Invocation {
#[must_use]
pub fn argument(&self) -> InvokeArgument {
match serde_json::to_value(self) {
Ok(serde_json::Value::Object(map)) => InvokeArgument::Json(map),
_ => InvokeArgument::None,
}
}
pub fn from_argument(argument: &InvokeArgument) -> Result<Self, ActionCallError> {
let InvokeArgument::Json(map) = argument else {
return Err(ActionCallError::invalid_request(
"an own-device invocation takes JSON arguments",
));
};
serde_json::from_value(serde_json::Value::Object(map.clone()))
.map_err(|_| ActionCallError::invalid_request("the own-device invocation is malformed"))
}
pub fn check(&self) -> Result<Checked, ActionCallError> {
let device = decode_device(&self.device)
.ok_or_else(|| ActionCallError::invalid_request("not a device key"))?;
if self.app.is_empty() || self.app.contains(':') {
return Err(ActionCallError::invalid_request("not an application id"));
}
let address = ActionAddress::checked(&self.resource, &self.action)
.ok_or_else(|| ActionCallError::invalid_request("not an action"))?;
Ok(Checked {
device,
app: self.app.clone(),
address,
argument: self
.arguments
.clone()
.map_or(InvokeArgument::None, InvokeArgument::Json),
})
}
}
impl Checked {
#[must_use]
pub fn forwarded(&self, workspace: &str, original: &InvokeRequest) -> InvokeRequest {
let confirmation = original.confirmation.clone();
InvokeRequest {
on_behalf_of: None,
invocation: original.invocation,
target: super::application_action_target(
workspace,
&self.app,
self.address.resource.clone(),
self.address.action.clone(),
),
argument: self.argument.clone(),
context: None,
confirmation,
revision: None,
wait_ms: None,
appearance: None,
signed: None,
}
}
}
#[must_use]
pub fn decode_device(hex_key: &str) -> Option<[u8; 32]> {
if hex_key.len() != 64 || hex_key.bytes().any(|byte| byte.is_ascii_uppercase()) {
return None;
}
let mut key = [0_u8; 32];
hex::decode_to_slice(hex_key, &mut key).ok()?;
Some(key)
}
#[cfg(test)]
mod tests {
use super::{Invocation, PROVIDER, decode_device, target};
use crate::remote::{Confirmation, InvokeArgument, InvokeRequest, application_provider};
fn invocation() -> Invocation {
Invocation {
device: hex::encode([7_u8; 32]),
app: "so.tilo.settings".into(),
resource: "settings.root".into(),
action: "storage-summary".into(),
arguments: None,
}
}
tilo_test_env::scenario! {
fn an_own_device_invocation_travels_in_its_argument;
phase an_own_device_invocation_round_trips_through_its_argument;
{
let asked = invocation();
let read = Invocation::from_argument(&asked.argument()).expect("reads back");
assert_eq!(read, asked);
let checked = read.check().expect("valid");
assert_eq!(checked.device, [7; 32]);
assert_eq!(checked.argument, InvokeArgument::None);
assert_eq!(target().provider, PROVIDER);
}
phase a_malformed_own_device_invocation_is_refused;
{
assert!(Invocation::from_argument(&InvokeArgument::Text("x".into())).is_err());
let mut extra = invocation().argument();
if let InvokeArgument::Json(map) = &mut extra {
map.insert("caller".into(), serde_json::json!("someone else"));
}
assert!(
Invocation::from_argument(&extra).is_err(),
"nothing beyond the declared fields is read, least of all a caller"
);
for broken in [
Invocation {
device: "AB".repeat(32),
..invocation()
},
Invocation {
device: "ab".into(),
..invocation()
},
Invocation {
app: "workspace:app".into(),
..invocation()
},
Invocation {
action: String::new(),
..invocation()
},
Invocation {
resource: format!("settings.root{}other", crate::KEY_SEP),
..invocation()
},
Invocation {
action: format!("storage-summary{}other", crate::KEY_SEP),
..invocation()
},
] {
assert!(broken.check().is_err(), "{broken:?}");
}
assert_eq!(decode_device(&hex::encode([1; 32])), Some([1; 32]));
}
phase the_forwarded_request_names_the_app_in_the_shared_workspace_under_the_same_id;
{
let checked = Invocation {
arguments: Some(serde_json::Map::from_iter([(
"workspace".into(),
serde_json::json!("w"),
)])),
..invocation()
}
.check()
.unwrap();
let original = InvokeRequest {
on_behalf_of: None,
invocation: crate::InvocationId::new(),
target: target(),
argument: InvokeArgument::None,
context: None,
confirmation: Some(Confirmation::Confirmed),
revision: None,
wait_ms: Some(1),
appearance: None,
signed: None,
};
let forwarded = checked.forwarded("workspace-1", &original);
assert_eq!(forwarded.invocation, original.invocation);
assert_eq!(
application_provider(&forwarded.target.provider),
Some(("workspace-1", "so.tilo.settings"))
);
assert_eq!(forwarded.target.address.action, "storage-summary");
assert!(matches!(forwarded.argument, InvokeArgument::Json(_)));
assert_eq!(
forwarded.confirmation,
Some(Confirmation::Confirmed),
"the person's own word travels with their call"
);
}
}
}