use serde::{Deserialize, Serialize};
use super::RemoteActionTarget;
use crate::api::ActionAddress;
pub const PROVIDER: &str = "tilo.environment";
pub const RESOURCE: &str = "environment";
pub const OPEN: &str = "open-browser";
pub const SEND_HELD: &str = "send-held-request";
pub const KEEP_HELD: &str = "keep-held-request";
pub const DEPARTURE_FACET: &str = "browser.departure";
#[must_use]
pub fn departure_facet(name: &str, value: impl Into<String>) -> crate::ActionFacet {
crate::ActionFacet::new(format!("{DEPARTURE_FACET}.{name}"), value)
}
#[must_use]
pub fn stated_facts(facets: &[crate::ActionFacet]) -> Vec<(String, String)> {
let prefix = format!("{DEPARTURE_FACET}.");
facets
.iter()
.filter_map(|facet| {
Some((
facet.key.strip_prefix(&prefix)?.to_owned(),
facet.value.clone(),
))
})
.collect()
}
#[must_use]
pub fn departure_facts(context: Option<&crate::ActionContext>) -> Vec<(String, String)> {
context.map_or_else(Vec::new, |context| stated_facts(&context.facets))
}
#[must_use]
pub fn departure_asked(facts: Vec<(String, String)>) -> super::asked::AskedFacts {
let on = facts
.iter()
.find(|(name, _)| name == "page")
.map(|(_, value)| value.clone());
super::asked::AskedFacts {
on,
facts: facts
.into_iter()
.map(|(label, value)| super::asked::Fact { label, value })
.collect(),
..super::asked::AskedFacts::default()
}
}
pub const MARK: &str = "TILO_HOSTED_BROWSER";
#[must_use]
pub fn target() -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, OPEN),
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpenBrowser {
pub workspace: String,
#[serde(default)]
pub account: String,
pub material: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpenedBrowser {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub opened_ms: Option<u64>,
pub device: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Placement {
pub host: [u8; 32],
pub workspace: String,
}
pub fn host_answered(
placed: Option<&Placement>,
caller: &super::Caller,
confirmation: Option<&super::Confirmation>,
) -> Result<bool, super::ActionCallError> {
let (Some(super::Confirmation::Confirmed), Some(forwarder)) =
(confirmation, caller.forwarder())
else {
return Ok(false);
};
let Some(placed) = placed else {
tracing::warn!(
forwarder = %hex::encode(forwarder),
"a confirmation another device forwarded reached a device no host placed, so it is refused"
);
return Err(super::ActionCallError::NotPermitted);
};
let by_host = *forwarder == placed.host;
let in_workspace = caller.workspace() == Some(placed.workspace.as_str());
if !(by_host && in_workspace) {
tracing::warn!(
forwarder = %hex::encode(forwarder),
by_host,
in_workspace,
"a page action's confirmation came from another device than the host that placed this window, or for another workspace, so it is refused"
);
return Err(super::ActionCallError::NotPermitted);
}
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_placing_host_answers_for_the_person_at_its_window() {
use super::super::{ActionCallError, Caller, Confirmation};
let host = [1; 32];
let placed = Placement {
host,
workspace: "ws".into(),
};
let agent = Caller::authenticated([7; 32], [8; 32]).in_workspace("ws");
let confirmed = Some(&Confirmation::Confirmed);
assert_eq!(
host_answered(Some(&placed), &agent.clone().forwarded_by(host), confirmed),
Ok(true)
);
for (caller, placed) in [
(agent.clone().forwarded_by([2; 32]), Some(&placed)),
(
Caller::authenticated([7; 32], [8; 32])
.in_workspace("other")
.forwarded_by(host),
Some(&placed),
),
(agent.clone().forwarded_by(host), None),
] {
assert_eq!(
host_answered(placed, &caller, confirmed),
Err(ActionCallError::NotPermitted),
"{caller:?}"
);
}
assert_eq!(host_answered(Some(&placed), &agent, confirmed), Ok(false));
assert_eq!(
host_answered(Some(&placed), &agent.forwarded_by(host), None),
Ok(false)
);
}
#[test]
fn an_opened_vm_names_its_device() {
assert_eq!(
serde_json::to_string(&OpenedBrowser {
opened_ms: None,
device: "ab".into()
})
.unwrap(),
r#"{"device":"ab"}"#
);
assert_eq!(
serde_json::to_string(&OpenedBrowser {
opened_ms: Some(900),
device: "ab".into()
})
.unwrap(),
r#"{"opened_ms":900,"device":"ab"}"#
);
}
}