use serde::{ser::Error as _, Deserialize, Deserializer, Serialize, Serializer};
use crate::session::ModuleControlRequest;
pub const OBSERVED_PEER_CAPABILITY: &str = "observed-peer/v1";
pub const OPERATOR_APP_CAPABILITY: &str = "operator-app/v1";
pub const PEER_BUILD_CAPABILITY: &str = "peer-build/v1";
pub const CALLER_ATTESTATION_CAPABILITY: &str = "caller-attestation/v1";
pub const MAX_ATTESTATION_INTEGER: u64 = (1_u64 << 53) - 1;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CallerClaim {
Own,
Brokered,
Relay,
Legacy,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CallerOrigin {
Release,
Development,
#[serde(other)]
Other,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CallerAttestation {
pub incarnation: String,
#[serde(deserialize_with = "deserialize_attestation_integer")]
pub spawn: u64,
#[serde(deserialize_with = "deserialize_attestation_integer")]
pub authority_epoch: u64,
pub claim: CallerClaim,
pub first_party: bool,
pub origin: CallerOrigin,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub declaration: Option<serde_json::Map<String, serde_json::Value>>,
pub approved_declarations_digest: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub declaration_digest: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallerAttestationError {
field: &'static str,
}
impl CallerAttestationError {
pub fn field(&self) -> &'static str {
self.field
}
}
impl std::fmt::Display for CallerAttestationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "caller {} exceeds 2^53-1", self.field)
}
}
impl std::error::Error for CallerAttestationError {}
impl CallerAttestation {
pub fn new(
incarnation: impl Into<String>,
spawn: u64,
authority_epoch: u64,
claim: CallerClaim,
first_party: bool,
origin: CallerOrigin,
approved_declarations_digest: impl Into<String>,
) -> Result<Self, CallerAttestationError> {
for (field, value) in [("spawn", spawn), ("authority_epoch", authority_epoch)] {
if value > MAX_ATTESTATION_INTEGER {
return Err(CallerAttestationError { field });
}
}
Ok(Self {
incarnation: incarnation.into(),
spawn,
authority_epoch,
claim,
first_party,
origin,
declaration: None,
approved_declarations_digest: approved_declarations_digest.into(),
declaration_digest: None,
})
}
#[must_use]
pub fn with_declaration(
mut self,
declaration: serde_json::Map<String, serde_json::Value>,
digest: impl Into<String>,
) -> Self {
self.declaration = Some(declaration);
self.declaration_digest = Some(digest.into());
self
}
}
fn deserialize_attestation_integer<'de, D: Deserializer<'de>>(decoder: D) -> Result<u64, D::Error> {
let value = u64::deserialize(decoder)?;
if value > MAX_ATTESTATION_INTEGER {
return Err(serde::de::Error::custom(
"attestation integer exceeds 2^53-1",
));
}
Ok(value)
}
fn deserialize_caller<'de, D: Deserializer<'de>>(
decoder: D,
) -> Result<Option<CallerAttestation>, D::Error> {
let Some(value) = Option::<serde_json::Value>::deserialize(decoder)? else {
return Ok(None);
};
for field in ["spawn", "authority_epoch"] {
if let Some(integer) = value.get(field) {
deserialize_attestation_integer(integer).map_err(serde::de::Error::custom)?;
}
}
if value.is_object()
&& [
"incarnation",
"spawn",
"authority_epoch",
"claim",
"first_party",
"origin",
"approved_declarations_digest",
]
.iter()
.any(|field| value.get(field).is_none())
{
return Ok(None);
}
serde_json::from_value(value)
.map(Some)
.map_err(serde::de::Error::custom)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ObservedPeerStatus {
Observed,
Unobserved,
Unknown(String),
}
impl Serialize for ObservedPeerStatus {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(match self {
Self::Observed => "observed",
Self::Unobserved => "unobserved",
Self::Unknown(value) => value,
})
}
}
impl<'de> Deserialize<'de> for ObservedPeerStatus {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(match String::deserialize(deserializer)?.as_str() {
"observed" => Self::Observed,
"unobserved" => Self::Unobserved,
value => Self::Unknown(value.to_owned()),
})
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ObservedPeer {
pub status: ObservedPeerStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uid: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exe: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signing_id: Option<String>,
}
impl ObservedPeer {
pub fn unobserved() -> Self {
Self {
status: ObservedPeerStatus::Unobserved,
uid: None,
sid: None,
exe: None,
signing_id: None,
}
}
pub fn observed_uid(uid: u32) -> Self {
Self {
status: ObservedPeerStatus::Observed,
uid: Some(uid),
..Self::unobserved()
}
}
pub fn observed_sid(sid: impl Into<String>) -> Self {
Self {
status: ObservedPeerStatus::Observed,
sid: Some(sid.into()),
..Self::unobserved()
}
}
#[must_use]
pub fn with_exe(mut self, exe: Option<String>) -> Self {
self.exe = exe;
self
}
#[must_use]
pub fn with_signing_id(mut self, signing_id: Option<String>) -> Self {
self.signing_id = signing_id;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct OperatorApp {
pub app: String,
pub pid: u32,
}
impl OperatorApp {
pub fn new(app: impl Into<String>, pid: u32) -> Self {
Self {
app: app.into(),
pid,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct RouteBindPeer {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub observed_peer: Option<ObservedPeer>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operator_app: Option<OperatorApp>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_caller"
)]
pub caller: Option<CallerAttestation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub peer_build: Option<String>,
}
impl RouteBindPeer {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_observed_peer(mut self, observed_peer: Option<ObservedPeer>) -> Self {
self.observed_peer = observed_peer;
self
}
#[must_use]
pub fn with_operator_app(mut self, operator_app: Option<OperatorApp>) -> Self {
self.operator_app = operator_app;
self
}
#[must_use]
pub fn with_caller(mut self, caller: Option<CallerAttestation>) -> Self {
self.caller = caller;
self
}
#[must_use]
pub fn with_peer_build(mut self, peer_build: Option<String>) -> Self {
self.peer_build = peer_build;
self
}
pub fn is_empty(&self) -> bool {
self.observed_peer.is_none()
&& self.operator_app.is_none()
&& self.caller.is_none()
&& self.peer_build.is_none()
}
}
pub fn encode_route_bind(
bind: &ModuleControlRequest,
peer: &RouteBindPeer,
) -> serde_json::Result<Vec<u8>> {
if !matches!(bind, ModuleControlRequest::RouteBind { .. }) {
return Err(serde_json::Error::custom(
"peer keys can only be added to a route.bind request",
));
}
if peer.is_empty() {
return serde_json::to_vec(bind);
}
#[derive(Serialize)]
struct WithPeer<'a> {
#[serde(flatten)]
bind: &'a ModuleControlRequest,
#[serde(flatten)]
peer: &'a RouteBindPeer,
}
serde_json::to_vec(&WithPeer { bind, peer })
}