Skip to main content

aimdb_core/
identity.rs

1//! Instance identity: which build this binary is, and which instance runs it.
2//!
3//! The build comes from the binary's build-info section, placed by
4//! [`aimdb_build_info::section!`]. The instance's name and unique ID are given
5//! at startup: a name on a host, the chip's ID on a board. All three are
6//! optional and set on the [`AimDbBuilder`](crate::AimDbBuilder); `build()`
7//! checks them and [`AimDb::identity`](crate::AimDb::identity) returns them.
8
9use alloc::format;
10use alloc::string::String;
11use alloc::vec::Vec;
12
13use aimdb_build_info::Section;
14
15/// Longest instance name, in bytes of UTF-8.
16pub const NAME_MAX: usize = 128;
17
18/// Longest instance UID, in bytes.
19pub const UID_MAX: usize = 32;
20
21/// The identity frozen at `build()`.
22#[derive(Debug, Clone, Default)]
23pub struct Identity {
24    name: Option<String>,
25    uid: Option<Vec<u8>>,
26    build_info: Option<Section<'static>>,
27}
28
29impl Identity {
30    /// The instance name given at startup.
31    pub fn name(&self) -> Option<&str> {
32        self.name.as_deref()
33    }
34
35    /// The instance's unique ID given at startup, e.g. the chip's.
36    pub fn uid(&self) -> Option<&[u8]> {
37        self.uid.as_deref()
38    }
39
40    /// This binary's build-info section. `build()` checked it: the payload is
41    /// at most [`PAYLOAD_MAX`](aimdb_build_info::PAYLOAD_MAX) bytes, holds no
42    /// line break, and (with the `remote` feature) is a JSON object.
43    pub fn build_info(&self) -> Option<&Section<'static>> {
44        self.build_info.as_ref()
45    }
46}
47
48/// What the builder collects, checked by `build()`.
49#[derive(Default)]
50pub(crate) struct IdentityConfig {
51    pub(crate) name: Option<String>,
52    pub(crate) uid: Option<Vec<u8>>,
53    pub(crate) build_info: Option<&'static [u8]>,
54}
55
56impl IdentityConfig {
57    /// The identity, and a message for each mistake.
58    pub(crate) fn freeze(self) -> (Identity, Vec<String>) {
59        let mut errors = Vec::new();
60        if let Some(name) = self.name.as_ref().filter(|n| n.len() > NAME_MAX) {
61            errors.push(format!(
62                "instance name is {} bytes, at most {NAME_MAX}",
63                name.len()
64            ));
65        }
66        if let Some(uid) = self.uid.as_ref().filter(|u| u.len() > UID_MAX) {
67            errors.push(format!(
68                "instance UID is {} bytes, at most {UID_MAX}",
69                uid.len()
70            ));
71        }
72        let build_info = self
73            .build_info
74            .and_then(|bytes| check_build_info(bytes).map_err(|e| errors.push(e)).ok());
75        let identity = Identity {
76            name: self.name,
77            uid: self.uid,
78            build_info,
79        };
80        (identity, errors)
81    }
82}
83
84/// The section, if AimX can serve it: replies carry the payload verbatim.
85fn check_build_info(bytes: &'static [u8]) -> Result<Section<'static>, String> {
86    let section = aimdb_build_info::parse(bytes).map_err(|e| format!("build info: {e}"))?;
87    let payload = section.payload;
88    if payload.len() > aimdb_build_info::PAYLOAD_MAX {
89        return Err(format!(
90            "build info: the payload is {} bytes, at most {}",
91            payload.len(),
92            aimdb_build_info::PAYLOAD_MAX
93        ));
94    }
95    // Newline-framed transports (UDS) would end the reply at the break.
96    if !aimdb_build_info::payload_is_single_line(payload) {
97        return Err("build info: the payload contains a line break".into());
98    }
99    #[cfg(feature = "remote")]
100    check_json_object(payload).map_err(|e| format!("build info: {e}"))?;
101    Ok(section)
102}
103
104/// Whether `payload` is one JSON object, checked without building a tree.
105#[cfg(feature = "remote")]
106fn check_json_object(payload: &[u8]) -> Result<(), serde_json::Error> {
107    use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
108
109    struct Object;
110
111    impl<'de> Visitor<'de> for Object {
112        type Value = ();
113
114        fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115            f.write_str("a JSON object")
116        }
117
118        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
119            while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
120            Ok(())
121        }
122    }
123
124    let mut de = serde_json::Deserializer::from_slice(payload);
125    (&mut de).deserialize_map(Object)?;
126    de.end()
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    use alloc::boxed::Box;
133    use alloc::vec;
134
135    /// A format-1 section around `payload`, by hand and without the build
136    /// helper's limits, leaked to `'static` as `section!()` is.
137    fn section(payload: &[u8]) -> &'static [u8] {
138        let region_off = (32 + payload.len()).div_ceil(8) * 8;
139        let total = region_off + 16;
140        let mut b = vec![0u8; total];
141        b[..8].copy_from_slice(&aimdb_build_info::MAGIC);
142        b[8..10].copy_from_slice(&aimdb_build_info::FORMAT.to_le_bytes());
143        b[10..12].copy_from_slice(&32u16.to_le_bytes());
144        b[12..16].copy_from_slice(&(payload.len() as u32).to_le_bytes());
145        b[16..20].copy_from_slice(&(region_off as u32).to_le_bytes());
146        b[20..24].copy_from_slice(&16u32.to_le_bytes());
147        b[24..28].copy_from_slice(&(total as u32).to_le_bytes());
148        b[32..32 + payload.len()].copy_from_slice(payload);
149        b[region_off..].fill(aimdb_build_info::ERASED);
150        Box::leak(b.into_boxed_slice())
151    }
152
153    fn with_build_info(bytes: &'static [u8]) -> (Identity, Vec<String>) {
154        IdentityConfig {
155            build_info: Some(bytes),
156            ..Default::default()
157        }
158        .freeze()
159    }
160
161    #[test]
162    fn unset_is_empty() {
163        let (id, errors) = IdentityConfig::default().freeze();
164        assert!(errors.is_empty());
165        assert_eq!(id.name(), None);
166        assert_eq!(id.uid(), None);
167        assert!(id.build_info().is_none());
168    }
169
170    #[test]
171    fn set_values_are_kept() {
172        let (id, errors) = IdentityConfig {
173            name: Some("gateway-3".into()),
174            uid: Some(vec![0x00, 0x35, 0xab]),
175            build_info: Some(section(br#"{"schema":1,"name":"app"}"#)),
176        }
177        .freeze();
178        assert!(errors.is_empty(), "{errors:?}");
179        assert_eq!(id.name(), Some("gateway-3"));
180        assert_eq!(id.uid(), Some(&[0x00, 0x35, 0xab][..]));
181        assert_eq!(
182            id.build_info().unwrap().payload,
183            br#"{"schema":1,"name":"app"}"#
184        );
185    }
186
187    #[test]
188    fn name_and_uid_limits_are_inclusive() {
189        let (_, errors) = IdentityConfig {
190            name: Some("n".repeat(NAME_MAX)),
191            uid: Some(vec![0; UID_MAX]),
192            build_info: None,
193        }
194        .freeze();
195        assert!(errors.is_empty(), "{errors:?}");
196
197        let (_, errors) = IdentityConfig {
198            name: Some("n".repeat(NAME_MAX + 1)),
199            uid: Some(vec![0; UID_MAX + 1]),
200            build_info: None,
201        }
202        .freeze();
203        assert_eq!(errors.len(), 2, "{errors:?}");
204        assert!(errors[0].contains("instance name is 129 bytes"));
205        assert!(errors[1].contains("instance UID is 33 bytes"));
206    }
207
208    #[test]
209    fn sections_that_cannot_be_served_are_rejected() {
210        let mut no_magic = section(b"{}").to_vec();
211        no_magic[0] = b'X';
212        let mut truncated = section(b"{}").to_vec();
213        truncated.pop();
214        // The parser accepts up to 64 KiB; AimX serves at most PAYLOAD_MAX.
215        let mut big = vec![b' '; aimdb_build_info::PAYLOAD_MAX - 1];
216        big[0] = b'{';
217        big.extend_from_slice(b"}");
218        big.push(b' ');
219
220        for (bytes, message) in [
221            (
222                &*Box::leak(no_magic.into_boxed_slice()),
223                "no build-info magic",
224            ),
225            (&*Box::leak(truncated.into_boxed_slice()), "truncated"),
226            (section(&big), "4097 bytes, at most 4096"),
227            (section(b"{\n}"), "line break"),
228            (section(b"{\r}"), "line break"),
229        ] {
230            let (id, errors) = with_build_info(bytes);
231            assert!(id.build_info().is_none());
232            assert_eq!(errors.len(), 1, "{errors:?}");
233            assert!(errors[0].starts_with("build info: "), "{errors:?}");
234            assert!(errors[0].contains(message), "{message}: {errors:?}");
235        }
236        // Exactly PAYLOAD_MAX is fine.
237        big.pop();
238        assert!(with_build_info(section(&big)).1.is_empty());
239    }
240
241    #[cfg(feature = "remote")]
242    #[test]
243    fn payload_must_be_one_json_object() {
244        for payload in [
245            &b"[1,2]"[..],
246            b"\"text\"",
247            b"",
248            b"{",
249            b"{\"a\":1} {}",
250            b"{\"a\":}",
251        ] {
252            let (_, errors) = with_build_info(section(payload));
253            assert_eq!(errors.len(), 1, "{:?}", core::str::from_utf8(payload));
254            assert!(errors[0].starts_with("build info: "), "{errors:?}");
255        }
256        // Whitespace between tokens, escapes, nesting and unknown fields are
257        // fine; only raw line breaks are not.
258        let ok = br#"{ "schema": 1,	"ext": {"note": "a\nb", "list": [1, {"x": null}]} }"#;
259        assert!(with_build_info(section(ok)).1.is_empty());
260    }
261
262    #[tokio::test]
263    async fn build_reports_identity_mistakes_with_the_rest() {
264        use crate::executor::test_support::NoopRuntimeOps;
265        let Err(err) = crate::AimDbBuilder::new()
266            .runtime(alloc::sync::Arc::new(NoopRuntimeOps))
267            .instance_name("n".repeat(NAME_MAX + 1))
268            .build_info(section(b"{\n}"))
269            .build()
270            .await
271        else {
272            panic!("build must fail");
273        };
274        let crate::DbError::InvalidConfiguration { errors } = &err else {
275            panic!("expected InvalidConfiguration, got {err:?}");
276        };
277        assert_eq!(errors.len(), 2, "{errors:?}");
278        assert!(errors
279            .iter()
280            .all(|e| e.record_key.is_empty() && e.url.is_none()));
281        let text = alloc::format!("{err}");
282        assert!(text.contains("instance name is 129 bytes"), "{text}");
283        assert!(
284            text.contains("build info: the payload contains a line break"),
285            "{text}"
286        );
287    }
288
289    #[tokio::test]
290    async fn identity_on_the_built_db() {
291        use crate::executor::test_support::NoopRuntimeOps;
292        let (db, _runner) = crate::AimDbBuilder::new()
293            .runtime(alloc::sync::Arc::new(NoopRuntimeOps))
294            .instance_name("gateway-3")
295            .instance_uid(&[0xde, 0xad])
296            .build_info(section(b"{}"))
297            .build()
298            .await
299            .unwrap();
300        let id = db.identity();
301        assert_eq!(id.name(), Some("gateway-3"));
302        assert_eq!(id.uid(), Some(&[0xde, 0xad][..]));
303        assert_eq!(id.build_info().unwrap().payload, b"{}");
304
305        let (db, _runner) = crate::AimDbBuilder::new()
306            .runtime(alloc::sync::Arc::new(NoopRuntimeOps))
307            .build()
308            .await
309            .unwrap();
310        assert!(db.identity().name().is_none() && db.identity().build_info().is_none());
311    }
312}