Repository navigation
Expand file tree
/
Copy pathcmd_report.rs
More file actions
1106 lines (1004 loc) · 37.9 KB
/
Copy pathcmd_report.rs
File metadata and controls
1106 lines (1004 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The `debug report` artifact: model and renderer.
//!
//! `Report` is an in-memory value holding everything the report file
//! shows. The CLI side does all impure work (admin fetch, shell-outs,
//! log tail) up front and fills the model; `render` turns it into the
//! artifact text as a pure function, which is where the feature is
//! tested.
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use rand::Rng;
use serde::Serialize;
use sha2::{Digest, Sha256};
use crate::admin::AdminClient;
use crate::assert::UnwrapAssert;
use crate::endor;
use crate::gossip::GOSSIP_PORT;
use crate::proxy;
use crate::state_dump::StateDump;
/// Everything the report file shows, collected before rendering.
#[derive(Debug, Clone)]
pub struct Report {
/// Unique, time-ordered report ID (ULID).
pub id: String,
/// Capture time (unix seconds).
pub captured_at_unix: u64,
/// Build hash of the CLI producing the report.
pub tool_build: String,
/// Trust snapshot from the daemon's admin socket.
pub dump: StateDump,
/// Interception state inferred from the environment (the intermesh
/// nftables table exists only while interception is active). `None`
/// means it could not be determined.
pub intercept: Option<bool>,
/// Environment probe results, rendered in order.
pub environment: Vec<Probe>,
/// Bounded tail of the daemon's log file. `None` means no log file
/// is configured; `Some(Err(_))` means the read failed.
pub log_tail: Option<Result<LogTail, String>>,
}
/// One environment probe: a label plus its output or an error note.
#[derive(Debug, Clone)]
pub struct Probe {
pub label: String,
pub result: Result<String, String>,
}
/// A bounded tail of a log file, plus the facts needed to say honestly
/// whether older lines were dropped to fit the bound.
#[derive(Debug, Clone)]
pub struct LogTail {
/// The lines shown, newest last (at most `LOG_TAIL_MAX_LINES`).
pub text: String,
/// Lines present in the byte window we examined. If this exceeds the
/// lines shown, the oldest were dropped by the line cap.
pub window_lines: usize,
/// True if the file was larger than `LOG_TAIL_MAX_BYTES`, so history
/// before the byte window exists but was never read.
pub byte_clipped: bool,
}
impl Report {
/// Render the report artifact. Pure: the same `Report` always
/// produces the same text.
#[must_use]
pub fn render(&self) -> String {
let mut out = String::new();
self.header(&mut out);
self.summary(&mut out);
self.identity(&mut out);
self.daemon_config(&mut out);
self.names(&mut out);
self.peers(&mut out);
self.routes_tunnels_listeners(&mut out);
self.environment(&mut out);
// The log tail is the one section that can run to hundreds of
// lines, so it sinks below the compact structured sections.
self.recent_events(&mut out);
self.footer(&mut out);
while out.ends_with("\n\n") {
out.pop();
}
out
}
fn header(&self, out: &mut String) {
let title = "intermesh debug report";
writeln!(out, "{title}").assert();
writeln!(out, "{}", "═".repeat(title.chars().count())).assert();
let fields = [
("node", node_name(&self.dump), ""),
("captured", rfc3339(self.captured_at_unix), ""),
("report id", self.id.clone(), ""),
(
"state",
state_fingerprint(&self.dump),
"(derived mesh view — agreeing nodes share this hash)",
),
(
"inputs",
inputs_digest(&self.dump.derivation.input),
"(this node's endorsements — per-node; new hash = inputs changed)",
),
("tool build", self.tool_build.clone(), ""),
(
"daemon build",
build_or_unknown(&self.dump.daemon_build).to_string(),
"",
),
];
for (label, value, note) in fields {
let label = format!("{label}:");
let line = format!(" {label:<13} {value} {note}");
writeln!(out, "{}", line.trim_end()).assert();
}
out.push('\n');
}
fn summary(&self, out: &mut String) {
writeln!(out, "SUMMARY").assert();
writeln!(
out,
" legend: ✓ ok ⚠ attention ✗ problem ○ planned (not yet built in any release)"
)
.assert();
out.push('\n');
// Daemon running. Reaching this code means the admin socket
// answered; the CLI errors out otherwise.
let mut detail = String::from("admin socket reachable");
let started = self.dump.daemon_started_at_unix;
if started > 0 && self.captured_at_unix >= started {
let up = format_uptime(self.captured_at_unix - started);
write!(detail, ", up {up}").assert();
}
write!(
detail,
", build {}",
build_or_unknown(&self.dump.daemon_build)
)
.assert();
row(out, "✓", "daemon running", &detail);
let names = self.dump.derivation.name_to_imid.len();
let with_ips = self.names_with_ips();
if names == 0 {
row(out, "⚠", "name resolution", "no names derived");
} else {
let symbol = if with_ips == names { "✓" } else { "⚠" };
let detail = format!("{names} names, {with_ips} with IPs");
row(out, symbol, "name resolution", &detail);
}
let peers = self.peer_rows().len();
let detail = format!("{peers} known · reachability (planned — future release)");
row(out, "○", "peers", &detail);
row(out, "○", "tunnels", "(planned — future release)");
let (symbol, detail) = match self.intercept {
Some(true) => {
let mut s = format!("gossip :{GOSSIP_PORT}");
for (name, addr) in proxy::expected_listeners() {
write!(s, ", {name} :{}", addr.port()).assert();
}
s.push_str(" · intercept on");
("✓", s)
}
Some(false) => ("✓", format!("gossip :{GOSSIP_PORT} · intercept off")),
None => ("⚠", format!("gossip :{GOSSIP_PORT} · intercept unknown")),
};
row(out, symbol, "listeners (expected)", &detail);
out.push('\n');
}
fn identity(&self, out: &mut String) {
let d = &self.dump.derivation;
let names = join_or_dash(d.imid_to_names.get(&d.my_imid).map(sorted));
let ips = join_or_dash(d.imid_to_ip.get(&d.my_imid).map(sorted));
writeln!(out, "IDENTITY").assert();
writeln!(
out,
" me {names} {} {ips}",
short(&d.my_imid.to_string())
)
.assert();
out.push('\n');
}
fn daemon_config(&self, out: &mut String) {
let socket = self.dump.admin_socket.as_deref().unwrap_or("(not set)");
let log = self.dump.log_file.as_deref().unwrap_or("(not set)");
writeln!(out, "DAEMON CONFIG").assert();
writeln!(out, " admin socket {socket} · log file {log}").assert();
out.push('\n');
}
fn names(&self, out: &mut String) {
let d = &self.dump.derivation;
writeln!(out, "NAMES → IDENTITIES → IPS").assert();
if d.name_to_imid.is_empty() {
writeln!(out, " (none)").assert();
}
let mut entries: Vec<_> = d.name_to_imid.iter().collect();
entries.sort_by_key(|(name, _)| name.to_string());
for (name, imids) in entries {
let imid_list = sorted(imids)
.iter()
.map(|i| short(i))
.collect::<Vec<_>>()
.join(", ");
let mut ips: BTreeSet<String> = BTreeSet::new();
for imid in imids {
if let Some(set) = d.imid_to_ip.get(imid) {
ips.extend(set.iter().map(ToString::to_string));
}
}
let ips = join_or_dash(Some(ips.into_iter().collect()));
writeln!(out, " {name} → {imid_list} → {ips}").assert();
}
out.push('\n');
}
fn peers(&self, out: &mut String) {
writeln!(out, "PEERS").assert();
let rows = self.peer_rows();
if rows.is_empty() {
writeln!(out, " (none known)").assert();
}
for (imid, names, ips) in rows {
writeln!(
out,
" {} {names} {ips} last contact: (planned — future release)",
short(&imid)
)
.assert();
}
out.push('\n');
}
fn routes_tunnels_listeners(&self, out: &mut String) {
writeln!(out, "ROUTES (name → VIP)").assert();
writeln!(out, " (planned — future release)").assert();
out.push('\n');
writeln!(out, "TUNNELS (open)").assert();
writeln!(out, " (planned — future release)").assert();
out.push('\n');
writeln!(out, "LISTENERS (expected)").assert();
writeln!(out, " {:<8} 0.0.0.0:{GOSSIP_PORT}", "gossip").assert();
if self.intercept == Some(true) {
for (name, addr) in proxy::expected_listeners() {
writeln!(out, " {name:<8} {addr}").assert();
}
}
out.push('\n');
}
fn recent_events(&self, out: &mut String) {
writeln!(out, "RECENT EVENTS").assert();
let path = self.dump.log_file.as_deref().unwrap_or("(unknown path)");
match &self.log_tail {
None => {
writeln!(out, " (no log output recorded — no log file configured)").assert();
}
Some(Ok(tail)) if tail.text.is_empty() => {
writeln!(out, " (no log output recorded — {path} is empty)").assert();
}
Some(Ok(tail)) => {
let shown = tail.text.lines().count();
if tail.byte_clipped {
writeln!(
out,
" log tail: {path} · last {shown} lines \
(log exceeds 64 KiB, older lines omitted)"
)
.assert();
} else if tail.window_lines > shown {
writeln!(
out,
" log tail: {path} · last {shown} of {} lines",
tail.window_lines
)
.assert();
} else {
writeln!(out, " log tail: {path}").assert();
}
for line in tail.text.lines() {
writeln!(out, " {line}").assert();
}
}
Some(Err(e)) => {
writeln!(out, " log tail: {path} — unavailable: {e}").assert();
}
}
out.push('\n');
}
fn environment(&self, out: &mut String) {
writeln!(out, "ENVIRONMENT").assert();
if self.environment.is_empty() {
writeln!(out, " (none captured)").assert();
}
for probe in &self.environment {
match &probe.result {
Ok(value) => {
let mut lines = value.lines();
let first = lines.next().unwrap_or_default();
writeln!(out, " {}: {first}", probe.label).assert();
for line in lines {
writeln!(out, " {line}").assert();
}
}
Err(e) => writeln!(out, " {}: unavailable — {e}", probe.label).assert(),
}
}
out.push('\n');
}
fn footer(&self, out: &mut String) {
let line = format!("end of report · {}", self.id);
writeln!(out, "{}", "═".repeat(line.chars().count())).assert();
writeln!(out, "{line}").assert();
}
/// Names that resolve to at least one IP.
fn names_with_ips(&self) -> usize {
let d = &self.dump.derivation;
d.name_to_imid
.values()
.filter(|imids| {
imids
.iter()
.any(|i| d.imid_to_ip.get(i).is_some_and(|ips| !ips.is_empty()))
})
.count()
}
/// Known peers (every identity except self), sorted by IMID:
/// `(imid, names or "-", ips or "-")`.
fn peer_rows(&self) -> Vec<(String, String, String)> {
let d = &self.dump.derivation;
let me = d.my_imid.to_string();
let mut peers: BTreeMap<String, (BTreeSet<String>, BTreeSet<String>)> = BTreeMap::new();
for (imid, names) in &d.imid_to_names {
let entry = peers.entry(imid.to_string()).or_default();
entry.0.extend(names.iter().map(ToString::to_string));
}
for (imid, ips) in &d.imid_to_ip {
let entry = peers.entry(imid.to_string()).or_default();
entry.1.extend(ips.iter().map(ToString::to_string));
}
peers.remove(&me);
peers
.into_iter()
.map(|(imid, (names, ips))| {
(
imid,
join_or_dash(Some(names.into_iter().collect())),
join_or_dash(Some(ips.into_iter().collect())),
)
})
.collect()
}
}
/// This node's mesh name (lexicographically first if several), or
/// `unknown` if the derivation assigns it none.
#[must_use]
pub fn node_name(dump: &StateDump) -> String {
let d = &dump.derivation;
d.imid_to_names
.get(&d.my_imid)
.map(sorted)
.and_then(|names| names.into_iter().next())
.unwrap_or_else(|| "unknown".to_string())
}
/// Canonical, node-independent view of derived state used for
/// `state_fingerprint`. Node-local fields (`my_imid`, `iteration`,
/// `derived_at`, `my_constraints`, and the `my_authz*` views) are deliberately
/// excluded so two nodes that agree on the mesh produce the same fingerprint.
#[derive(Serialize)]
struct FingerprintView {
names: BTreeMap<String, BTreeSet<String>>,
imids: BTreeMap<String, BTreeSet<String>>,
ips: BTreeMap<String, BTreeSet<String>>,
}
/// Hash of the shared derived view: the "do these nodes agree?"
/// comparison key. Two nodes with the same derived mesh state produce
/// the same fingerprint.
#[must_use]
pub fn state_fingerprint(dump: &StateDump) -> String {
let d = &dump.derivation;
let view = FingerprintView {
names: canonical_map(d.name_to_imid.iter()),
imids: canonical_map(d.imid_to_names.iter()),
ips: canonical_map(d.imid_to_ip.iter()),
};
sha256_short(&serde_json::to_vec(&view).assert())
}
/// Hash of the input endorsement bases. Node-local only: input sets
/// legitimately differ across nodes (some endorsements are never
/// gossiped), so this is a per-node change marker, not a cross-node
/// comparison key.
#[must_use]
pub fn inputs_digest(input: &BTreeSet<endor::Base>) -> String {
sha256_short(&serde_json::to_vec(input).assert())
}
fn canonical_map<'a, K, V>(
entries: impl Iterator<Item = (&'a K, &'a BTreeSet<V>)>,
) -> BTreeMap<String, BTreeSet<String>>
where
K: ToString + 'a,
V: ToString + 'a,
{
entries
.map(|(k, vs)| (k.to_string(), vs.iter().map(ToString::to_string).collect()))
.collect()
}
/// First 16 hex chars of the sha256, in `sha256:<hex>` form. Enough to
/// compare two reports; short enough to keep the header readable.
fn sha256_short(bytes: &[u8]) -> String {
let first8: [u8; 8] = Sha256::digest(bytes)[..8].try_into().assert();
format!("sha256:{:016x}", u64::from_be_bytes(first8))
}
fn rfc3339(unix: u64) -> String {
humantime::format_rfc3339_seconds(UNIX_EPOCH + Duration::from_secs(unix)).to_string()
}
fn format_uptime(secs: u64) -> String {
let days = secs / 86_400;
let hours = secs / 3_600 % 24;
let minutes = secs / 60 % 60;
if days > 0 {
format!("{days}d{hours}h")
} else if hours > 0 {
format!("{hours}h{minutes}m")
} else if minutes > 0 {
format!("{minutes}m")
} else {
format!("{secs}s")
}
}
fn short(s: &str) -> String {
match s.get(..16) {
Some(prefix) if s.len() > 16 => format!("{prefix}…"),
_ => s.to_string(),
}
}
fn build_or_unknown(build: &str) -> &str {
if build.is_empty() {
"unknown"
} else {
build
}
}
fn sorted<T: ToString>(values: &BTreeSet<T>) -> Vec<String> {
let mut v: Vec<String> = values.iter().map(ToString::to_string).collect();
v.sort();
v
}
fn join_or_dash(values: Option<Vec<String>>) -> String {
match values {
Some(v) if !v.is_empty() => v.join(", "),
_ => "-".to_string(),
}
}
fn row(out: &mut String, symbol: &str, label: &str, detail: &str) {
writeln!(out, " {symbol} {label:<22}{detail}").assert();
}
// ============================================================================
// Collection — the impure side. Everything below gathers data and fills
// the model; nothing below renders.
// ============================================================================
const LOG_TAIL_MAX_BYTES: i64 = 64 * 1024;
const LOG_TAIL_MAX_LINES: usize = 200;
const PROBE_MAX_LINES: usize = 25;
const PROBE_MAX_BYTES: usize = 4 * 1024;
/// Run `debug report`: collect, render, write one file, print its path.
///
/// The daemon is the report's primary data source: if the admin socket
/// does not answer we exit with an error rather than write a
/// near-empty file. Every other probe degrades into a note in the
/// report.
pub async fn run(socket_path: Option<PathBuf>) -> Result<()> {
let dump = AdminClient::new(socket_path)
.debug_dump()
.await
.context("cannot collect a report without the daemon; check that it is running")?;
let captured_at_unix = unix_now().as_secs();
let (nftables, intercept) = nftables_probe();
let environment = vec![
command_probe("os", "uname", &["-a"]),
command_probe("interfaces", "ip", &["-brief", "addr"]),
command_probe("routes", "ip", &["route"]),
nftables,
resolver_probe(),
];
let log_tail = collect_log_tail(dump.log_file.as_deref());
let report = Report {
id: new_report_id(),
captured_at_unix,
tool_build: env!("GIT_COMMIT").to_string(),
dump,
intercept,
environment,
log_tail,
};
let path = format!(
"intermesh-report-{}-{}.txt",
node_name(&report.dump),
report.id
);
fs::write(&path, report.render()).with_context(|| format!("failed to write {path}"))?;
println!("{path}");
Ok(())
}
/// Run a command and capture its clipped stdout, degrading to an error
/// note. For probes with no output policy of their own.
fn command_probe(label: &str, cmd: &str, args: &[&str]) -> Probe {
let result = match Command::new(cmd).args(args).output() {
Ok(out) if out.status.success() => {
Ok(clip_probe(String::from_utf8_lossy(&out.stdout).trim()))
}
Ok(out) => Err(format!("{cmd} exited with {}", out.status)),
Err(e) => Err(format!("{cmd} unavailable: {e}")),
};
Probe {
label: label.to_string(),
result,
}
}
/// Cap probe output at the first 25 lines / 4 KiB. The report wants
/// signal, not an inventory — fuller output belongs in a future debug
/// archive. First lines carry the signal here (default route, physical
/// interfaces), unlike the log tail where the newest lines do.
fn clip_probe(text: &str) -> String {
let total = text.lines().count();
let mut out = String::new();
for (i, line) in text.lines().enumerate() {
if i == PROBE_MAX_LINES || out.len() + line.len() > PROBE_MAX_BYTES {
if !out.is_empty() {
out.push('\n');
}
write!(out, "… (+{} lines)", total - i).assert();
return out;
}
if i > 0 {
out.push('\n');
}
out.push_str(line);
}
out
}
/// The nftables probe doubles as the interception detector: the daemon
/// injects the `intermesh` table only while interception is active.
/// When the table exists its rules are included, so a maintainer can
/// check the redirects the daemon actually installed.
fn nftables_probe() -> (Probe, Option<bool>) {
let (result, intercept) = match Command::new("nft")
.args(["list", "table", "ip", "intermesh"])
.output()
{
Ok(out) if out.status.success() => {
let rules = String::from_utf8_lossy(&out.stdout);
(
Ok(format!(
"table ip intermesh present (interception active)\n{}",
clip_probe(rules.trim())
)),
Some(true),
)
}
Ok(_) => (
Ok("table ip intermesh absent (interception inactive)".to_string()),
Some(false),
),
Err(e) => (Err(format!("nft unavailable: {e}")), None),
};
let probe = Probe {
label: "nftables".to_string(),
result,
};
(probe, intercept)
}
fn resolver_probe() -> Probe {
let result = match fs::read_to_string("/etc/resolv.conf") {
Ok(conf) => {
let servers: Vec<&str> = conf
.lines()
.filter_map(|line| line.trim().strip_prefix("nameserver"))
.map(str::trim)
.collect();
if servers.is_empty() {
Ok("no nameservers in /etc/resolv.conf".to_string())
} else {
Ok(servers.join(", "))
}
}
Err(e) => Err(format!("read /etc/resolv.conf: {e}")),
};
Probe {
label: "resolver".to_string(),
result,
}
}
/// Tail of the configured log file; `None` when none is configured.
fn collect_log_tail(path: Option<&str>) -> Option<Result<LogTail, String>> {
Some(tail_file(path?))
}
/// Bounded tail of a log file: at most the last 64 KiB, then at most
/// the last 200 lines of that.
fn tail_file(path: &str) -> Result<LogTail, String> {
let mut file = fs::File::open(path).map_err(|e| format!("open {path}: {e}"))?;
let len = i64::try_from(file.metadata().map_err(|e| e.to_string())?.len()).unwrap_or(i64::MAX);
let byte_clipped = len > LOG_TAIL_MAX_BYTES;
if byte_clipped {
file.seek(SeekFrom::End(-LOG_TAIL_MAX_BYTES))
.map_err(|e| format!("seek {path}: {e}"))?;
}
let mut buf = Vec::new();
file.read_to_end(&mut buf)
.map_err(|e| format!("read {path}: {e}"))?;
let content = String::from_utf8_lossy(&buf);
let window_lines = content.lines().count();
let text = last_lines(&content, LOG_TAIL_MAX_LINES);
Ok(LogTail {
text,
window_lines,
byte_clipped,
})
}
fn last_lines(text: &str, n: usize) -> String {
let lines: Vec<&str> = text.lines().collect();
lines[lines.len().saturating_sub(n)..].join("\n")
}
/// A ULID: 48 bits of unix-ms timestamp then 80 random bits, Crockford
/// base32. Time-ordered, so report filenames sort by capture time.
/// Hand-rolled from deps already in the tree rather than adding one.
fn new_report_id() -> String {
let ms = u64::try_from(unix_now().as_millis()).assert();
let mut random = [0u8; 10];
rand::rng().fill(&mut random);
report_id_at(ms, random)
}
fn report_id_at(unix_ms: u64, random: [u8; 10]) -> String {
let mut bytes = [0u8; 16];
bytes[..6].copy_from_slice(&unix_ms.to_be_bytes()[2..8]);
bytes[6..].copy_from_slice(&random);
base32::encode(base32::Alphabet::Crockford, &bytes)
}
fn unix_now() -> Duration {
SystemTime::now().duration_since(UNIX_EPOCH).assert()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imid::ImidKeypair;
use crate::test_utils::{TestConstraint, TestEndorsement, TestFixture};
use crate::trust_engine::Derivation;
use std::net::IpAddr;
/// A three-node dump: me (10.0.0.1), db (10.0.0.2), and web
/// (10.0.0.3 + `fd00::1`).
fn test_dump() -> StateDump {
let me = ImidKeypair::test_keypair("me");
let db = ImidKeypair::test_keypair("db");
let web = ImidKeypair::test_keypair("web");
let name_to_imid = BTreeMap::from([
(
"me.test.mesh".parse().assert(),
BTreeSet::from([me.to_imid()]),
),
(
"db.test.mesh".parse().assert(),
BTreeSet::from([db.to_imid()]),
),
(
"web.test.mesh".parse().assert(),
BTreeSet::from([web.to_imid()]),
),
]);
let imid_to_names = BTreeMap::from([
(
me.to_imid(),
BTreeSet::from(["me.test.mesh".parse().assert()]),
),
(
db.to_imid(),
BTreeSet::from(["db.test.mesh".parse().assert()]),
),
(
web.to_imid(),
BTreeSet::from(["web.test.mesh".parse().assert()]),
),
]);
let imid_to_ip = BTreeMap::from([
(
me.to_imid(),
BTreeSet::from(["10.0.0.1".parse::<IpAddr>().assert()]),
),
(
db.to_imid(),
BTreeSet::from(["10.0.0.2".parse::<IpAddr>().assert()]),
),
(
web.to_imid(),
BTreeSet::from([
"10.0.0.3".parse::<IpAddr>().assert(),
"fd00::1".parse::<IpAddr>().assert(),
]),
),
]);
StateDump {
derivation: Derivation {
my_imid: me.to_imid(),
iteration: 3,
name_to_imid,
imid_to_names,
imid_to_ip,
my_authz_to: BTreeSet::new(),
my_authz_from: BTreeSet::new(),
my_constraints: BTreeSet::new(),
my_authz: BTreeSet::new(),
derived_at: 0,
input: BTreeSet::new(),
},
admin_socket: Some("/run/intermesh/admin.sock".to_string()),
log_file: None,
daemon_build: "a1b2c3d".to_string(),
daemon_started_at_unix: 1_699_988_480, // 3h12m before capture
}
}
#[test]
fn render_view() {
// Golden test: the full artifact for a healthy three-node mesh.
let dump = test_dump();
let report = Report {
id: "01JR8Z9K3F0000000000000000".to_string(),
captured_at_unix: 1_700_000_000,
tool_build: "e5f6a7b".to_string(),
dump,
intercept: Some(true),
environment: vec![
Probe {
label: "os".to_string(),
result: Ok("Linux 6.8.0-test x86_64".to_string()),
},
Probe {
label: "interfaces".to_string(),
result: Ok("lo UNKNOWN 127.0.0.1/8\neth0 UP 10.2.0.7/24".to_string()),
},
Probe {
label: "nftables".to_string(),
result: Ok(
"table ip intermesh present (interception active)\ntable ip intermesh { chain output { … } }"
.to_string(),
),
},
Probe {
label: "resolver".to_string(),
result: Err("read /etc/resolv.conf: not found".to_string()),
},
],
log_tail: None,
};
let state = state_fingerprint(&report.dump);
let inputs = inputs_digest(&report.dump.derivation.input);
let footer = format!("end of report · {}", report.id);
let footer_rule = "═".repeat(footer.chars().count());
let expected = format!(
r"intermesh debug report
══════════════════════
node: me.test.mesh
captured: 2023-11-14T22:13:20Z
report id: 01JR8Z9K3F0000000000000000
state: {state} (derived mesh view — agreeing nodes share this hash)
inputs: {inputs} (this node's endorsements — per-node; new hash = inputs changed)
tool build: e5f6a7b
daemon build: a1b2c3d
SUMMARY
legend: ✓ ok ⚠ attention ✗ problem ○ planned (not yet built in any release)
✓ daemon running admin socket reachable, up 3h12m, build a1b2c3d
✓ name resolution 3 names, 3 with IPs
○ peers 2 known · reachability (planned — future release)
○ tunnels (planned — future release)
✓ listeners (expected) gossip :9898, proxy :15001, dns :15053, external :9797 · intercept on
IDENTITY
me me.test.mesh Aj1Lizc7Xdv-DjFv… 10.0.0.1
DAEMON CONFIG
admin socket /run/intermesh/admin.sock · log file (not set)
NAMES → IDENTITIES → IPS
db.test.mesh → A1UqiwUlUpEHC0b_… → 10.0.0.2
me.test.mesh → Aj1Lizc7Xdv-DjFv… → 10.0.0.1
web.test.mesh → AoHQqnbGQu_8OBYX… → 10.0.0.3, fd00::1
PEERS
A1UqiwUlUpEHC0b_… db.test.mesh 10.0.0.2 last contact: (planned — future release)
AoHQqnbGQu_8OBYX… web.test.mesh 10.0.0.3, fd00::1 last contact: (planned — future release)
ROUTES (name → VIP)
(planned — future release)
TUNNELS (open)
(planned — future release)
LISTENERS (expected)
gossip 0.0.0.0:9898
proxy 127.0.0.1:15001
dns 127.0.0.1:15053
external 0.0.0.0:9797
ENVIRONMENT
os: Linux 6.8.0-test x86_64
interfaces: lo UNKNOWN 127.0.0.1/8
eth0 UP 10.2.0.7/24
nftables: table ip intermesh present (interception active)
table ip intermesh {{ chain output {{ … }} }}
resolver: unavailable — read /etc/resolv.conf: not found
RECENT EVENTS
(no log output recorded — no log file configured)
{footer_rule}
{footer}
"
);
assert_eq!(report.render(), expected);
// Same model, same text.
assert_eq!(report.render(), report.render());
}
#[test]
fn render_degraded_view() {
// Intercept off, older daemon, log tail present.
let mut dump = test_dump();
dump.daemon_build = String::new();
dump.daemon_started_at_unix = 0;
dump.log_file = Some("/var/log/intermesh.log".to_string());
let report = Report {
id: "01JR8Z9K3F0000000000000001".to_string(),
captured_at_unix: 1_700_000_000,
tool_build: "e5f6a7b".to_string(),
dump,
intercept: Some(false),
environment: vec![],
log_tail: Some(Ok(LogTail {
text: "line one\nline two".to_string(),
window_lines: 2,
byte_clipped: false,
})),
};
let out = report.render();
assert!(out.contains("daemon build: unknown"));
assert!(out.contains("admin socket reachable, build unknown"));
assert!(!out.contains(", up "));
assert!(out.contains("gossip :9898 · intercept off"));
assert!(!out.contains("external"));
assert!(out.contains("log tail: /var/log/intermesh.log"));
assert!(out.contains("\n line one\n line two\n"));
assert!(out.contains("(none captured)"));
// Unknown interception state is flagged, not guessed.
let unknown = Report {
intercept: None,
..report
};
assert!(unknown
.render()
.contains("⚠ listeners (expected) gossip :9898 · intercept unknown"));
}
#[test]
fn recent_events_notes_configured_but_empty_log() {
// A configured log file with no output yet is called out as
// empty — distinct from the unconfigured case pinned by the
// `render_view` golden test.
let mut dump = test_dump();
dump.log_file = Some("/var/log/intermesh.log".to_string());
let report = Report {
id: "01JR8Z9K3F0000000000000002".to_string(),
captured_at_unix: 1_700_000_000,
tool_build: "e5f6a7b".to_string(),
dump,
intercept: Some(false),
environment: vec![],
log_tail: Some(Ok(LogTail {
text: String::new(),
window_lines: 0,
byte_clipped: false,
})),
};
assert!(report
.render()
.contains("(no log output recorded — /var/log/intermesh.log is empty)"));
}
#[test]
fn fingerprint_ignores_node_local_fields() {
let mut fix = TestFixture::new();
let dump_a = test_dump();
// Same shared view from another node's perspective: different self
// identity, iteration, derived_at, constraints, and input.
let mut dump_b = dump_a.clone();
dump_b.derivation.my_imid = ImidKeypair::test_keypair("db").to_imid();
dump_b.derivation.iteration = 99;
dump_b.derivation.derived_at = 123_456;
dump_b.derivation.my_constraints = BTreeSet::from([TestConstraint {
endorser_imids: "me",
any_target: true,
permitted_patterns: "**.test.mesh",
..Default::default()
}
.build(&mut fix)]);
dump_b.derivation.input = BTreeSet::from([TestEndorsement {
endorser: "me",
target_imids: "db",
names: "db.test.mesh",
ips: "10.0.0.2",
..Default::default()
}
.to_base(&mut fix)]);
dump_b.daemon_build = "fffffff".to_string();
dump_b.daemon_started_at_unix = 42;
assert_eq!(state_fingerprint(&dump_a), state_fingerprint(&dump_b));
// Changing the shared view changes the fingerprint.
let mut dump_c = dump_a.clone();
let db = ImidKeypair::test_keypair("db").to_imid();
dump_c
.derivation
.imid_to_ip
.get_mut(&db)
.assert()
.insert("10.9.9.9".parse().assert());
assert_ne!(state_fingerprint(&dump_a), state_fingerprint(&dump_c));
// Format: sha256: prefix plus 16 hex chars.
let fp = state_fingerprint(&dump_a);
assert!(fp.starts_with("sha256:"));
assert_eq!(fp.len(), "sha256:".len() + 16);
}