Skip to main content

kanade_shared/wire/
heartbeat.rs

1use serde::{Deserialize, Serialize};
2
3/// Liveness ping every agent sends on a 30 s cadence (see
4/// `inventory_interval` / `heartbeat_interval` in agent_config).
5///
6/// `hostname` and `os_family` are enriched baseline facts so the
7/// SPA agents page has *something* to show as soon as the agent
8/// boots — even when the full WMI-driven `HwInventory` hasn't been
9/// (or can't be) collected. Both stay `Option<String>` so older
10/// agents that don't send them still deserialize cleanly.
11#[derive(Serialize, Deserialize, Debug, Clone)]
12pub struct Heartbeat {
13    pub pc_id: String,
14    pub at: chrono::DateTime<chrono::Utc>,
15    pub agent_version: String,
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub hostname: Option<String>,
18    /// Coarse OS bucket from `std::env::consts::OS` — `"windows"`,
19    /// `"linux"`, `"macos"`. Rich OS metadata still flows through
20    /// the inventory path; this is just the "agent is alive on a
21    /// <family>" signal.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub os_family: Option<String>,
24    // v0.37 / Part 2: agent process self-perf. All Option so older
25    // agents (or any future build that hits a sysinfo error) keep
26    // sending valid heartbeats — backend just shows blanks. Cost on
27    // the agent is one `sysinfo::System::refresh_processes_specifics`
28    // call per 30 s tick. On Windows the underlying APIs are
29    // `CreateToolhelp32Snapshot` + per-process `GetProcessMemoryInfo`
30    // / `GetProcessIoCounters` (NOT WMI; NOT
31    // `NtQuerySystemInformation`). Single-digit ms on a typical
32    // endpoint; scales with the host's process count for the
33    // Toolhelp snapshot — fine on a normal PC, larger on RDS hosts.
34    /// Agent process CPU usage, in percent-of-one-core (a process
35    /// fully pinning one core reports 100; one pinning two cores
36    /// reports 200). This is sysinfo's convention — closer to
37    /// `top` than to Windows Task Manager (which normalises by
38    /// total cores, so a 1-core peg on an 8-core box shows up as
39    /// ~12.5 % in TM). Divide by host core count if you want a
40    /// host-normalised view. `None` is published on the very first
41    /// heartbeat after process start, because sysinfo's CPU% needs
42    /// two consecutive samples to diff — populating it would
43    /// always report 0.0 there and risk an operator misreading
44    /// "agent isn't doing anything".
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub agent_cpu_pct: Option<f64>,
47    /// Agent process resident set size in bytes — sysinfo's
48    /// `Process::memory()`, which on Windows is
49    /// `PROCESS_MEMORY_COUNTERS_EX::WorkingSetSize` (full working
50    /// set, shared + private). Closest Task Manager column is
51    /// "Working set (memory)", NOT "Memory (private working set)"
52    /// which would be `PrivateUsage` and sysinfo exposes
53    /// separately as `virtual_memory()`.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub agent_rss_bytes: Option<i64>,
56    /// Absolute bytes the agent process has read from disk since
57    /// it started. Wire format is cumulative (not delta) so
58    /// dropped / out-of-order heartbeats don't poison rate math
59    /// for any client that wants to derive a rate by diffing
60    /// successive snapshots. Today neither the backend projector
61    /// nor the SPA does that diff — they just store and render
62    /// the cumulative value. Future SPA work or an exporter can
63    /// compute rate without a schema change.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub agent_disk_read_bytes: Option<i64>,
66    /// Absolute bytes the agent process has written to disk since
67    /// it started. Same shape as `agent_disk_read_bytes`.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub agent_disk_written_bytes: Option<i64>,
70    /// #582 Phase 2: versions this agent's boot sentinel rolled back
71    /// after they crash-looped on boot. The self-update path refuses
72    /// to (re-)deploy any version listed here, so the SPA's rollout
73    /// view can flag "PC-X failed to adopt target 0.43.51" — the
74    /// fleet-wide signal that a rollout is bad. Empty (the common
75    /// case) is skipped on the wire; older agents simply omit it and
76    /// `#[serde(default)]` leaves it empty.
77    #[serde(default, skip_serializing_if = "Vec::is_empty")]
78    pub quarantined_versions: Vec<String>,
79    /// Most-recently signed-in account on this host, read from the
80    /// Windows `LogonUI` registry key
81    /// (`HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\LastLoggedOnUser`).
82    /// This is the `DOMAIN\sam` (or `.\user`) login name the sign-in
83    /// screen last used; it survives logoff, so it's populated even
84    /// when no one is currently signed in. `None` on a never-signed-in
85    /// host and on non-Windows agents (`read_hklm_value` returns `None`
86    /// off-Windows) — see #655 for the cross-platform follow-up — so
87    /// older agents keep sending valid heartbeats either way.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub last_logon_user: Option<String>,
90    /// Display name paired with [`Self::last_logon_user`], from
91    /// `LogonUI\LastLoggedOnDisplayName` (e.g. `"Yamada Taro"`). `None`
92    /// when unavailable.
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub last_logon_display_name: Option<String>,
95    /// #1165: the command-signing keys this agent currently trusts, each as
96    /// `kid:fingerprint`.
97    ///
98    /// Reported so "which machines still trust the old key" is answerable.
99    /// Without it, retiring a key is a guess: an agent that never received the
100    /// replacement rejects every command at stage 3, and there is no way to
101    /// know it was going to before it does.
102    ///
103    /// The fingerprint half (#1229) answers a question the id cannot: **do two
104    /// machines holding the same id hold the same key**. The id is chosen by
105    /// whoever wrote the ring, so a mistyped paste, a same-`kid` re-mint, or a
106    /// hand-edited registry value produces a host that reports the expected id,
107    /// refuses every command once enforcement is on, and never self-heals —
108    /// the reload-on-unknown-key path (#1186) does not fire, because the key
109    /// *is* present, just wrong.
110    ///
111    /// One flat string rather than a nested object on purpose. The projected
112    /// column is a JSON array queried with `LIKE`, because the read-only query
113    /// path rejects table-valued functions (`json_each`) — so
114    /// `LIKE '%"backend-2026…:3f2a…"%'` pins the exact key with the machinery
115    /// that already exists, while `LIKE '%"backend-2026…:%'` still asks the
116    /// id-only question. Nothing parses these back apart; they are matched.
117    ///
118    /// `Option<Vec<_>>` rather than a plain `Vec` with
119    /// `skip_serializing_if = "Vec::is_empty"` — the shape
120    /// [`Self::quarantined_versions`] uses — because **empty is the state this
121    /// exists to surface**. Skipping an empty list would put "this agent holds
122    /// no keys" and "this agent is too old to say" on the wire as the same
123    /// thing, and they need opposite responses: provision the first one, and
124    /// upgrade the second before you can even ask. So:
125    ///
126    /// * `None` — the agent predates this field. Unknown, not empty.
127    /// * `Some([])` — reporting, and holds nothing. This is the work queue.
128    /// * `Some([kid, ..])` — what it will actually accept right now.
129    ///
130    /// It reports the **in-memory** ring, not the registry. Those differ
131    /// between a key landing on disk and the reload that picks it up (#1186),
132    /// and the useful answer is what this agent would accept if a command
133    /// arrived now — reporting the file would describe a machine that does not
134    /// exist yet.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub command_keys: Option<Vec<String>>,
137    /// #1250: whether this agent is refusing commands it cannot verify.
138    ///
139    /// [`Self::command_keys`] made key *distribution* enumerable; this makes
140    /// *enforcement* enumerable, which nothing else does. It cannot be inferred
141    /// from the signature outcomes: in normal operation every command is
142    /// signed, so an enforcing host and a non-enforcing one both report
143    /// `command_signature_ok`. The two are observationally identical until
144    /// something unsigned arrives — which is exactly the event nobody wants to
145    /// stage across a fleet to find out. Nor from `command_keys`: a host can
146    /// hold a perfect ring and not be enforcing, which is what every machine is
147    /// doing today.
148    ///
149    /// Three states, for the same reason as `command_keys`:
150    ///
151    /// * `None` — the agent predates this field. Unknown, not "no".
152    /// * `Some(false)` — reporting, and not enforcing. **This is the queue.**
153    /// * `Some(true)` — refusing unverified commands right now.
154    ///
155    /// The **effective** state, not the configured one: an agent declines to
156    /// enforce on an empty ring (refusing everything would include the command
157    /// that restores the keys), so a host in that state reports `false` however
158    /// its registry reads. Reporting the configured value would describe a
159    /// machine that does not exist — the same rule that makes `command_keys`
160    /// report memory rather than disk.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub enforcing: Option<bool>,
163    /// The command protocols this agent can verify (`legacy`,
164    /// `kanade.command.v2`). What later gates switching a host to receive the
165    /// envelope form: a host that cannot verify it must keep getting the old one.
166    ///
167    /// Three states, the same convention as [`Self::command_keys`]: `None` —
168    /// not reported (a ping reply, or a build that predates the field; NOT
169    /// "supports only legacy"); `Some(vec![])` — reported, supports none; or a
170    /// populated set.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub command_protocols: Option<Vec<String>>,
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use chrono::TimeZone;
179
180    #[test]
181    fn heartbeat_round_trips_through_json() {
182        let hb = Heartbeat {
183            pc_id: "pc-01".into(),
184            at: chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap(),
185            agent_version: "0.12.0".into(),
186            hostname: Some("PC-01".into()),
187            os_family: Some("windows".into()),
188            agent_cpu_pct: Some(0.3),
189            agent_rss_bytes: Some(45_000_000),
190            agent_disk_read_bytes: Some(1024 * 1024),
191            agent_disk_written_bytes: Some(512 * 1024),
192            quarantined_versions: vec!["0.43.51".into()],
193            last_logon_user: Some("EXAMPLE\\taro".into()),
194            last_logon_display_name: Some("Yamada Taro".into()),
195            command_keys: Some(vec!["backend-20260728".into()]),
196            enforcing: Some(false),
197            command_protocols: Some(vec!["legacy".into(), "kanade.command.v2".into()]),
198        };
199        let json = serde_json::to_string(&hb).unwrap();
200        let back: Heartbeat = serde_json::from_str(&json).unwrap();
201        assert_eq!(back.pc_id, hb.pc_id);
202        assert_eq!(back.at, hb.at);
203        assert_eq!(back.agent_version, hb.agent_version);
204        assert_eq!(back.hostname, hb.hostname);
205        assert_eq!(back.os_family, hb.os_family);
206        assert_eq!(back.agent_cpu_pct, hb.agent_cpu_pct);
207        assert_eq!(back.agent_rss_bytes, hb.agent_rss_bytes);
208        assert_eq!(back.agent_disk_read_bytes, hb.agent_disk_read_bytes);
209        assert_eq!(back.agent_disk_written_bytes, hb.agent_disk_written_bytes);
210        assert_eq!(back.quarantined_versions, hb.quarantined_versions);
211        assert_eq!(back.last_logon_user, hb.last_logon_user);
212        assert_eq!(back.last_logon_display_name, hb.last_logon_display_name);
213        assert_eq!(back.command_keys, hb.command_keys);
214        assert_eq!(back.command_protocols, hb.command_protocols);
215    }
216
217    #[test]
218    fn heartbeat_empty_quarantine_is_omitted_on_the_wire() {
219        let hb = Heartbeat {
220            pc_id: "x".into(),
221            at: chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap(),
222            agent_version: "0.43.50".into(),
223            hostname: None,
224            os_family: None,
225            agent_cpu_pct: None,
226            agent_rss_bytes: None,
227            agent_disk_read_bytes: None,
228            agent_disk_written_bytes: None,
229            quarantined_versions: Vec::new(),
230            last_logon_user: None,
231            last_logon_display_name: None,
232            command_keys: None,
233            enforcing: None,
234            command_protocols: None,
235        };
236        let json = serde_json::to_string(&hb).unwrap();
237        assert!(
238            !json.contains("quarantined_versions"),
239            "empty quarantine must be skipped on the wire: {json}",
240        );
241        // And a payload without the field still decodes to empty.
242        let back: Heartbeat = serde_json::from_str(&json).unwrap();
243        assert!(back.quarantined_versions.is_empty());
244    }
245
246    #[test]
247    fn an_empty_keyring_is_reported_rather_than_omitted() {
248        // The distinction the whole field exists for. `quarantined_versions`
249        // skips an empty list because "nothing quarantined" is the boring
250        // default; an empty *keyring* is the opposite — it is the machine an
251        // operator has to act on. If it were skipped, it would arrive looking
252        // exactly like an agent too old to report at all, and the two need
253        // opposite responses (provision it / upgrade it first).
254        let hb = Heartbeat {
255            pc_id: "x".into(),
256            at: chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap(),
257            agent_version: "0.44.36".into(),
258            hostname: None,
259            os_family: None,
260            agent_cpu_pct: None,
261            agent_rss_bytes: None,
262            agent_disk_read_bytes: None,
263            agent_disk_written_bytes: None,
264            quarantined_versions: Vec::new(),
265            last_logon_user: None,
266            last_logon_display_name: None,
267            command_keys: Some(Vec::new()),
268            enforcing: Some(false),
269            command_protocols: None,
270        };
271        let json = serde_json::to_string(&hb).unwrap();
272        assert!(
273            json.contains("command_keys"),
274            "an empty keyring must still reach the backend: {json}"
275        );
276        let back: Heartbeat = serde_json::from_str(&json).unwrap();
277        assert_eq!(back.command_keys, Some(Vec::new()));
278
279        // And an agent that predates the field stays distinguishable from it.
280        let old = r#"{"pc_id":"x","at":"2026-05-16T00:00:00Z","agent_version":"0.44.35"}"#;
281        let hb: Heartbeat = serde_json::from_str(old).unwrap();
282        assert_eq!(hb.command_keys, None, "absent must not decode as empty");
283    }
284
285    #[test]
286    fn not_enforcing_is_reported_rather_than_omitted() {
287        // #1250, and the same trap as the keyring above: `false` is the state
288        // worth acting on, so it must not be skipped. A `skip_serializing_if`
289        // that dropped it would put "this host is not enforcing" and "this host
290        // is too old to say" on the wire as the same absence — and stage 3's
291        // remaining work is exactly the first set.
292        let hb = Heartbeat {
293            pc_id: "x".into(),
294            at: chrono::Utc.with_ymd_and_hms(2026, 8, 1, 0, 0, 0).unwrap(),
295            agent_version: "0.45.1".into(),
296            hostname: None,
297            os_family: None,
298            agent_cpu_pct: None,
299            agent_rss_bytes: None,
300            agent_disk_read_bytes: None,
301            agent_disk_written_bytes: None,
302            quarantined_versions: Vec::new(),
303            last_logon_user: None,
304            last_logon_display_name: None,
305            command_keys: Some(vec!["backend-20260728:75b4c8f44e18012d".into()]),
306            enforcing: Some(false),
307            command_protocols: None,
308        };
309        let json = serde_json::to_string(&hb).unwrap();
310        assert!(
311            json.contains("\"enforcing\":false"),
312            "a host that is not enforcing must say so: {json}"
313        );
314        let back: Heartbeat = serde_json::from_str(&json).unwrap();
315        assert_eq!(back.enforcing, Some(false));
316
317        // The pairing this field exists to expose: a complete ring proves
318        // nothing about enforcement, so neither value can be read off the
319        // other. This heartbeat is every machine in the fleet today.
320        assert!(back.command_keys.is_some_and(|k| !k.is_empty()));
321
322        let old = r#"{"pc_id":"x","at":"2026-08-01T00:00:00Z","agent_version":"0.45.1"}"#;
323        let hb: Heartbeat = serde_json::from_str(old).unwrap();
324        assert_eq!(hb.enforcing, None, "absent must not decode as false");
325    }
326
327    #[test]
328    fn heartbeat_without_enrichment_still_decodes() {
329        // Older agents sending only the v0.11 shape must still parse.
330        let json = r#"{"pc_id":"x","at":"2026-05-16T00:00:00Z","agent_version":"0.11.5"}"#;
331        let hb: Heartbeat = serde_json::from_str(json).unwrap();
332        assert_eq!(hb.pc_id, "x");
333        assert_eq!(hb.hostname, None);
334        assert_eq!(hb.os_family, None);
335        // v0.37 Part 2: perf fields are also optional and default
336        // to None, so a pre-0.37 agent's heartbeat keeps decoding.
337        assert_eq!(hb.agent_cpu_pct, None);
338        assert_eq!(hb.agent_rss_bytes, None);
339        assert_eq!(hb.agent_disk_read_bytes, None);
340        assert_eq!(hb.agent_disk_written_bytes, None);
341        // last-logon fields are optional too: a heartbeat that omits
342        // them (older agent, non-Windows host) decodes to None.
343        assert_eq!(hb.last_logon_user, None);
344        assert_eq!(hb.last_logon_display_name, None);
345    }
346}