Skip to main content

core_api/
device_binding.rs

1//! Durable identity of a fixed-Space product. Business credentials remain private
2//! to its Client. A dependent Host reads this binding, never a second claim.
3use crate::{runtime_space::SpaceIdentity, RuntimeEnv};
4use serde::{Deserialize, Serialize};
5
6pub const DEVICE_BINDING_VERSION: u32 = 1;
7pub const DEVICE_BINDING_PATH: &str = "security/device-binding.json";
8
9#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase", deny_unknown_fields)]
11pub struct DeviceComponentIdentity {
12    pub id: String,
13    pub key_id: String,
14}
15
16#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "camelCase", deny_unknown_fields)]
18pub struct DeviceBinding {
19    pub version: u32,
20    pub env: RuntimeEnv,
21    pub client: DeviceComponentIdentity,
22    pub host: Option<DeviceComponentIdentity>,
23    /// Replaced only by factory reset. Credentials and grants must match it.
24    pub generation: String,
25    /// None means initialized locally but not yet bound by the owner.
26    pub space: Option<SpaceIdentity>,
27}
28
29impl DeviceComponentIdentity {
30    pub fn validate(&self) -> Result<(), &'static str> {
31        if valid_id(&self.id) && valid_id(&self.key_id) {
32            Ok(())
33        } else {
34            Err("invalid device component identity")
35        }
36    }
37}
38impl DeviceBinding {
39    pub fn validate(&self) -> Result<(), &'static str> {
40        if self.version != DEVICE_BINDING_VERSION || !valid_id(&self.generation) {
41            return Err("invalid device binding version or generation");
42        }
43        self.client.validate()?;
44        if let Some(host) = &self.host {
45            host.validate()?;
46        }
47        if let Some(space) = &self.space {
48            space
49                .validate()
50                .map_err(|_| "invalid device Space binding")?;
51        }
52        Ok(())
53    }
54}
55fn valid_id(id: &str) -> bool {
56    !id.is_empty() && id.len() <= 256 && id.trim() == id
57}