1use std::cmp::Ordering;
84use std::collections::{BTreeMap, BTreeSet};
85use std::fmt;
86
87use serde::Serialize;
88use serde_json::Value;
89use zenoh_keyexpr::keyexpr;
90
91use crate::authoring::Kind;
92use crate::chunk::is_plain_chunk;
93use crate::contract::{Contract, Resource};
94use crate::freshness::{self, Horizon};
95use crate::grammar::KindToken;
96use crate::template::{Segment, Template};
97
98pub const PROFILE: &str = "link.v1";
100
101const ARCHIVE: &str = "archive.v1";
104
105pub const NAME: &str = "link";
107
108pub const EXPOSURE: &str = "link.exposure";
110
111pub const VOCABULARY: &[&str] = &["exposure"];
114
115pub const PROFILE_V2: &str = "link.v2";
118
119#[must_use]
122pub fn uses_v2(c: &Contract) -> bool {
123 c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
124}
125
126pub const ENVELOPE_BYTES: u64 = 8;
129
130pub const DEFAULT_LEASE_MS: u64 = 10_000;
133
134pub const DEFAULT_WINDOW_S: u64 = 60;
136
137const STOCK_PROTOCOLS: &[&str] = &[
143 "tcp",
144 "udp",
145 "tls",
146 "quic",
147 "serial",
148 "unixpipe",
149 "unixsock-stream",
150 "vsock",
151 "ws",
152];
153
154const ZM_1_10_2_R1_PROTOCOLS: &[&str] = &[
157 "tcp",
158 "udp",
159 "tls",
160 "quic",
161 "serial",
162 "unixpipe",
163 "unixsock-stream",
164 "unixsock-dgram",
165 "vsock",
166 "ws",
167];
168
169pub const MESSAGES: [&str; 9] = [
171 "put",
172 "delete",
173 "declare_subscriber",
174 "query",
175 "declare_queryable",
176 "reply",
177 "liveliness_token",
178 "declare_liveliness_subscriber",
179 "liveliness_query",
180];
181
182pub const PUSH_MESSAGES: [&str; 3] = ["put", "delete", "declare_subscriber"];
184
185pub const FLOWS: [&str; 2] = ["egress", "ingress"];
187
188pub const ZK_DENY: &str = "zk2/**/@zk/**";
190
191pub const ADV_DENY: &str = "zk2/**/@adv/**";
193
194pub const ADMIN_DENY: &str = "@/**";
196
197pub const PUSH_TOKENS: [KindToken; 5] = [
199 KindToken::Stream,
200 KindToken::ExplicitStream,
201 KindToken::State,
202 KindToken::ExplicitState,
203 KindToken::Events,
204];
205
206const MAX_U32: u64 = u32::MAX as u64;
207const MAX_BATCH: u64 = 65_535;
208const MAX_REGION: usize = 32;
209const MAX_KEEP_ALIVE: u64 = 255;
212const MAX_LOSS_PPM: u64 = 1_000_000;
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
218pub enum Profile {
219 #[default]
221 V1,
222 V2,
224}
225
226impl Profile {
227 #[must_use]
229 pub fn as_str(self) -> &'static str {
230 match self {
231 Self::V1 => PROFILE,
232 Self::V2 => PROFILE_V2,
233 }
234 }
235}
236
237const FORK_RELEASE: &str = "zm-1.10.2-r";
240
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
245pub enum Binding {
246 #[default]
248 Zenoh1_10_1,
249 Zenoh1_10_2,
251 Zm1_10_2R1,
255}
256
257impl Binding {
258 pub const ALL: [Binding; 3] = [
260 Binding::Zenoh1_10_1,
261 Binding::Zenoh1_10_2,
262 Binding::Zm1_10_2R1,
263 ];
264
265 pub const NAMES: [&'static str; Binding::ALL.len()] = {
268 let mut names = [""; Binding::ALL.len()];
269 let mut i = 0;
270 while i < names.len() {
271 names[i] = Binding::ALL[i].as_str();
272 i += 1;
273 }
274 names
275 };
276
277 #[must_use]
279 pub const fn as_str(self) -> &'static str {
280 match self {
281 Self::Zenoh1_10_1 => "zenoh-1.10.1",
282 Self::Zenoh1_10_2 => "zenoh-1.10.2",
283 Self::Zm1_10_2R1 => "zm-1.10.2-r1",
284 }
285 }
286
287 #[must_use]
291 pub fn parse(s: &str) -> Option<Binding> {
292 Self::ALL.into_iter().find(|b| b.as_str() == s).or_else(|| {
293 let n = s.strip_prefix(FORK_RELEASE)?;
294 (!n.is_empty() && !n.starts_with('0') && n.bytes().all(|b| b.is_ascii_digit()))
295 .then_some(Binding::Zm1_10_2R1)
296 })
297 }
298
299 #[must_use]
302 pub fn protocols(self) -> &'static [&'static str] {
303 match self {
304 Self::Zenoh1_10_1 | Self::Zenoh1_10_2 => STOCK_PROTOCOLS,
305 Self::Zm1_10_2R1 => ZM_1_10_2_R1_PROTOCOLS,
306 }
307 }
308
309 #[must_use]
314 pub fn defaults(self) -> Transport {
315 Transport {
316 lease_ms: 10_000,
317 keep_alive: 4,
318 wait_before_close_ms: match self {
319 Self::Zenoh1_10_1 | Self::Zenoh1_10_2 => 5_000,
320 Self::Zm1_10_2R1 => 10_000,
321 },
322 sequence: Sequence::Bit32,
323 batch_bytes: MAX_BATCH,
324 open_timeout_ms: DEFAULT_TIMEOUT_MS,
325 accept_timeout_ms: DEFAULT_TIMEOUT_MS,
326 interests_timeout_ms: DEFAULT_TIMEOUT_MS,
327 }
328 }
329}
330
331impl fmt::Display for Binding {
332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333 f.write_str(self.as_str())
334 }
335}
336
337impl Serialize for Binding {
338 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
339 s.serialize_str(self.as_str())
340 }
341}
342
343#[derive(Debug, Clone, PartialEq, Eq)]
346pub struct UnknownBinding(pub String);
347
348impl fmt::Display for UnknownBinding {
349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 write!(
351 f,
352 "not a binding; one of: {}, or {FORK_RELEASE}<n> for a later release of the fork",
353 Binding::NAMES.join(", ")
354 )
355 }
356}
357
358impl std::error::Error for UnknownBinding {}
359
360impl std::str::FromStr for Binding {
363 type Err = UnknownBinding;
364
365 fn from_str(s: &str) -> Result<Self, Self::Err> {
366 Binding::parse(s).ok_or_else(|| UnknownBinding(s.to_owned()))
367 }
368}
369
370impl<'de> serde::Deserialize<'de> for Binding {
374 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
375 let name = String::deserialize(d)?;
376 Binding::parse(&name)
377 .ok_or_else(|| serde::de::Error::unknown_variant(&name, &Binding::NAMES))
378 }
379}
380
381pub const DEFAULT_TIMEOUT_MS: u64 = 10_000;
384
385#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
387pub enum Sequence {
388 Bit8,
389 Bit16,
390 Bit32,
391 Bit64,
392}
393
394impl Sequence {
395 pub const ALL: [Sequence; 4] = [
397 Sequence::Bit8,
398 Sequence::Bit16,
399 Sequence::Bit32,
400 Sequence::Bit64,
401 ];
402
403 #[must_use]
405 pub fn as_str(self) -> &'static str {
406 match self {
407 Self::Bit8 => "8bit",
408 Self::Bit16 => "16bit",
409 Self::Bit32 => "32bit",
410 Self::Bit64 => "64bit",
411 }
412 }
413
414 #[must_use]
416 pub fn parse(s: &str) -> Option<Sequence> {
417 Self::ALL.into_iter().find(|q| q.as_str() == s)
418 }
419
420 #[must_use]
426 pub fn window(self) -> u64 {
427 match self {
428 Self::Bit8 => 1 << 6,
429 Self::Bit16 => 1 << 13,
430 Self::Bit32 => 1 << 27,
431 Self::Bit64 => 1 << 31,
432 }
433 }
434
435 #[must_use]
440 pub fn max_bytes(self) -> u64 {
441 match self {
442 Self::Bit8 => 1,
443 Self::Bit16 => 2,
444 Self::Bit32 => 4,
445 Self::Bit64 => 5,
446 }
447 }
448}
449
450pub const UNSTREAMED_PROTOCOLS: [&str; 3] = ["serial", "ws", "unixsock-dgram"];
456
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
461pub struct PutQos {
462 pub block: bool,
464 pub priority_data: bool,
466 pub express: bool,
468}
469
470impl PutQos {
471 pub const DATA_DROP: PutQos = PutQos {
473 block: false,
474 priority_data: true,
475 express: false,
476 };
477}
478
479#[must_use]
488pub fn allowance(payload: u64, qos: PutQos, sequence: Sequence, protocols: &[String]) -> u64 {
489 let length = match payload {
490 0..128 => 1,
491 128..16_384 => 2,
492 _ => 3,
493 };
494 let push_qos = if qos.priority_data && !qos.block && !qos.express {
495 0
496 } else {
497 2
498 };
499 let frame_qos = if qos.priority_data { 0 } else { 2 };
500 let batch_length = if protocols
501 .iter()
502 .all(|p| UNSTREAMED_PROTOCOLS.contains(&p.as_str()))
503 {
504 0
505 } else {
506 2
507 };
508 3 + length + push_qos + 1 + sequence.max_bytes() + frame_qos + batch_length
509}
510
511#[must_use]
514pub fn fits_batch(
515 payload: u64,
516 batch_bytes: u64,
517 qos: PutQos,
518 sequence: Sequence,
519 protocols: &[String],
520) -> bool {
521 u128::from(payload) + u128::from(allowance(payload, qos, sequence, protocols))
522 <= u128::from(batch_bytes)
523}
524
525impl Serialize for Sequence {
526 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
527 s.serialize_str(self.as_str())
528 }
529}
530
531#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
535pub struct Transport {
536 pub lease_ms: u64,
537 pub keep_alive: u64,
538 pub wait_before_close_ms: u64,
539 pub sequence: Sequence,
540 pub batch_bytes: u64,
541 pub open_timeout_ms: u64,
542 pub accept_timeout_ms: u64,
543 pub interests_timeout_ms: u64,
544}
545
546impl Transport {
547 #[must_use]
551 pub fn value(&self, key: TransportKey) -> Value {
552 match key {
553 TransportKey::Lease => Value::from(self.lease_ms),
554 TransportKey::KeepAlive => Value::from(self.keep_alive),
555 TransportKey::WaitBeforeClose => Value::from(self.wait_before_close_ms * 1_000),
556 TransportKey::Sequence => Value::from(self.sequence.as_str()),
557 TransportKey::BatchBytes => Value::from(self.batch_bytes),
558 TransportKey::OpenTimeout => Value::from(self.open_timeout_ms),
559 TransportKey::AcceptTimeout => Value::from(self.accept_timeout_ms),
560 TransportKey::InterestsTimeout => Value::from(self.interests_timeout_ms),
561 }
562 }
563
564 #[must_use]
567 pub fn keep_alive_interval_ms(&self) -> u64 {
568 self.lease_ms / self.keep_alive.max(1)
569 }
570
571 #[must_use]
574 pub fn keep_alive_interval_words(&self) -> String {
575 let exact = self.lease_ms.is_multiple_of(self.keep_alive.max(1));
576 format!(
577 "{}{} ms",
578 if exact { "" } else { "about " },
579 self.keep_alive_interval_ms()
580 )
581 }
582}
583
584#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
587pub enum TransportKey {
588 Lease,
589 KeepAlive,
590 WaitBeforeClose,
591 Sequence,
592 BatchBytes,
593 OpenTimeout,
594 AcceptTimeout,
595 InterestsTimeout,
596}
597
598impl TransportKey {
599 pub const ALL: [TransportKey; 8] = [
601 TransportKey::Lease,
602 TransportKey::KeepAlive,
603 TransportKey::WaitBeforeClose,
604 TransportKey::Sequence,
605 TransportKey::BatchBytes,
606 TransportKey::OpenTimeout,
607 TransportKey::AcceptTimeout,
608 TransportKey::InterestsTimeout,
609 ];
610
611 #[must_use]
613 pub fn key(self) -> &'static str {
614 match self {
615 Self::Lease => "lease_ms",
616 Self::KeepAlive => "keep_alive",
617 Self::WaitBeforeClose => "wait_before_close_ms",
618 Self::Sequence => "sequence",
619 Self::BatchBytes => "batch_bytes",
620 Self::OpenTimeout => "open_timeout_ms",
621 Self::AcceptTimeout => "accept_timeout_ms",
622 Self::InterestsTimeout => "interests_timeout_ms",
623 }
624 }
625
626 #[must_use]
628 pub fn at(self) -> String {
629 format!("transport.{}", self.key())
630 }
631
632 #[must_use]
635 pub fn path(self) -> &'static str {
636 match self {
637 Self::Lease => "transport/link/tx/lease",
638 Self::KeepAlive => "transport/link/tx/keep_alive",
639 Self::WaitBeforeClose => {
640 "transport/link/tx/queue/congestion_control/block/wait_before_close"
641 }
642 Self::Sequence => "transport/link/tx/sequence_number_resolution",
643 Self::BatchBytes => "transport/link/tx/batch_size",
644 Self::OpenTimeout => "transport/unicast/open_timeout",
645 Self::AcceptTimeout => "transport/unicast/accept_timeout",
646 Self::InterestsTimeout => "routing/interests/timeout",
647 }
648 }
649
650 #[must_use]
652 pub fn of_path(path: &str) -> Option<TransportKey> {
653 Self::ALL.into_iter().find(|k| k.path() == path)
654 }
655}
656
657pub const TIMESTAMPING_OFF: [(&str, bool); 2] = [
663 ("timestamping/enabled/router", false),
664 ("timestamping/enabled/peer", false),
665];
666
667pub const POSTURE_PATHS: [&str; 2] = ["mode", "timestamping/enabled"];
670
671const MODES: [&str; 3] = ["router", "peer", "client"];
674
675#[derive(Debug, Clone, Default, PartialEq)]
686pub struct StatedTransport(pub BTreeMap<String, Value>);
687
688impl StatedTransport {
689 #[must_use]
694 pub fn read(config: &Value) -> StatedTransport {
695 let mut out = BTreeMap::new();
696 let paths = TransportKey::ALL
697 .into_iter()
698 .map(TransportKey::path)
699 .chain(POSTURE_PATHS);
700 for path in paths {
701 let v = path
702 .split('/')
703 .try_fold(config, |node, part| node.get(part));
704 if let Some(v) = v {
705 out.insert(path.to_owned(), v.clone());
706 }
707 }
708 StatedTransport(out)
709 }
710
711 #[must_use]
726 pub fn stamps(&self) -> bool {
727 let mode = match self.0.get("mode") {
728 Some(Value::String(mode)) if MODES.contains(&mode.as_str()) => mode.as_str(),
729 _ => "router",
732 };
733 let default = mode == "router";
734 let read = |value: Option<&Value>| match value {
735 Some(Value::Bool(b)) => *b,
736 _ => default,
739 };
740 match self.0.get("timestamping/enabled") {
741 Some(Value::Object(per_mode)) => read(per_mode.get(mode)),
742 value => read(value),
743 }
744 }
745
746 #[must_use]
754 pub fn null_left_out(&self, key: TransportKey) -> bool {
755 key == TransportKey::InterestsTimeout && matches!(self.0.get(key.path()), Some(Value::Null))
756 }
757
758 fn stated(&self, key: TransportKey) -> Option<&Value> {
762 self.0.get(key.path()).filter(|_| !self.null_left_out(key))
763 }
764
765 #[must_use]
768 pub fn states(&self, key: TransportKey) -> bool {
769 self.stated(key).is_some()
770 }
771
772 #[must_use]
776 pub fn runs(&self, key: TransportKey, defaults: &Transport) -> Value {
777 self.stated(key)
778 .cloned()
779 .unwrap_or_else(|| defaults.value(key))
780 }
781}
782
783#[derive(Debug, Clone, PartialEq, Eq)]
787pub enum Exposure {
788 Host,
790 Link,
792 Invalid(String),
794 Ignored,
796}
797
798impl Exposure {
799 #[must_use]
801 pub fn as_str(&self) -> &'static str {
802 match self {
803 Self::Host => "host",
804 Self::Link => "link",
805 Self::Invalid(_) => "invalid",
806 Self::Ignored => "ignored",
807 }
808 }
809}
810
811#[must_use]
814pub fn exposure(kind: Kind, annotations: &BTreeMap<String, Value>) -> Exposure {
815 if kind == Kind::Operation {
816 return Exposure::Ignored;
817 }
818 match annotations.get(EXPOSURE) {
819 None => Exposure::Host,
820 Some(Value::String(s)) if s == "host" => Exposure::Host,
821 Some(Value::String(s)) if s == "link" => Exposure::Link,
822 Some(v) => Exposure::Invalid(v.to_string()),
823 }
824}
825
826#[must_use]
828pub fn exposure_of(r: &Resource) -> Exposure {
829 exposure(r.kind, &r.annotations)
830}
831
832#[derive(Debug, Clone, Copy, PartialEq, Eq)]
834pub enum Expose {
835 Link,
837 None,
839}
840
841#[derive(Debug, Clone, Copy, PartialEq, Eq)]
843pub enum Pushes {
844 Downsampled,
846 Whole,
848 Denied,
850 None,
852}
853
854impl Pushes {
855 #[must_use]
857 pub fn as_str(self) -> &'static str {
858 match self {
859 Self::Downsampled => "downsampled",
860 Self::Whole => "whole",
861 Self::Denied => "denied",
862 Self::None => "none",
863 }
864 }
865}
866
867#[derive(Debug, Clone, Copy, PartialEq, Eq)]
869pub enum Reason {
870 RequestsOnly,
872 Invalid,
874 Host,
876 FaceClosed,
878 Templated,
881 Unlisted,
884 Timed,
887 Exposed,
889}
890
891impl Reason {
892 #[must_use]
894 pub fn as_str(self) -> &'static str {
895 match self {
896 Self::RequestsOnly => "requests_only",
897 Self::Invalid => "invalid",
898 Self::Host => "host",
899 Self::FaceClosed => "face_closed",
900 Self::Templated => "templated",
901 Self::Unlisted => "unlisted",
902 Self::Timed => "timed",
903 Self::Exposed => "exposed",
904 }
905 }
906}
907
908#[derive(Debug, Clone, Copy, PartialEq, Eq)]
910pub struct Crossing {
911 pub pushes: Pushes,
912 pub reason: Reason,
913}
914
915impl Crossing {
916 #[must_use]
918 pub fn crosses(self) -> bool {
919 matches!(self.pushes, Pushes::Downsampled | Pushes::Whole)
920 }
921}
922
923#[must_use]
926pub fn crossing(
927 token: KindToken,
928 templated: bool,
929 exposure: &Exposure,
930 expose: Expose,
931) -> Crossing {
932 let denied = |reason| Crossing {
933 pushes: Pushes::Denied,
934 reason,
935 };
936 if token == KindToken::Op {
937 return Crossing {
938 pushes: Pushes::None,
939 reason: Reason::RequestsOnly,
940 };
941 }
942 match exposure {
943 Exposure::Ignored => Crossing {
944 pushes: Pushes::None,
945 reason: Reason::RequestsOnly,
946 },
947 Exposure::Invalid(_) => denied(Reason::Invalid),
948 Exposure::Host => denied(Reason::Host),
949 Exposure::Link if expose == Expose::None => denied(Reason::FaceClosed),
950 Exposure::Link if is_stream(token) && templated => denied(Reason::Templated),
951 Exposure::Link if is_stream(token) => Crossing {
952 pushes: Pushes::Downsampled,
953 reason: Reason::Exposed,
954 },
955 Exposure::Link => Crossing {
956 pushes: Pushes::Whole,
957 reason: Reason::Exposed,
958 },
959 }
960}
961
962#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
965pub struct Shape {
966 pub templated: bool,
968 pub frame: bool,
970 pub timed: bool,
973}
974
975impl Shape {
976 #[must_use]
980 pub fn of(
981 token: KindToken,
982 templated: bool,
983 frame: bool,
984 annotations: &BTreeMap<String, Value>,
985 ) -> Self {
986 Shape {
987 templated,
988 frame,
989 timed: is_stream(token) && timed(annotations),
990 }
991 }
992}
993
994#[must_use]
998pub fn timed(annotations: &BTreeMap<String, Value>) -> bool {
999 annotations.contains_key(crate::timing::DEADLINE_MS)
1000}
1001
1002#[must_use]
1010pub fn crossing_v2(
1011 token: KindToken,
1012 shape: Shape,
1013 exposure: &Exposure,
1014 expose: Expose,
1015 listed: Option<bool>,
1016) -> Crossing {
1017 let c = crossing(token, shape.templated, exposure, expose);
1018 let denied = |reason| Crossing {
1019 pushes: Pushes::Denied,
1020 reason,
1021 };
1022 if token == KindToken::Events && c.pushes == Pushes::Whole && listed == Some(false) {
1023 return denied(Reason::Unlisted);
1024 }
1025 if c.pushes != Pushes::Downsampled {
1026 return c;
1027 }
1028 if shape.frame {
1029 if listed == Some(false) {
1030 return denied(Reason::Unlisted);
1031 }
1032 return Crossing {
1033 pushes: Pushes::Whole,
1034 reason: Reason::Exposed,
1035 };
1036 }
1037 if shape.timed {
1038 return denied(Reason::Timed);
1039 }
1040 c
1041}
1042
1043#[must_use]
1047pub fn packed_required(uses_v2: bool, token: KindToken, exposure: &Exposure, packed: bool) -> bool {
1048 uses_v2 && token != KindToken::Op && *exposure == Exposure::Link && !packed
1049}
1050
1051#[must_use]
1056pub fn contract_findings(c: &Contract) -> Vec<Finding> {
1057 let v2 = uses_v2(c);
1058 let mut out: Vec<Finding> = c
1059 .resources
1060 .iter()
1061 .map(|r| Res::of(c, r))
1062 .filter(|r| {
1063 packed_required(
1064 v2,
1065 r.token,
1066 &exposure(kind_of(r.token), &r.annotations),
1067 r.packed,
1068 )
1069 })
1070 .map(|r| {
1071 Finding::new(
1072 Code::PackedRequired,
1073 None,
1074 res_name(&c.iface.to_string(), &r),
1075 )
1076 })
1077 .collect();
1078 sort_findings(&mut out);
1079 out
1080}
1081
1082fn is_stream(token: KindToken) -> bool {
1083 matches!(token, KindToken::Stream | KindToken::ExplicitStream)
1084}
1085
1086fn is_state(token: KindToken) -> bool {
1087 matches!(token, KindToken::State | KindToken::ExplicitState)
1088}
1089
1090#[must_use]
1092pub fn kind_of(token: KindToken) -> Kind {
1093 match token {
1094 KindToken::Stream | KindToken::ExplicitStream => Kind::Stream,
1095 KindToken::State | KindToken::ExplicitState => Kind::State,
1096 KindToken::Events => Kind::Event,
1097 KindToken::Op => Kind::Operation,
1098 }
1099}
1100
1101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1105pub enum Code {
1106 Toml,
1108 UnknownField,
1110 MissingField,
1112 BadValue,
1114 RouterAttach,
1116 SelectInterfaces,
1118 UnknownProtocol,
1120 SharedProtocol,
1122 BatchOverLease,
1124 FarOfTwoFaces,
1128 ServiceUnknown,
1130 ContractUnknown,
1132 TemplatedExposure,
1134 CarveOutOverlap,
1136 IntervalOverHorizon,
1139 ExposureDisagrees,
1142 FrameOverInterval,
1146 FrameOverBatch,
1150 HistoryOnFrame,
1154 OwnerHeartbeatDenied,
1159 WindowUnderOutage,
1161 ZkNotDenied,
1163 WildcardDownsampling,
1165 IntersectingDownsampling,
1167 BlockDisabled,
1170 NearSubjectOnFace,
1174 FaceSubjectMissing,
1177 FaceSubjectBeyondFace,
1180 FaceSubjectMisplaced,
1183 NarrowedTooFar,
1187 TransportMissing,
1189 MovedField,
1192 WaitUnderLease,
1195 KeepAliveFlaps,
1198 SequenceWindow,
1200 OpenUnderHandshake,
1203 ReplyTimeoutShort,
1205 NoArq,
1207 TransportDiffers,
1210 PeerDiffers,
1213 FaceTimestamping,
1216 CatalogMismatch,
1218 PackedRequired,
1221 NotPacked,
1224 FrameUnknown,
1227 EventUnknown,
1231 FrameUnlisted,
1235 KeyframeUnreachable,
1238 HorizonUnderFace,
1241 BlockOverBatch,
1245 KeepAliveNotSuppressed,
1248 TimedDownsampled,
1250 CatalogMissing,
1253 DeviceListed,
1256 PresenceRequired,
1261 EpochOnDevice,
1265 NearOpensUser,
1269 NearOpensUnauthenticated,
1272}
1273
1274impl Code {
1275 #[must_use]
1277 pub fn as_str(self) -> &'static str {
1278 match self {
1279 Self::Toml => "toml",
1280 Self::UnknownField => "unknown_field",
1281 Self::MissingField => "missing_field",
1282 Self::BadValue => "bad_value",
1283 Self::RouterAttach => "router_attach",
1284 Self::SelectInterfaces => "select_interfaces",
1285 Self::UnknownProtocol => "unknown_protocol",
1286 Self::SharedProtocol => "shared_protocol",
1287 Self::BatchOverLease => "batch_over_lease",
1288 Self::FarOfTwoFaces => "far_of_two_faces",
1289 Self::ServiceUnknown => "service_unknown",
1290 Self::ContractUnknown => "contract_unknown",
1291 Self::TemplatedExposure => "templated_exposure",
1292 Self::CarveOutOverlap => "carve_out_overlap",
1293 Self::IntervalOverHorizon => "interval_over_horizon",
1294 Self::ExposureDisagrees => "exposure_disagrees",
1295 Self::FrameOverInterval => "frame_over_interval",
1296 Self::FrameOverBatch => "frame_over_batch",
1297 Self::HistoryOnFrame => "history_on_frame",
1298 Self::OwnerHeartbeatDenied => "owner_heartbeat_denied",
1299 Self::WindowUnderOutage => "window_under_outage",
1300 Self::ZkNotDenied => "zk_not_denied",
1301 Self::WildcardDownsampling => "wildcard_downsampling",
1302 Self::IntersectingDownsampling => "intersecting_downsampling",
1303 Self::BlockDisabled => "block_disabled",
1304 Self::NearSubjectOnFace => "near_subject_on_face",
1305 Self::FaceSubjectMissing => "face_subject_missing",
1306 Self::FaceSubjectBeyondFace => "face_subject_beyond_face",
1307 Self::FaceSubjectMisplaced => "face_subject_misplaced",
1308 Self::NarrowedTooFar => "narrowed_too_far",
1309 Self::TransportMissing => "transport_missing",
1310 Self::MovedField => "moved_field",
1311 Self::WaitUnderLease => "wait_under_lease",
1312 Self::KeepAliveFlaps => "keep_alive_flaps",
1313 Self::SequenceWindow => "sequence_window",
1314 Self::OpenUnderHandshake => "open_under_handshake",
1315 Self::ReplyTimeoutShort => "reply_timeout_short",
1316 Self::NoArq => "no_arq",
1317 Self::TransportDiffers => "transport_differs",
1318 Self::PeerDiffers => "peer_differs",
1319 Self::FaceTimestamping => "face_timestamping",
1320 Self::CatalogMismatch => "catalog_mismatch",
1321 Self::PackedRequired => "packed_required",
1322 Self::NotPacked => "not_packed",
1323 Self::FrameUnknown => "frame_unknown",
1324 Self::EventUnknown => "event_unknown",
1325 Self::FrameUnlisted => "frame_unlisted",
1326 Self::KeyframeUnreachable => "keyframe_unreachable",
1327 Self::HorizonUnderFace => "horizon_under_face",
1328 Self::BlockOverBatch => "block_over_batch",
1329 Self::KeepAliveNotSuppressed => "keep_alive_not_suppressed",
1330 Self::TimedDownsampled => "timed_downsampled",
1331 Self::CatalogMissing => "catalog_missing",
1332 Self::DeviceListed => "device_listed",
1333 Self::PresenceRequired => "presence_required",
1334 Self::EpochOnDevice => "epoch_on_device",
1335 Self::NearOpensUser => "near_opens_user",
1336 Self::NearOpensUnauthenticated => "near_opens_unauthenticated",
1337 }
1338 }
1339
1340 #[must_use]
1342 pub fn severity(self) -> Severity {
1343 match self {
1344 Self::BatchOverLease
1345 | Self::FarOfTwoFaces
1346 | Self::TemplatedExposure
1347 | Self::CarveOutOverlap
1348 | Self::IntervalOverHorizon
1349 | Self::ExposureDisagrees
1350 | Self::FrameOverInterval
1351 | Self::FrameOverBatch
1352 | Self::HistoryOnFrame
1353 | Self::OwnerHeartbeatDenied
1354 | Self::KeepAliveFlaps
1355 | Self::SequenceWindow
1356 | Self::OpenUnderHandshake
1357 | Self::ReplyTimeoutShort
1358 | Self::NoArq
1359 | Self::PeerDiffers
1360 | Self::FaceTimestamping
1361 | Self::NotPacked
1362 | Self::FrameUnlisted
1363 | Self::HorizonUnderFace
1364 | Self::BlockOverBatch
1365 | Self::KeepAliveNotSuppressed
1366 | Self::TimedDownsampled
1367 | Self::EpochOnDevice
1368 | Self::NearOpensUnauthenticated => Severity::Warning,
1369 _ => Severity::Error,
1370 }
1371 }
1372}
1373
1374impl fmt::Display for Code {
1375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1376 f.write_str(self.as_str())
1377 }
1378}
1379
1380impl Serialize for Code {
1381 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1382 s.serialize_str(self.as_str())
1383 }
1384}
1385
1386#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
1388#[serde(rename_all = "snake_case")]
1389pub enum Severity {
1390 Error,
1391 Warning,
1392}
1393
1394#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
1396pub struct Finding {
1397 pub code: Code,
1398 pub severity: Severity,
1399 pub face: Option<String>,
1401 pub at: String,
1404}
1405
1406impl Finding {
1407 #[must_use]
1409 pub fn new(code: Code, face: Option<&str>, at: impl Into<String>) -> Self {
1410 Finding {
1411 code,
1412 severity: code.severity(),
1413 face: face.map(str::to_owned),
1414 at: at.into(),
1415 }
1416 }
1417
1418 #[must_use]
1420 pub fn is_error(&self) -> bool {
1421 self.severity == Severity::Error
1422 }
1423}
1424
1425impl fmt::Display for Finding {
1426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1427 let sev = match self.severity {
1428 Severity::Error => "error",
1429 Severity::Warning => "warning",
1430 };
1431 match &self.face {
1432 Some(face) => write!(f, "{sev} {} [face {face}] {}", self.code, self.at),
1433 None => write!(f, "{sev} {} {}", self.code, self.at),
1434 }
1435 }
1436}
1437
1438pub fn sort_findings(findings: &mut Vec<Finding>) {
1441 findings.sort_by(|a, b| {
1442 a.face
1443 .cmp(&b.face)
1444 .then_with(|| a.at.cmp(&b.at))
1445 .then_with(|| a.code.as_str().cmp(b.code.as_str()))
1446 });
1447 findings.dedup();
1448}
1449
1450#[derive(Debug, Clone, PartialEq, Eq)]
1454pub enum Attach {
1455 Client,
1457 SouthRegion { region: String },
1459 Device { devices: Vec<String> },
1463}
1464
1465impl Attach {
1466 #[must_use]
1468 pub fn devices(&self) -> &[String] {
1469 match self {
1470 Attach::Device { devices } => devices,
1471 _ => &[],
1472 }
1473 }
1474
1475 #[must_use]
1477 pub fn is_device(&self) -> bool {
1478 matches!(self, Attach::Device { .. })
1479 }
1480}
1481
1482#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1485pub enum Opens {
1486 #[default]
1490 Far,
1491 Near,
1493}
1494
1495#[derive(Debug, Clone, PartialEq, Eq)]
1497pub struct Face {
1498 pub far: String,
1500 pub attach: Attach,
1501 pub link_protocols: Vec<String>,
1503 pub expose: Expose,
1504 pub interval_s: Option<u64>,
1506 pub max_outage_s: u64,
1507 pub batch_bytes: u64,
1510 pub link_bps: u64,
1511 pub lease_ms: u64,
1514 pub loss_ppm: Option<u64>,
1517 pub arq: Option<bool>,
1519 pub reply_timeout_ms: Option<u64>,
1522 pub frames: Option<BTreeMap<String, FrameCadence>>,
1527 pub events: Option<BTreeSet<String>>,
1532 pub horizon_s: Option<u64>,
1535 pub opens: Opens,
1538}
1539
1540#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1543pub struct FrameCadence {
1544 pub every_s: u64,
1546 #[serde(skip_serializing_if = "Option::is_none")]
1548 pub keyframe_s: Option<u64>,
1549}
1550
1551impl Face {
1552 #[must_use]
1555 pub fn batch_within_lease(&self) -> bool {
1556 within_lease(self.batch_bytes, self.link_bps, self.lease_ms)
1557 }
1558
1559 #[must_use]
1563 pub fn freq(&self) -> Option<f64> {
1564 self.interval_s
1565 .map(|n| 1.0 / f64::from(u32::try_from(n).unwrap_or(u32::MAX)))
1566 }
1567}
1568
1569fn within_lease(batch_bytes: u64, link_bps: u64, lease_ms: u64) -> bool {
1570 u128::from(batch_bytes) * 24_000 <= u128::from(lease_ms) * u128::from(link_bps)
1571}
1572
1573fn flaps(lease_ms: u64, keep_alive: u64, loss_ppm: u64) -> bool {
1577 use num_bigint::BigUint;
1578 let n = u32::try_from(keep_alive.saturating_sub(1)).unwrap_or(u32::MAX);
1579 let lhs = BigUint::from(172_800_000u64) * keep_alive * BigUint::from(loss_ppm).pow(n);
1580 let rhs = BigUint::from(lease_ms) * BigUint::from(1_000_000u64).pow(n);
1581 lhs > rhs
1582}
1583
1584fn window_filled(sequence: Sequence, batch_bytes: u64, lease_ms: u64, link_bps: u64) -> bool {
1587 u128::from(sequence.window()) * 8 * u128::from(batch_bytes) * 1_000
1588 <= u128::from(lease_ms) * u128::from(link_bps)
1589}
1590
1591fn under_handshake(timeout_ms: u64, link_bps: u64) -> bool {
1594 u128::from(timeout_ms) * u128::from(link_bps) < 6_144_000
1595}
1596
1597fn reply_short(reply_timeout_ms: u64, link_bps: u64, batch_bytes: u64) -> bool {
1600 u128::from(reply_timeout_ms) * u128::from(link_bps) < 128_000 * u128::from(batch_bytes)
1601}
1602
1603#[derive(Debug, Clone, PartialEq, Eq)]
1605pub struct FacePolicy {
1606 pub profile: Profile,
1608 pub system: String,
1609 pub services: Vec<String>,
1611 pub faces: BTreeMap<String, Face>,
1613 pub binding: Binding,
1616 pub binding_name: String,
1620 pub transport: Option<Transport>,
1623 pub catalog: Option<String>,
1626}
1627
1628impl FacePolicy {
1629 #[must_use]
1631 pub fn address(&self, service: &str) -> String {
1632 format!("{}/{service}", self.system)
1633 }
1634
1635 pub fn devices(&self) -> impl Iterator<Item = (&str, &str)> {
1638 self.faces.iter().flat_map(|(name, f)| {
1639 f.attach
1640 .devices()
1641 .iter()
1642 .map(move |d| (name.as_str(), d.as_str()))
1643 })
1644 }
1645
1646 #[must_use]
1650 pub fn device_face(&self, address: &str) -> Option<&str> {
1651 debug_assert!(
1652 self.devices().filter(|(_, d)| *d == address).count() <= 1,
1653 "{address} on more than one device face: the linter's device_listed refuses it"
1654 );
1655 self.devices()
1656 .find(|(_, d)| *d == address)
1657 .map(|(name, _)| name)
1658 }
1659
1660 #[must_use]
1665 pub fn owners(&self) -> Vec<Owner<'_>> {
1666 let mut out: Vec<Owner<'_>> = self
1667 .services
1668 .iter()
1669 .map(|s| Owner {
1670 address: self.address(s),
1671 key: s.as_str(),
1672 device_face: None,
1673 })
1674 .chain(self.devices().map(|(face, d)| Owner {
1675 address: d.to_owned(),
1676 key: d,
1677 device_face: Some(face),
1678 }))
1679 .collect();
1680 out.sort_by(|a, b| a.address.cmp(&b.address));
1681 out
1682 }
1683}
1684
1685#[derive(Debug, Clone, PartialEq, Eq)]
1688pub struct Owner<'a> {
1689 pub address: String,
1691 pub key: &'a str,
1696 pub device_face: Option<&'a str>,
1698}
1699
1700impl FacePolicy {
1701 pub fn far_side(&self, face: &str) -> Result<FarSide, FarSideRefusal> {
1706 let (Profile::V2, Some(transport)) = (self.profile, self.transport) else {
1707 return Err(FarSideRefusal::NotV2);
1708 };
1709 let Some(f) = self.faces.get(face) else {
1710 return Err(FarSideRefusal::NoFace {
1711 face: face.to_owned(),
1712 faces: self.faces.keys().cloned().collect(),
1713 });
1714 };
1715 let (Some(reply_timeout_ms), Some(arq)) = (f.reply_timeout_ms, f.arq) else {
1717 return Err(FarSideRefusal::NotV2);
1718 };
1719 Ok(FarSide {
1720 face: face.to_owned(),
1721 reply_timeout_ms,
1722 arq,
1723 transport,
1724 })
1725 }
1726}
1727
1728pub const SILENT_HORIZONS: u32 = 2;
1733
1734#[derive(Debug, Clone, PartialEq, Eq)]
1739pub struct FarSide {
1740 pub face: String,
1742 pub reply_timeout_ms: u64,
1745 pub arq: bool,
1747 pub transport: Transport,
1749}
1750
1751impl FarSide {
1752 #[must_use]
1754 pub fn reply_timeout(&self) -> std::time::Duration {
1755 std::time::Duration::from_millis(self.reply_timeout_ms)
1756 }
1757
1758 #[must_use]
1761 pub fn at_least(&self, timeout: std::time::Duration) -> std::time::Duration {
1762 timeout.max(self.reply_timeout())
1763 }
1764
1765 #[must_use]
1770 pub fn redeclares(&self) -> bool {
1771 !self.arq
1772 }
1773
1774 #[must_use]
1779 pub fn session_keys(&self) -> Vec<(TransportKey, Value)> {
1780 TransportKey::ALL
1781 .into_iter()
1782 .map(|k| (k, self.transport.value(k)))
1783 .collect()
1784 }
1785
1786 #[must_use]
1789 pub fn silence(horizon: std::time::Duration) -> std::time::Duration {
1790 horizon.saturating_mul(SILENT_HORIZONS)
1791 }
1792}
1793
1794#[derive(Debug, Clone, PartialEq, Eq)]
1796pub enum FarSideRefusal {
1797 NotV2,
1799 NoFace { face: String, faces: Vec<String> },
1801}
1802
1803impl fmt::Display for FarSideRefusal {
1804 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1805 match self {
1806 Self::NotV2 => f.write_str(
1807 "a link.v1 policy states no reply timeout and no transport: a far side reads a \
1808 link.v2 policy (link.v2 §2.20)",
1809 ),
1810 Self::NoFace { face, faces } => write!(
1811 f,
1812 "the policy has no face {face:?}; its faces are {}",
1813 faces.join(", ")
1814 ),
1815 }
1816 }
1817}
1818
1819pub const REPAIRS: u32 = 3;
1821
1822#[must_use]
1841pub fn repair_key(selector: &str, n: u32) -> Option<String> {
1842 if n == 0 || n > REPAIRS {
1843 return None;
1844 }
1845 let chunks: Vec<&str> = selector.split('/').collect();
1846 let kind = (0..chunks.len()).find(|&z| {
1849 chunks[z] == crate::grammar::GRAMMAR
1850 && z + 5 < chunks.len()
1851 && chunks[z + 3].parse::<crate::grammar::IfaceId>().is_ok()
1852 && chunks[z + 4].parse::<KindToken>().is_ok()
1853 })? + 4;
1854 let literal = chunks
1857 .iter()
1858 .position(|c| c.contains(['*', '$']))
1859 .unwrap_or(chunks.len());
1860 let at = literal.checked_sub(1).filter(|&i| i > kind)?;
1861 if !is_plain_chunk(chunks[at]) {
1862 return None;
1863 }
1864 let split = chunks[at].len().checked_sub(usize::try_from(n - 1).ok()?)?;
1865 let chunk = format!("{}$*{}", &chunks[at][..split], &chunks[at][split..]);
1866 let mut out = chunks.clone();
1867 out[at] = &chunk;
1868 let repair = out.join("/");
1869 keyexpr::new(repair.as_str()).ok()?;
1870 Some(repair)
1871}
1872
1873#[must_use]
1880pub fn redeclare_horizon(c: &Contract, r: &Resource) -> Option<std::time::Duration> {
1881 if matches!(r.kind, Kind::State) && freshness::uses_v2(c) {
1882 return None;
1883 }
1884 freshness::horizon_of(r).ttl()
1885}
1886
1887#[must_use]
1891pub fn redeclare_heartbeat_horizon(c: &Contract) -> Option<std::time::Duration> {
1892 if !freshness::uses_v2(c) {
1893 return None;
1894 }
1895 crate::heartbeat::Layout::of(c).horizon()
1896}
1897
1898#[must_use]
1905pub fn redeclare_owner_heartbeat_horizon(
1906 c: &Contract,
1907 class: crate::heartbeat::Class,
1908) -> Option<std::time::Duration> {
1909 if !freshness::uses_v2(c) {
1910 return None;
1911 }
1912 crate::heartbeat::Layout::of(c).class_horizon(class)
1913}
1914
1915#[derive(Debug, Clone)]
1918pub struct Parsed {
1919 pub policy: Option<FacePolicy>,
1920 pub findings: Vec<Finding>,
1921}
1922
1923const TOP_KEYS_V1: &[&str] = &["system", "services", "face"];
1924const TOP_KEYS_V2: &[&str] = &[
1925 "profile",
1926 "system",
1927 "services",
1928 "binding",
1929 "catalog",
1930 "transport",
1931 "face",
1932];
1933
1934#[must_use]
1937pub fn parse(text: &str) -> Parsed {
1938 let refuse = |f: Finding| Parsed {
1939 policy: None,
1940 findings: vec![f],
1941 };
1942 let table: toml::Table = match toml::from_str(text) {
1943 Ok(t) => t,
1944 Err(_) => return refuse(Finding::new(Code::Toml, None, "")),
1945 };
1946 if crate::toml10::first_beyond_toml10(text).is_some() {
1947 return refuse(Finding::new(Code::Toml, None, ""));
1948 }
1949 let mut out = Vec::new();
1950 let profile = match table.get("profile") {
1953 None => Profile::V1,
1954 Some(toml::Value::String(s)) if s == PROFILE_V2 => Profile::V2,
1955 Some(_) => {
1956 out.push(Finding::new(Code::BadValue, None, "profile"));
1957 Profile::V2
1958 }
1959 };
1960 let top = match profile {
1961 Profile::V1 => TOP_KEYS_V1,
1962 Profile::V2 => TOP_KEYS_V2,
1963 };
1964 for k in table.keys() {
1965 if !top.contains(&k.as_str()) {
1966 out.push(Finding::new(Code::UnknownField, None, k.clone()));
1967 }
1968 }
1969 let system = match table.get("system") {
1970 None => {
1971 out.push(Finding::new(Code::MissingField, None, "system"));
1972 None
1973 }
1974 Some(toml::Value::String(s)) if is_plain_chunk(s) => Some(s.clone()),
1975 Some(_) => {
1976 out.push(Finding::new(Code::BadValue, None, "system"));
1977 None
1978 }
1979 };
1980 let services = match table.get("services") {
1981 None => {
1982 out.push(Finding::new(Code::MissingField, None, "services"));
1983 None
1984 }
1985 Some(v) => match plain_list(v) {
1986 Some(l) => Some(l),
1987 None => {
1988 out.push(Finding::new(Code::BadValue, None, "services"));
1989 None
1990 }
1991 },
1992 };
1993 let (binding, catalog, transport) = match profile {
1995 Profile::V1 => (
1996 Some((
1997 Binding::Zenoh1_10_1,
1998 Binding::Zenoh1_10_1.as_str().to_owned(),
1999 )),
2000 None,
2001 None,
2002 ),
2003 Profile::V2 => {
2004 let binding = match table.get("binding") {
2005 None => {
2006 out.push(Finding::new(Code::MissingField, None, "binding"));
2007 None
2008 }
2009 Some(toml::Value::String(s)) => {
2010 let b = Binding::parse(s);
2011 if b.is_none() {
2012 out.push(Finding::new(Code::BadValue, None, "binding"));
2013 }
2014 b.map(|b| (b, s.clone()))
2015 }
2016 Some(_) => {
2017 out.push(Finding::new(Code::BadValue, None, "binding"));
2018 None
2019 }
2020 };
2021 let catalog = match table.get("catalog") {
2022 None => None,
2023 Some(toml::Value::String(s)) if is_catalog_id(s) => Some(s.clone()),
2024 Some(_) => {
2025 out.push(Finding::new(Code::BadValue, None, "catalog"));
2026 None
2027 }
2028 };
2029 let transport = match table.get("transport") {
2030 None => {
2031 out.push(Finding::new(Code::TransportMissing, None, "transport"));
2032 None
2033 }
2034 Some(toml::Value::Table(t)) => Some(parse_transport(t, &mut out)),
2035 Some(_) => {
2036 out.push(Finding::new(Code::BadValue, None, "transport"));
2037 None
2038 }
2039 };
2040 (binding, catalog, transport)
2041 }
2042 };
2043 let ctx = FaceCtx {
2044 profile,
2045 protocols: binding.as_ref().map(|(b, _)| b.protocols()),
2046 transport: transport.as_ref(),
2047 };
2048 let mut faces = BTreeMap::new();
2049 match table.get("face") {
2050 None => out.push(Finding::new(Code::MissingField, None, "face")),
2051 Some(toml::Value::Table(t)) if t.is_empty() => {
2052 out.push(Finding::new(Code::BadValue, None, "face"));
2053 }
2054 Some(toml::Value::Table(t)) => {
2055 for (name, v) in t {
2056 if !is_plain_chunk(name) {
2057 out.push(Finding::new(Code::BadValue, Some(name), ""));
2058 }
2059 match v {
2060 toml::Value::Table(ft) => {
2061 if let Some(face) = parse_face(name, ft, &ctx, &mut out) {
2062 faces.insert(name.clone(), face);
2063 }
2064 }
2065 _ => out.push(Finding::new(Code::BadValue, Some(name), "")),
2066 }
2067 }
2068 }
2069 Some(_) => out.push(Finding::new(Code::BadValue, None, "face")),
2070 }
2071 if let Some(protocols) = ctx.protocols {
2072 shared_protocols(&table, protocols, &mut out);
2073 }
2074 shared_far(&table, &mut out);
2075 if profile == Profile::V2 {
2076 device_listed(&table, system.as_deref(), services.as_deref(), &mut out);
2077 }
2078 sort_findings(&mut out);
2079 let policy = if out.iter().any(Finding::is_error) {
2080 None
2081 } else {
2082 Some(FacePolicy {
2083 profile,
2084 system: system.unwrap_or_default(),
2085 services: services.unwrap_or_default(),
2086 faces,
2087 binding_name: binding.as_ref().map_or_else(
2088 || Binding::default().as_str().to_owned(),
2089 |(_, n)| n.clone(),
2090 ),
2091 binding: binding.map(|(b, _)| b).unwrap_or_default(),
2092 transport: transport.as_ref().and_then(TransportDraft::complete),
2093 catalog,
2094 })
2095 };
2096 Parsed {
2097 policy,
2098 findings: out,
2099 }
2100}
2101
2102fn is_catalog_id(s: &str) -> bool {
2104 s.len() == 8 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
2105}
2106
2107#[derive(Debug, Clone, Default)]
2110struct TransportDraft {
2111 lease_ms: Option<u64>,
2112 keep_alive: Option<u64>,
2113 wait_before_close_ms: Option<u64>,
2114 sequence: Option<Sequence>,
2115 batch_bytes: Option<u64>,
2116 open_timeout_ms: Option<u64>,
2117 accept_timeout_ms: Option<u64>,
2118 interests_timeout_ms: Option<u64>,
2119}
2120
2121impl TransportDraft {
2122 fn complete(&self) -> Option<Transport> {
2123 Some(Transport {
2124 lease_ms: self.lease_ms?,
2125 keep_alive: self.keep_alive?,
2126 wait_before_close_ms: self.wait_before_close_ms?,
2127 sequence: self.sequence?,
2128 batch_bytes: self.batch_bytes?,
2129 open_timeout_ms: self.open_timeout_ms?,
2130 accept_timeout_ms: self.accept_timeout_ms?,
2131 interests_timeout_ms: self.interests_timeout_ms?,
2132 })
2133 }
2134}
2135
2136fn parse_transport(t: &toml::Table, out: &mut Vec<Finding>) -> TransportDraft {
2139 let keys: Vec<&str> = TransportKey::ALL.iter().map(|k| k.key()).collect();
2140 for k in t.keys() {
2141 if !keys.contains(&k.as_str()) {
2142 out.push(Finding::new(
2143 Code::UnknownField,
2144 None,
2145 format!("transport.{k}"),
2146 ));
2147 }
2148 }
2149 let mut int = |key: TransportKey, hi: u64, default: Option<u64>| match t.get(key.key()) {
2150 None => {
2151 if default.is_none() {
2152 out.push(Finding::new(Code::MissingField, None, key.at()));
2153 }
2154 default
2155 }
2156 Some(v) => {
2157 let n = int_in(v, 1, hi);
2158 if n.is_none() {
2159 out.push(Finding::new(Code::BadValue, None, key.at()));
2160 }
2161 n
2162 }
2163 };
2164 let mut d = TransportDraft {
2165 lease_ms: int(TransportKey::Lease, MAX_U32, None),
2166 keep_alive: int(TransportKey::KeepAlive, MAX_KEEP_ALIVE, None),
2167 wait_before_close_ms: int(TransportKey::WaitBeforeClose, MAX_U32, None),
2168 sequence: None,
2169 batch_bytes: int(TransportKey::BatchBytes, MAX_BATCH, Some(MAX_BATCH)),
2170 open_timeout_ms: int(TransportKey::OpenTimeout, MAX_U32, Some(DEFAULT_TIMEOUT_MS)),
2171 accept_timeout_ms: int(
2172 TransportKey::AcceptTimeout,
2173 MAX_U32,
2174 Some(DEFAULT_TIMEOUT_MS),
2175 ),
2176 interests_timeout_ms: int(
2177 TransportKey::InterestsTimeout,
2178 MAX_U32,
2179 Some(DEFAULT_TIMEOUT_MS),
2180 ),
2181 };
2182 d.sequence = match t.get(TransportKey::Sequence.key()) {
2183 None => {
2184 out.push(Finding::new(
2185 Code::MissingField,
2186 None,
2187 TransportKey::Sequence.at(),
2188 ));
2189 None
2190 }
2191 Some(toml::Value::String(s)) => {
2192 let q = Sequence::parse(s);
2193 if q.is_none() {
2194 out.push(Finding::new(
2195 Code::BadValue,
2196 None,
2197 TransportKey::Sequence.at(),
2198 ));
2199 }
2200 q
2201 }
2202 Some(_) => {
2203 out.push(Finding::new(
2204 Code::BadValue,
2205 None,
2206 TransportKey::Sequence.at(),
2207 ));
2208 None
2209 }
2210 };
2211 if let (Some(lease), Some(wbc)) = (d.lease_ms, d.wait_before_close_ms)
2212 && wbc < lease
2213 {
2214 out.push(Finding::new(
2215 Code::WaitUnderLease,
2216 None,
2217 TransportKey::WaitBeforeClose.at(),
2218 ));
2219 }
2220 d
2221}
2222
2223fn plain_list(v: &toml::Value) -> Option<Vec<String>> {
2225 let a = v.as_array()?;
2226 let mut seen = BTreeSet::new();
2227 let mut out = Vec::with_capacity(a.len());
2228 for x in a {
2229 let s = x.as_str().filter(|s| is_plain_chunk(s))?;
2230 if !seen.insert(s) {
2231 return None;
2232 }
2233 out.push(s.to_owned());
2234 }
2235 Some(out)
2236}
2237
2238fn int_in(v: &toml::Value, lo: u64, hi: u64) -> Option<u64> {
2240 let i = v.as_integer()?;
2241 u64::try_from(i).ok().filter(|n| (lo..=hi).contains(n))
2242}
2243
2244fn protocol_list(v: &toml::Value) -> Option<Vec<String>> {
2247 let a = v.as_array()?;
2248 if a.is_empty() {
2249 return None;
2250 }
2251 let mut seen = BTreeSet::new();
2252 let mut out = Vec::with_capacity(a.len());
2253 for x in a {
2254 let s = x.as_str()?;
2255 if !seen.insert(s) {
2256 return None;
2257 }
2258 out.push(s.to_owned());
2259 }
2260 Some(out)
2261}
2262
2263const FACE_KEYS: &[&str] = &[
2264 "far",
2265 "attach",
2266 "region",
2267 "select",
2268 "class",
2269 "expose",
2270 "interval_s",
2271 "max_outage_s",
2272 "batch_bytes",
2273 "link_bps",
2274 "lease_ms",
2275];
2276
2277const FACE_KEYS_V2: &[&str] = &[
2280 "far",
2281 "attach",
2282 "region",
2283 "select",
2284 "class",
2285 "expose",
2286 "interval_s",
2287 "max_outage_s",
2288 "link_bps",
2289 "loss_ppm",
2290 "arq",
2291 "reply_timeout_ms",
2292 "horizon_s",
2293 "frames",
2294 "events",
2295 "devices",
2296 "opens",
2297];
2298
2299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2301enum AttachKind {
2302 Client,
2303 South,
2304 Device,
2305}
2306
2307fn device_list(v: &toml::Value) -> Option<Vec<String>> {
2311 let a = v.as_array()?;
2312 if a.is_empty() {
2313 return None;
2314 }
2315 let mut seen = BTreeSet::new();
2316 for x in a {
2317 let s = x.as_str()?;
2318 let (system, service) = s.split_once('/')?;
2319 if !is_plain_chunk(system) || !is_plain_chunk(service) || !seen.insert(s) {
2320 return None;
2321 }
2322 }
2323 Some(seen.into_iter().map(str::to_owned).collect())
2325}
2326
2327fn parse_frames(
2332 face: &str,
2333 v: &toml::Value,
2334 out: &mut Vec<Finding>,
2335) -> Option<BTreeMap<String, FrameCadence>> {
2336 let at = Some(face);
2337 let toml::Value::Table(t) = v else {
2338 out.push(Finding::new(Code::BadValue, at, "frames"));
2339 return None;
2340 };
2341 let mut ok = true;
2342 let mut frames = BTreeMap::new();
2343 for (k, v) in t {
2344 let entry = format!("frames.{k}");
2345 let mut bad = |out: &mut Vec<Finding>, code: Code, key: String| {
2346 out.push(Finding::new(code, at, key));
2347 ok = false;
2348 };
2349 let name = k.split_once('/').and_then(|(i, rest)| {
2350 let iface: crate::grammar::IfaceId = i.parse().ok()?;
2351 let template = Template::parse(rest).ok().filter(|t| !t.has_params())?;
2352 Some(format!("{iface}/stream/{}", template.as_str()))
2353 });
2354 if name.is_none() {
2355 bad(out, Code::BadValue, entry.clone());
2356 }
2357 let toml::Value::Table(e) = v else {
2358 if name.is_some() {
2359 bad(out, Code::BadValue, entry);
2360 }
2361 continue;
2362 };
2363 for key in e.keys() {
2364 if key != "every_s" && key != "keyframe_s" {
2365 bad(out, Code::UnknownField, format!("{entry}.{key}"));
2366 }
2367 }
2368 let every_s = match e.get("every_s") {
2369 None => {
2370 bad(out, Code::MissingField, format!("{entry}.every_s"));
2371 None
2372 }
2373 Some(v) => {
2374 let n = int_in(v, 1, MAX_U32);
2375 if n.is_none() {
2376 bad(out, Code::BadValue, format!("{entry}.every_s"));
2377 }
2378 n
2379 }
2380 };
2381 let keyframe_s = match e.get("keyframe_s") {
2382 None => Some(None),
2383 Some(v) => {
2384 let n = int_in(v, 1, MAX_U32);
2385 if n.is_none() {
2386 bad(out, Code::BadValue, format!("{entry}.keyframe_s"));
2387 }
2388 n.map(Some)
2389 }
2390 };
2391 if let (Some(name), Some(every_s), Some(keyframe_s)) = (name, every_s, keyframe_s) {
2392 frames.insert(
2393 name,
2394 FrameCadence {
2395 every_s,
2396 keyframe_s,
2397 },
2398 );
2399 }
2400 }
2401 ok.then_some(frames)
2402}
2403
2404fn parse_events(face: &str, v: &toml::Value, out: &mut Vec<Finding>) -> Option<BTreeSet<String>> {
2410 let read = || {
2411 let mut names = BTreeSet::new();
2412 for x in v.as_array()? {
2413 let (i, rest) = x.as_str()?.split_once('/')?;
2414 let iface: crate::grammar::IfaceId = i.parse().ok()?;
2415 let template = Template::parse(rest).ok()?;
2416 if !names.insert(format!("{iface}/events/{}", template.as_str())) {
2417 return None;
2418 }
2419 }
2420 Some(names)
2421 };
2422 let events = read();
2423 if events.is_none() {
2424 out.push(Finding::new(Code::BadValue, Some(face), "events"));
2425 }
2426 events
2427}
2428
2429struct FaceCtx<'a> {
2433 profile: Profile,
2434 protocols: Option<&'static [&'static str]>,
2435 transport: Option<&'a TransportDraft>,
2436}
2437
2438fn parse_face(
2439 name: &str,
2440 t: &toml::Table,
2441 ctx: &FaceCtx<'_>,
2442 out: &mut Vec<Finding>,
2443) -> Option<Face> {
2444 let at = Some(name);
2445 let v2 = ctx.profile == Profile::V2;
2446 let mut ok = true;
2447 let mut bad = |out: &mut Vec<Finding>, code: Code, key: &str| {
2448 out.push(Finding::new(code, at, key));
2449 ok = false;
2450 };
2451 for k in t.keys() {
2452 if v2 && (k == "batch_bytes" || k == "lease_ms") {
2453 bad(out, Code::MovedField, k);
2454 } else if !(if v2 { FACE_KEYS_V2 } else { FACE_KEYS }).contains(&k.as_str()) {
2455 bad(out, Code::UnknownField, k);
2456 }
2457 }
2458 let far = match t.get("far") {
2459 None => {
2460 bad(out, Code::MissingField, "far");
2461 None
2462 }
2463 Some(toml::Value::String(s)) if !s.is_empty() => Some(s.clone()),
2464 Some(_) => {
2465 bad(out, Code::BadValue, "far");
2466 None
2467 }
2468 };
2469 let attach = match t.get("attach") {
2472 None => {
2473 bad(out, Code::MissingField, "attach");
2474 None
2475 }
2476 Some(toml::Value::String(s)) if s == "client" => Some(AttachKind::Client),
2477 Some(toml::Value::String(s)) if s == "south-region" => Some(AttachKind::South),
2478 Some(toml::Value::String(s)) if v2 && s == "device" => Some(AttachKind::Device),
2479 Some(toml::Value::String(s)) if s == "router" => {
2480 bad(out, Code::RouterAttach, "attach");
2481 None
2482 }
2483 Some(_) => {
2484 bad(out, Code::BadValue, "attach");
2485 None
2486 }
2487 };
2488 let region = match t.get("region") {
2489 None => None,
2490 Some(toml::Value::String(s)) if !s.is_empty() && s.len() <= MAX_REGION => Some(s.clone()),
2491 Some(_) => {
2492 bad(out, Code::BadValue, "region");
2493 None
2494 }
2495 };
2496 match (attach, t.contains_key("region")) {
2497 (Some(AttachKind::South), false) => bad(out, Code::MissingField, "region"),
2498 (Some(AttachKind::Client | AttachKind::Device), true) => {
2499 bad(out, Code::BadValue, "region");
2500 }
2501 _ => {}
2502 }
2503 let devices = match t.get("devices") {
2507 Some(v) if v2 => {
2508 let l = device_list(v);
2509 if l.is_none() || matches!(attach, Some(AttachKind::Client | AttachKind::South)) {
2510 bad(out, Code::BadValue, "devices");
2511 }
2512 l
2513 }
2514 _ => None,
2515 };
2516 if attach == Some(AttachKind::Device) && !t.contains_key("devices") {
2517 bad(out, Code::MissingField, "devices");
2518 }
2519 let opens = match t.get("opens") {
2523 Some(v) if v2 => match v.as_str() {
2524 Some("far") => Some(Opens::Far),
2525 Some("near") if !matches!(attach, Some(AttachKind::Client | AttachKind::Device)) => {
2526 Some(Opens::Near)
2527 }
2528 _ => {
2529 bad(out, Code::BadValue, "opens");
2530 None
2531 }
2532 },
2533 _ => Some(Opens::Far),
2534 };
2535 let link_protocols = match t.get("select") {
2536 None => {
2537 bad(out, Code::MissingField, "select");
2538 None
2539 }
2540 Some(toml::Value::Table(s)) => {
2541 for k in s.keys() {
2542 if k == "interfaces" {
2543 bad(out, Code::SelectInterfaces, "select.interfaces");
2544 } else if k != "link_protocols" {
2545 bad(out, Code::UnknownField, &format!("select.{k}"));
2546 }
2547 }
2548 match s.get("link_protocols") {
2549 None => {
2550 bad(out, Code::MissingField, "select.link_protocols");
2551 None
2552 }
2553 Some(v) => match protocol_list(v) {
2554 None => {
2555 bad(out, Code::BadValue, "select.link_protocols");
2556 None
2557 }
2558 Some(l)
2561 if ctx.protocols.is_some_and(|known| {
2562 l.iter().any(|p| !known.contains(&p.as_str()))
2563 }) =>
2564 {
2565 bad(out, Code::UnknownProtocol, "select.link_protocols");
2566 None
2567 }
2568 Some(l) => Some(l),
2569 },
2570 }
2571 }
2572 Some(_) => {
2573 bad(out, Code::BadValue, "select");
2574 None
2575 }
2576 };
2577 match t.get("class") {
2578 None => bad(out, Code::MissingField, "class"),
2579 Some(toml::Value::String(s)) if s == "constrained" => {}
2580 Some(_) => bad(out, Code::BadValue, "class"),
2581 }
2582 let expose = match t.get("expose") {
2583 None => {
2584 bad(out, Code::MissingField, "expose");
2585 None
2586 }
2587 Some(toml::Value::String(s)) if s == "link" => Some(Expose::Link),
2588 Some(toml::Value::String(s)) if s == "none" => Some(Expose::None),
2589 Some(_) => {
2590 bad(out, Code::BadValue, "expose");
2591 None
2592 }
2593 };
2594 let interval_s = match t.get("interval_s") {
2595 None => None,
2596 Some(v) => match int_in(v, 1, MAX_U32) {
2597 Some(n) => Some(n),
2598 None => {
2599 bad(out, Code::BadValue, "interval_s");
2600 None
2601 }
2602 },
2603 };
2604 match (expose, t.contains_key("interval_s")) {
2605 (Some(Expose::Link), false) => bad(out, Code::MissingField, "interval_s"),
2606 (Some(Expose::None), true) => bad(out, Code::BadValue, "interval_s"),
2607 _ => {}
2608 }
2609 let mut int = |key: &str, lo: u64, hi: u64, required: bool| match t.get(key) {
2610 None => {
2611 if required {
2612 bad(out, Code::MissingField, key);
2613 }
2614 None
2615 }
2616 Some(v) => {
2617 let n = int_in(v, lo, hi);
2618 if n.is_none() {
2619 bad(out, Code::BadValue, key);
2620 }
2621 n
2622 }
2623 };
2624 let max_outage_s = int("max_outage_s", 1, MAX_U32, true);
2625 let link_bps = int("link_bps", 1, MAX_U32, true);
2626 if v2 {
2627 let loss_ppm = int("loss_ppm", 0, MAX_LOSS_PPM, true);
2628 let reply_timeout_ms = int("reply_timeout_ms", 1, MAX_U32, true);
2629 let horizon_s = int("horizon_s", 1, MAX_U32, false);
2630 let arq = match t.get("arq") {
2631 None => {
2632 bad(out, Code::MissingField, "arq");
2633 None
2634 }
2635 Some(toml::Value::Boolean(b)) => Some(*b),
2636 Some(_) => {
2637 bad(out, Code::BadValue, "arq");
2638 None
2639 }
2640 };
2641 let frames = match t.get("frames") {
2642 None => Some(None),
2643 Some(v) => {
2644 let f = parse_frames(name, v, out);
2645 if f.is_none() {
2646 ok = false;
2647 }
2648 f.map(Some)
2649 }
2650 };
2651 let events = match t.get("events") {
2652 None => Some(None),
2653 Some(v) => {
2654 let e = parse_events(name, v, out);
2655 if e.is_none() {
2656 ok = false;
2657 }
2658 e.map(Some)
2659 }
2660 };
2661 if expose == Some(Expose::None) {
2665 for key in ["frames", "events", "horizon_s"] {
2666 if t.contains_key(key) {
2667 out.push(Finding::new(Code::BadValue, at, key));
2668 ok = false;
2669 }
2670 }
2671 }
2672 face_lints_v2(
2673 name,
2674 ctx.transport,
2675 link_bps,
2676 loss_ppm,
2677 reply_timeout_ms,
2678 arq,
2679 out,
2680 );
2681 if !ok {
2682 return None;
2683 }
2684 let tr = ctx.transport?;
2691 return Some(Face {
2692 far: far?,
2693 attach: match attach? {
2694 AttachKind::Client => Attach::Client,
2695 AttachKind::South => Attach::SouthRegion { region: region? },
2696 AttachKind::Device => Attach::Device { devices: devices? },
2697 },
2698 link_protocols: link_protocols?,
2699 expose: expose?,
2700 interval_s,
2701 max_outage_s: max_outage_s?,
2702 batch_bytes: tr.batch_bytes?,
2703 link_bps: link_bps?,
2704 lease_ms: tr.lease_ms?,
2705 loss_ppm,
2706 arq,
2707 reply_timeout_ms,
2708 frames: frames?,
2709 events: events?,
2710 horizon_s,
2711 opens: opens?,
2712 });
2713 }
2714 let batch_bytes = int("batch_bytes", 1, MAX_BATCH, true);
2715 let lease_ms = int("lease_ms", 1, MAX_U32, false);
2716 let lease = if t.contains_key("lease_ms") {
2719 lease_ms
2720 } else {
2721 Some(DEFAULT_LEASE_MS)
2722 };
2723 if let (Some(b), Some(bps), Some(l)) = (batch_bytes, link_bps, lease)
2724 && !within_lease(b, bps, l)
2725 {
2726 out.push(Finding::new(Code::BatchOverLease, at, "batch_bytes"));
2727 }
2728 if !ok {
2729 return None;
2730 }
2731 Some(Face {
2732 far: far?,
2733 attach: match attach? {
2734 AttachKind::Client => Attach::Client,
2735 AttachKind::South => Attach::SouthRegion { region: region? },
2736 AttachKind::Device => return None,
2739 },
2740 link_protocols: link_protocols?,
2741 expose: expose?,
2742 interval_s,
2743 max_outage_s: max_outage_s?,
2744 batch_bytes: batch_bytes?,
2745 link_bps: link_bps?,
2746 lease_ms: if t.contains_key("lease_ms") {
2747 lease_ms?
2748 } else {
2749 DEFAULT_LEASE_MS
2750 },
2751 loss_ppm: None,
2752 arq: None,
2753 reply_timeout_ms: None,
2754 frames: None,
2755 events: None,
2756 horizon_s: None,
2757 opens: Opens::Far,
2758 })
2759}
2760
2761fn face_lints_v2(
2765 name: &str,
2766 tr: Option<&TransportDraft>,
2767 link_bps: Option<u64>,
2768 loss_ppm: Option<u64>,
2769 reply_timeout_ms: Option<u64>,
2770 arq: Option<bool>,
2771 out: &mut Vec<Finding>,
2772) {
2773 let at = Some(name);
2774 let tr = tr.cloned().unwrap_or_default();
2775 let mut warn = |code: Code, key: String| out.push(Finding::new(code, at, key));
2776 if let (Some(b), Some(bps), Some(l)) = (tr.batch_bytes, link_bps, tr.lease_ms)
2777 && !within_lease(b, bps, l)
2778 {
2779 warn(Code::BatchOverLease, TransportKey::BatchBytes.at());
2780 }
2781 if let (Some(l), Some(k), Some(p)) = (tr.lease_ms, tr.keep_alive, loss_ppm)
2782 && flaps(l, k, p)
2783 {
2784 warn(Code::KeepAliveFlaps, TransportKey::KeepAlive.at());
2785 }
2786 if let (Some(q), Some(b), Some(l), Some(bps)) =
2787 (tr.sequence, tr.batch_bytes, tr.lease_ms, link_bps)
2788 && window_filled(q, b, l, bps)
2789 {
2790 warn(Code::SequenceWindow, TransportKey::Sequence.at());
2791 }
2792 for (key, timeout) in [
2793 (TransportKey::OpenTimeout, tr.open_timeout_ms),
2794 (TransportKey::AcceptTimeout, tr.accept_timeout_ms),
2795 ] {
2796 if let (Some(t), Some(bps)) = (timeout, link_bps)
2797 && under_handshake(t, bps)
2798 {
2799 warn(Code::OpenUnderHandshake, key.at());
2800 }
2801 }
2802 if let (Some(r), Some(bps), Some(b)) = (reply_timeout_ms, link_bps, tr.batch_bytes)
2803 && reply_short(r, bps, b)
2804 {
2805 warn(Code::ReplyTimeoutShort, "reply_timeout_ms".to_owned());
2806 }
2807 if arq == Some(false) {
2808 warn(Code::NoArq, "arq".to_owned());
2809 }
2810}
2811
2812fn shared_protocols(table: &toml::Table, known: &[&str], out: &mut Vec<Finding>) {
2817 let Some(toml::Value::Table(faces)) = table.get("face") else {
2818 return;
2819 };
2820 let lists: Vec<(&String, Vec<String>)> = faces
2821 .iter()
2822 .filter_map(|(name, v)| {
2823 let l = protocol_list(v.get("select")?.get("link_protocols")?)?;
2824 l.iter()
2825 .all(|p| known.contains(&p.as_str()))
2826 .then_some((name, l))
2827 })
2828 .collect();
2829 for (i, (name, l)) in lists.iter().enumerate() {
2830 let shared = lists
2831 .iter()
2832 .enumerate()
2833 .any(|(j, (_, m))| i != j && l.iter().any(|p| m.contains(p)));
2834 if shared {
2835 out.push(Finding::new(
2836 Code::SharedProtocol,
2837 Some(name),
2838 "select.link_protocols",
2839 ));
2840 }
2841 }
2842}
2843
2844fn shared_far(table: &toml::Table, out: &mut Vec<Finding>) {
2850 let Some(toml::Value::Table(faces)) = table.get("face") else {
2851 return;
2852 };
2853 let mut named: BTreeMap<&str, usize> = BTreeMap::new();
2854 for v in faces.values() {
2855 if let Some(toml::Value::String(far)) = v.get("far")
2856 && !far.is_empty()
2857 {
2858 *named.entry(far.as_str()).or_default() += 1;
2859 }
2860 }
2861 for (far, n) in named {
2862 if n > 1 {
2863 out.push(Finding::new(Code::FarOfTwoFaces, None, far));
2864 }
2865 }
2866}
2867
2868fn device_listed(
2873 table: &toml::Table,
2874 system: Option<&str>,
2875 services: Option<&[String]>,
2876 out: &mut Vec<Finding>,
2877) {
2878 let Some(toml::Value::Table(faces)) = table.get("face") else {
2879 return;
2880 };
2881 let lists: Vec<(&String, Vec<String>)> = faces
2882 .iter()
2883 .filter(|(_, v)| v.get("attach").and_then(toml::Value::as_str) == Some("device"))
2884 .filter_map(|(name, v)| Some((name, device_list(v.get("devices")?)?)))
2885 .collect();
2886 let listed: BTreeSet<String> = match (system, services) {
2887 (Some(sys), Some(services)) => services.iter().map(|s| format!("{sys}/{s}")).collect(),
2888 _ => BTreeSet::new(),
2889 };
2890 for (i, (name, l)) in lists.iter().enumerate() {
2891 let elsewhere = l.iter().any(|d| {
2892 listed.contains(d)
2893 || lists
2894 .iter()
2895 .enumerate()
2896 .any(|(j, (_, m))| i != j && m.contains(d))
2897 });
2898 if elsewhere {
2899 out.push(Finding::new(Code::DeviceListed, Some(name), "devices"));
2900 }
2901 }
2902}
2903
2904fn integer(v: &Value) -> Option<i128> {
2909 v.as_u64()
2910 .map(i128::from)
2911 .or_else(|| v.as_i64().map(i128::from))
2912}
2913
2914#[must_use]
2917pub fn same_value(a: &Value, b: &Value) -> bool {
2918 match (a.as_u64(), b.as_u64()) {
2919 (Some(x), Some(y)) => x == y,
2920 _ => a == b,
2921 }
2922}
2923
2924#[must_use]
2938pub fn check_transport(
2939 policy: &FacePolicy,
2940 router: &StatedTransport,
2941 peer: Option<&StatedTransport>,
2942) -> Vec<Finding> {
2943 let mut out = Vec::new();
2944 let Some(planned) = &policy.transport else {
2945 return out;
2946 };
2947 let defaults = policy.binding.defaults();
2948 for key in TransportKey::ALL {
2949 if !same_value(&planned.value(key), &router.runs(key, &defaults)) {
2950 out.push(Finding::new(Code::TransportDiffers, None, key.at()));
2951 }
2952 }
2953 let lease_us = integer(&router.runs(TransportKey::Lease, &defaults)).map(|ms| ms * 1_000);
2959 let wbc_us = integer(&router.runs(TransportKey::WaitBeforeClose, &defaults));
2960 if let (Some(lease), Some(wbc)) = (lease_us, wbc_us)
2961 && wbc < lease
2962 {
2963 out.push(Finding::new(
2964 Code::WaitUnderLease,
2965 None,
2966 TransportKey::WaitBeforeClose.at(),
2967 ));
2968 }
2969 if let Some(peer) = peer {
2970 for key in [TransportKey::Lease, TransportKey::KeepAlive] {
2971 if !same_value(&router.runs(key, &defaults), &peer.runs(key, &defaults)) {
2972 out.push(Finding::new(Code::PeerDiffers, None, key.at()));
2973 }
2974 }
2975 }
2976 if router.stamps() {
2977 out.push(Finding::new(Code::FaceTimestamping, None, "timestamping"));
2978 }
2979 sort_findings(&mut out);
2980 out
2981}
2982
2983pub fn catalog_id(text: &str) -> Result<String, crate::catalog::Refusal> {
2991 crate::catalog::Catalog::parse(text).map(|c| c.id().hex())
2992}
2993
2994#[must_use]
2997pub fn check_catalog(policy: &FacePolicy, held: &str) -> Vec<Finding> {
2998 if policy.catalog.as_deref() == Some(held) {
2999 Vec::new()
3000 } else {
3001 vec![Finding::new(Code::CatalogMismatch, None, "catalog")]
3002 }
3003}
3004
3005#[derive(Debug, Clone)]
3014pub struct Res {
3015 pub template: Template,
3016 pub token: KindToken,
3017 pub annotations: BTreeMap<String, Value>,
3018 pub history: bool,
3019 pub frame: Option<FrameFacts>,
3020 pub packed: bool,
3024 pub block: bool,
3027 pub priority_data: bool,
3031 pub express: bool,
3033 pub longest_bytes: Option<u64>,
3039 pub link_v2: bool,
3041 pub epoch: Option<String>,
3045 pub tombstone_only: bool,
3050 pub cardinality: Option<u64>,
3056}
3057
3058impl Res {
3059 #[must_use]
3065 pub fn new(template: Template, token: KindToken, annotations: BTreeMap<String, Value>) -> Self {
3066 Res {
3067 history: false,
3068 frame: None,
3069 packed: false,
3070 block: false,
3071 priority_data: true,
3072 express: false,
3073 longest_bytes: None,
3074 link_v2: false,
3075 epoch: None,
3076 tombstone_only: tombstone_only(token, &template, &annotations, |_| false),
3077 cardinality: None,
3078 template,
3079 token,
3080 annotations,
3081 }
3082 }
3083
3084 #[must_use]
3086 pub fn shape(&self) -> Shape {
3087 Shape::of(
3088 self.token,
3089 self.template.has_params(),
3090 self.frame.is_some(),
3091 &self.annotations,
3092 )
3093 }
3094}
3095
3096#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3099pub struct FrameFacts {
3100 pub interval_ms: Option<u64>,
3103 pub largest_bytes: Option<u64>,
3107 pub keyframe_every: u32,
3110}
3111
3112impl Res {
3113 #[must_use]
3115 pub fn qos(&self) -> PutQos {
3116 PutQos {
3117 block: self.block,
3118 priority_data: self.priority_data,
3119 express: self.express,
3120 }
3121 }
3122
3123 #[must_use]
3125 pub fn of(c: &Contract, r: &Resource) -> Self {
3126 let data = match &r.body {
3127 crate::contract::Body::Data(d) => Some(d),
3128 crate::contract::Body::Operation(_) => None,
3129 };
3130 let frame = data.and_then(|d| d.frame.as_ref()).map(|p| FrameFacts {
3131 interval_ms: p.interval_ms(&r.annotations),
3132 largest_bytes: crate::frame::Layout::of_resource(c, r)
3133 .ok()
3134 .flatten()
3135 .map(|l| l.largest_payload_bytes()),
3136 keyframe_every: p.keyframe_every,
3137 });
3138 let packed = data.is_some_and(|d| d.type_.is_packed());
3139 let longest_bytes = match (&frame, data) {
3140 (Some(f), _) => f.largest_bytes,
3141 (None, Some(d)) if packed => c
3142 .packed_layout(&d.type_)
3143 .ok()
3144 .flatten()
3145 .map(|l| ENVELOPE_BYTES + l.max_bits().div_ceil(8)),
3146 _ => None,
3147 };
3148 Res {
3149 template: r.template.clone(),
3150 token: r.token,
3151 annotations: r.annotations.clone(),
3152 history: data.is_some_and(|d| d.history.is_some()),
3153 frame,
3154 packed,
3155 block: data.is_some_and(|d| d.congestion == crate::authoring::Congestion::Block),
3156 priority_data: data.is_none_or(|d| d.priority == crate::authoring::Priority::Data),
3157 express: data.is_some_and(|d| d.express),
3158 longest_bytes,
3159 link_v2: uses_v2(c),
3160 epoch: r.epoch.clone(),
3161 tombstone_only: tombstone_only(r.token, &r.template, &r.annotations, |p| {
3162 c.uses.iter().any(|u| u.to_string() == p)
3163 }),
3164 cardinality: r.cardinality.filter(|_| r.template.has_params()),
3165 }
3166 }
3167}
3168
3169#[must_use]
3190pub fn tombstone_only(
3191 token: KindToken,
3192 template: &Template,
3193 annotations: &BTreeMap<String, Value>,
3194 uses: impl Fn(&str) -> bool,
3195) -> bool {
3196 is_state(token)
3197 && (crate::collection::per_key_in(token, annotations, uses)
3198 || crate::collection::snapshot_prefix(template).is_none())
3199}
3200
3201#[derive(Debug, Clone, Default)]
3204pub struct Deployment {
3205 pub implements: BTreeMap<String, Vec<String>>,
3207 pub interfaces: BTreeMap<String, Vec<Vec<Res>>>,
3213 pub heartbeats: BTreeSet<String>,
3217 pub fingerprints: BTreeMap<String, BTreeSet<crate::canonical::Fingerprint>>,
3221 pub catalog: Option<crate::catalog::Catalog>,
3225 pub governed: BTreeSet<String>,
3229 pub users: BTreeSet<String>,
3233 pub default_allow: bool,
3239 pub owner_heartbeats: BTreeSet<String>,
3245}
3246
3247impl Deployment {
3248 pub fn add_contract(&mut self, c: &Contract) {
3251 if freshness::uses_v2(c) {
3252 self.heartbeats.insert(c.iface.to_string());
3253 }
3254 if crate::redundancy::is_governed(c) {
3255 self.governed.insert(c.iface.to_string());
3256 }
3257 self.fingerprints
3258 .entry(c.iface.to_string())
3259 .or_default()
3260 .insert(crate::canonical::Fingerprint::of(c));
3261 self.add_revision(
3262 c.iface.to_string(),
3263 c.resources.iter().map(|r| Res::of(c, r)).collect(),
3264 );
3265 }
3266
3267 pub fn add_revision(&mut self, iface: impl Into<String>, resources: Vec<Res>) {
3269 self.interfaces
3270 .entry(iface.into())
3271 .or_default()
3272 .push(resources);
3273 }
3274}
3275
3276fn merge(revisions: &[Vec<Res>]) -> (Vec<Res>, BTreeSet<usize>) {
3290 let mut out: Vec<Res> = Vec::new();
3291 let mut readings: Vec<Vec<&Res>> = Vec::new();
3292 for rev in revisions {
3293 for r in rev {
3294 match out
3295 .iter()
3296 .position(|x| x.token == r.token && x.template == r.template)
3297 {
3298 Some(i) => readings[i].push(r),
3299 None => {
3300 out.push(r.clone());
3301 readings.push(vec![r]);
3302 }
3303 }
3304 }
3305 }
3306 let mut disagree = BTreeSet::new();
3307 for (i, rs) in readings.iter().enumerate() {
3308 let links = rs
3309 .iter()
3310 .filter(|r| exposure(kind_of(r.token), &r.annotations) == Exposure::Link)
3311 .count();
3312 out[i].history = rs.iter().any(|r| r.history);
3317 if out[i].epoch.is_none() {
3318 out[i].epoch = rs.iter().find_map(|r| r.epoch.clone());
3319 }
3320 if let Some(f) = &mut out[i].frame {
3321 f.keyframe_every = rs
3322 .iter()
3323 .filter_map(|r| r.frame.map(|f| f.keyframe_every))
3324 .min()
3325 .unwrap_or(f.keyframe_every);
3326 f.largest_bytes = rs
3329 .iter()
3330 .filter_map(|r| r.frame.and_then(|f| f.largest_bytes))
3331 .max();
3332 }
3333 out[i].packed = rs.iter().all(|r| r.packed);
3339 if !timed(&out[i].annotations)
3340 && let Some(d) = rs
3341 .iter()
3342 .find_map(|r| r.annotations.get(crate::timing::DEADLINE_MS))
3343 {
3344 out[i]
3345 .annotations
3346 .insert(crate::timing::DEADLINE_MS.to_owned(), d.clone());
3347 }
3348 let block = rs.iter().any(|r| r.block);
3349 out[i].block = block;
3350 out[i].priority_data = rs.iter().all(|r| r.priority_data);
3353 out[i].express = rs.iter().any(|r| r.express);
3354 out[i].tombstone_only = rs.iter().any(|r| r.tombstone_only);
3355 out[i].cardinality = if rs.iter().any(|r| r.cardinality.is_none()) {
3358 None
3359 } else {
3360 rs.iter().filter_map(|r| r.cardinality).max()
3361 };
3362 out[i].longest_bytes = rs
3363 .iter()
3364 .filter(|r| r.block || !block)
3365 .filter_map(|r| r.longest_bytes)
3366 .max();
3367 if links > 0 && links < rs.len() {
3368 disagree.insert(i);
3369 out[i]
3370 .annotations
3371 .insert(EXPOSURE.to_owned(), Value::String("host".to_owned()));
3372 }
3373 let ttls: Vec<Option<std::time::Duration>> = rs.iter().map(|r| horizon(r).ttl()).collect();
3374 if ttls.windows(2).any(|w| w[0] != w[1]) {
3375 match ttls.into_iter().collect::<Option<Vec<_>>>() {
3376 Some(all) => {
3377 let least = all.into_iter().min().unwrap_or_default();
3378 out[i]
3379 .annotations
3380 .insert(freshness::TTL_S.to_owned(), Value::from(least.as_secs()));
3381 }
3382 None => {
3383 out[i].annotations.remove(freshness::TTL_S);
3384 }
3385 }
3386 }
3387 }
3388 (out, disagree)
3389}
3390
3391#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3395pub struct Deny {
3396 pub id: String,
3397 pub flows: Vec<&'static str>,
3398 pub messages: Vec<&'static str>,
3399 pub key_exprs: Vec<String>,
3400}
3401
3402#[derive(Debug, Clone, PartialEq, Serialize)]
3404pub struct Rule {
3405 pub key_expr: String,
3406 pub freq: f64,
3407}
3408
3409#[derive(Debug, Clone, PartialEq, Serialize)]
3411pub struct Downsampling {
3412 pub id: String,
3413 pub link_protocols: Vec<String>,
3414 pub flows: Vec<&'static str>,
3415 pub messages: Vec<&'static str>,
3416 pub rules: Vec<Rule>,
3417}
3418
3419#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3421pub struct Filter {
3422 #[serde(skip_serializing_if = "Vec::is_empty")]
3423 pub modes: Vec<String>,
3424 #[serde(skip_serializing_if = "Vec::is_empty")]
3425 pub region_names: Vec<String>,
3426}
3427
3428#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3430pub struct South {
3431 pub filters: Vec<Filter>,
3432}
3433
3434#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3436pub struct Gateway {
3437 pub south: Vec<South>,
3438}
3439
3440#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3442#[serde(tag = "shape")]
3443pub enum AttachPlan {
3444 #[serde(rename = "client")]
3445 Client,
3446 #[serde(rename = "south-region")]
3447 SouthRegion { region: String, gateway: Gateway },
3448 #[serde(rename = "device")]
3450 Device { devices: Vec<String> },
3451}
3452
3453#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3457pub struct Window {
3458 pub service: String,
3459 pub min_s: u64,
3460}
3461
3462#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3464pub struct Liveness {
3465 pub service: String,
3466 pub evidence: Vec<String>,
3467}
3468
3469#[derive(Debug, Clone, PartialEq, Serialize)]
3471pub struct FacePlan {
3472 pub name: String,
3473 pub far: String,
3474 pub attach: AttachPlan,
3475 pub deny: Vec<Deny>,
3476 pub downsampling: Option<Downsampling>,
3477 pub windows: Vec<Window>,
3478 pub liveness: Vec<Liveness>,
3479 #[serde(skip_serializing_if = "Option::is_none")]
3482 pub reply_timeout_ms: Option<u64>,
3483 #[serde(skip_serializing_if = "Option::is_none")]
3487 pub frames: Option<Vec<ListedFrame>>,
3488 pub findings: Vec<Finding>,
3489 #[serde(skip)]
3497 pub crossing: BTreeSet<String>,
3498}
3499
3500impl FacePlan {
3501 #[must_use]
3503 pub fn crosses(&self, iface: &str, token: KindToken, template: &Template) -> bool {
3504 self.crossing
3505 .contains(&format!("{iface}/{}/{}", token.as_str(), template.as_str()))
3506 }
3507
3508 #[must_use]
3510 pub fn heartbeat_crosses(&self, iface: &str) -> bool {
3511 self.crossing.contains(&heartbeat_name(iface))
3512 }
3513
3514 #[must_use]
3519 pub fn owner_heartbeat_crosses(&self, class: crate::heartbeat::Class) -> bool {
3520 self.crossing.contains(&owner_heartbeat_name(class))
3521 }
3522}
3523
3524fn heartbeat_name(iface: &str) -> String {
3526 format!("{}/stream/heartbeat/{iface}", freshness::PROFILE_V2)
3527}
3528
3529#[must_use]
3532pub fn owner_heartbeat_name(class: crate::heartbeat::Class) -> String {
3533 format!("{}/stream/heartbeats/{class}", freshness::PROFILE_V2)
3534}
3535
3536#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3538pub struct ListedFrame {
3539 pub resource: String,
3541 #[serde(flatten)]
3542 pub cadence: FrameCadence,
3543}
3544
3545#[derive(Debug, Default)]
3549struct FaceFacts {
3550 crossing: BTreeSet<String>,
3551 unlisted: BTreeSet<String>,
3552 ifaces: BTreeSet<String>,
3553}
3554
3555fn res_name(iface: &str, r: &Res) -> String {
3557 format!("{iface}/{}/{}", r.token.as_str(), r.template.as_str())
3558}
3559
3560pub fn plan(policy: &FacePolicy, deployment: &Deployment) -> Result<Vec<FacePlan>, Vec<Finding>> {
3563 let mut errors = Vec::new();
3564 let mut listed: BTreeSet<&str> = BTreeSet::new();
3565 let services = policy.owners();
3569 for s in &services {
3570 match deployment.implements.get(s.key) {
3571 None => errors.push(Finding::new(Code::ServiceUnknown, None, s.key)),
3572 Some(ifaces) => {
3573 for i in ifaces {
3574 if deployment
3575 .interfaces
3576 .get(i)
3577 .is_some_and(|revs| !revs.is_empty())
3578 {
3579 listed.insert(i);
3580 } else {
3581 errors.push(Finding::new(Code::ContractUnknown, None, i.clone()));
3582 }
3583 if let Some(face) = s.device_face
3586 && (i == ARCHIVE || deployment.governed.contains(i))
3587 {
3588 errors.push(Finding::new(Code::PresenceRequired, Some(face), i.clone()));
3589 }
3590 }
3591 }
3592 }
3593 }
3594 let mut unauthenticated: BTreeSet<&str> = BTreeSet::new();
3599 for (name, face) in &policy.faces {
3600 if face.opens == Opens::Near && deployment.users.contains(&face.far) {
3601 if deployment.default_allow {
3602 unauthenticated.insert(name.as_str());
3603 } else {
3604 errors.push(Finding::new(Code::NearOpensUser, Some(name), "opens"));
3605 }
3606 }
3607 }
3608 if !errors.is_empty() {
3609 sort_findings(&mut errors);
3610 return Err(errors);
3611 }
3612 let view: View = listed
3614 .iter()
3615 .map(|i| ((*i).to_owned(), merge(&deployment.interfaces[*i])))
3616 .collect();
3617 let v2 = policy.profile == Profile::V2;
3618 if v2 {
3620 for i in &listed {
3621 for r in deployment.interfaces[*i].iter().flatten() {
3622 let e = exposure(kind_of(r.token), &r.annotations);
3623 if packed_required(r.link_v2, r.token, &e, r.packed) {
3624 errors.push(Finding::new(Code::PackedRequired, None, res_name(i, r)));
3625 }
3626 }
3627 }
3628 }
3629 let mut faces: Vec<(FacePlan, FaceFacts)> = policy
3630 .faces
3631 .iter()
3632 .map(|(name, face)| {
3633 plan_face(
3634 policy,
3635 deployment,
3636 &view,
3637 &services,
3638 &listed,
3639 name,
3640 face,
3641 &mut errors,
3642 )
3643 })
3644 .collect();
3645 for (p, _) in &mut faces {
3646 if unauthenticated.contains(p.name.as_str()) {
3647 p.findings.push(Finding::new(
3648 Code::NearOpensUnauthenticated,
3649 Some(&p.name),
3650 "opens",
3651 ));
3652 sort_findings(&mut p.findings);
3653 }
3654 }
3655 if v2 {
3656 let crossing: BTreeSet<String> = faces
3658 .iter()
3659 .flat_map(|(_, f)| f.crossing.iter().cloned())
3660 .collect();
3661 for (p, f) in &mut faces {
3662 for n in f.unlisted.iter().filter(|n| !crossing.contains(*n)) {
3663 p.findings
3664 .push(Finding::new(Code::FrameUnlisted, Some(&p.name), n.clone()));
3665 }
3666 sort_findings(&mut p.findings);
3667 }
3668 if let Some(cat) = &deployment.catalog {
3670 let ifaces: BTreeSet<&String> = faces.iter().flat_map(|(_, f)| &f.ifaces).collect();
3671 for i in ifaces {
3672 let Ok(id) = i.parse::<crate::grammar::IfaceId>() else {
3673 continue;
3674 };
3675 for fp in deployment.fingerprints.get(i).into_iter().flatten() {
3676 if cat.index_of(&id, fp).is_none() {
3677 errors.push(Finding::new(
3678 Code::CatalogMissing,
3679 None,
3680 format!("{i}@{fp}"),
3681 ));
3682 }
3683 }
3684 }
3685 }
3686 }
3687 if !errors.is_empty() {
3688 sort_findings(&mut errors);
3689 return Err(errors);
3690 }
3691 Ok(faces.into_iter().map(|(p, _)| p).collect())
3692}
3693
3694type View = BTreeMap<String, (Vec<Res>, BTreeSet<usize>)>;
3697
3698#[allow(clippy::too_many_arguments)]
3699fn plan_face(
3700 policy: &FacePolicy,
3701 deployment: &Deployment,
3702 view: &View,
3703 services: &[Owner<'_>],
3704 listed: &BTreeSet<&str>,
3705 name: &str,
3706 face: &Face,
3707 errors: &mut Vec<Finding>,
3708) -> (FacePlan, FaceFacts) {
3709 let mut findings = Vec::new();
3710 let mut facts = FaceFacts::default();
3711 let v2 = policy.profile == Profile::V2;
3712 let resources_of = |iface: &str| -> &[Res] { &view[iface].0 };
3713 let sequence = policy.transport.map_or(Sequence::Bit32, |t| t.sequence);
3717 let fits = |payload: u64, qos: PutQos| {
3718 fits_batch(
3719 payload,
3720 face.batch_bytes,
3721 qos,
3722 sequence,
3723 &face.link_protocols,
3724 )
3725 };
3726 let crossing_of = |iface: &str, r: &Res| {
3729 let e = exposure(kind_of(r.token), &r.annotations);
3730 if v2 {
3731 let name = res_name(iface, r);
3732 let listed = if r.token == KindToken::Events {
3733 face.events.as_ref().map(|l| l.contains(&name))
3734 } else {
3735 face.frames.as_ref().map(|f| f.contains_key(&name))
3736 };
3737 crossing_v2(r.token, r.shape(), &e, face.expose, listed)
3738 } else {
3739 crossing(r.token, r.template.has_params(), &e, face.expose)
3740 }
3741 };
3742 for entry in face.frames.iter().flat_map(BTreeMap::keys) {
3745 let known = listed.iter().any(|i| {
3746 resources_of(i)
3747 .iter()
3748 .any(|r| r.frame.is_some() && &res_name(i, r) == entry)
3749 });
3750 if !known {
3751 errors.push(Finding::new(Code::FrameUnknown, Some(name), entry.clone()));
3752 }
3753 }
3754 for entry in face.events.iter().flatten() {
3757 let known = listed.iter().any(|i| {
3758 resources_of(i)
3759 .iter()
3760 .any(|r| r.token == KindToken::Events && &res_name(i, r) == entry)
3761 });
3762 if !known {
3763 errors.push(Finding::new(Code::EventUnknown, Some(name), entry.clone()));
3764 }
3765 }
3766 for iface in listed {
3767 let (resources, disagree) = &view[*iface];
3768 for (i, r) in resources.iter().enumerate() {
3769 match crossing_of(iface, r).reason {
3770 Reason::Templated => findings.push(Finding::new(
3771 Code::TemplatedExposure,
3772 Some(name),
3773 res_name(iface, r),
3774 )),
3775 Reason::Timed => findings.push(Finding::new(
3776 Code::TimedDownsampled,
3777 Some(name),
3778 res_name(iface, r),
3779 )),
3780 Reason::Unlisted if r.frame.is_some() => {
3783 facts.unlisted.insert(res_name(iface, r));
3784 }
3785 _ => {}
3786 }
3787 if face.expose == Expose::Link && disagree.contains(&i) {
3788 findings.push(Finding::new(
3789 Code::ExposureDisagrees,
3790 Some(name),
3791 res_name(iface, r),
3792 ));
3793 }
3794 }
3795 }
3796
3797 let mut deny = if face.attach.is_device() {
3800 zk_carve()
3801 } else {
3802 vec![plane("zk", ZK_DENY)]
3803 };
3804 deny.extend([plane("adv", ADV_DENY), plane("admin", ADMIN_DENY)]);
3805 for s in services.iter().filter(|s| s.device_face == Some(name)) {
3808 for iface in &deployment.implements[s.key] {
3809 for r in resources_of(iface).iter().filter(|r| r.epoch.is_some()) {
3810 findings.push(Finding::new(
3811 Code::EpochOnDevice,
3812 Some(name),
3813 res_name(iface, r),
3814 ));
3815 }
3816 }
3817 }
3818 let mut overlapped: BTreeSet<String> = BTreeSet::new();
3820 let mut by_token: BTreeMap<usize, Vec<Deny>> = BTreeMap::new();
3824 let mut heartbeat_crosses: BTreeMap<String, bool> = BTreeMap::new();
3825 let order = [2usize, 3, 4, 0, 1];
3826 for t in order {
3827 let token = PUSH_TOKENS[t];
3828 if token == KindToken::Stream {
3829 heartbeat_crosses = heartbeats_of(deployment, listed, view, &|i: &str, r: &Res| {
3830 crossing_of(i, r).crosses() && !overlapped.contains(&res_name(i, r))
3831 });
3832 }
3833 let mut pseudo: Vec<(Template, bool)> = if token == KindToken::Stream {
3841 heartbeat_crosses
3842 .iter()
3843 .filter_map(|(i, crosses)| {
3844 Template::parse(&format!("heartbeat/{i}"))
3845 .ok()
3846 .map(|t| (t, *crosses))
3847 })
3848 .collect()
3849 } else {
3850 Vec::new()
3851 };
3852 if !pseudo.is_empty() {
3859 let link = heartbeat_crosses.values().any(|c| *c);
3860 let owner: Vec<(String, bool)> = if v2 {
3861 crate::heartbeat::Class::ALL
3862 .into_iter()
3863 .map(|c| {
3864 (
3865 format!("heartbeats/{c}"),
3866 link && c == crate::heartbeat::Class::Link,
3867 )
3868 })
3869 .collect()
3870 } else {
3871 vec![(crate::heartbeat::OWNER_RESOURCE.to_owned(), false)]
3872 };
3873 pseudo.extend(
3874 owner
3875 .into_iter()
3876 .filter_map(|(t, crosses)| Template::parse(&t).ok().map(|t| (t, crosses))),
3877 );
3878 }
3879 let mut groups: BTreeMap<String, Vec<Item<'_>>> = BTreeMap::new();
3880 for iface in listed {
3881 if !pseudo.is_empty() && *iface == freshness::PROFILE_V2 {
3882 continue;
3883 }
3884 groups.insert(
3885 (*iface).to_owned(),
3886 resources_of(iface)
3887 .iter()
3888 .filter(|r| r.token == token)
3889 .map(|r| Item {
3890 template: &r.template,
3891 crosses: crossing_of(iface, r).crosses(),
3892 })
3893 .collect(),
3894 );
3895 }
3896 if !pseudo.is_empty() {
3897 groups.insert(
3898 freshness::PROFILE_V2.to_owned(),
3899 pseudo
3900 .iter()
3901 .map(|(template, crosses)| Item {
3902 template,
3903 crosses: *crosses,
3904 })
3905 .collect(),
3906 );
3907 }
3908 let any = groups.values().flatten().any(|i| i.crosses);
3909 if !any {
3910 by_token.insert(
3911 t,
3912 vec![push_deny(
3913 token.as_str().to_owned(),
3914 vec![format!("zk2/*/*/*/{}/**", token.as_str())],
3915 )],
3916 );
3917 continue;
3918 }
3919 let mut denies = Vec::new();
3920 for (iface, items) in &groups {
3921 let root = format!("zk2/*/*/{iface}/{}", token.as_str());
3922 let keys = if items.iter().any(|i| i.crosses) {
3923 let (keys, exact) = carve(&root, items);
3924 for c in items.iter().filter(|i| i.crosses) {
3925 let hit = exact.iter().any(|&t| {
3926 let t = items[t].template;
3927 t.overlaps(c.template) && c.template.precedence(t) == Ordering::Greater
3928 });
3929 if hit {
3930 let at = format!("{iface}/{}/{}", token.as_str(), c.template.as_str());
3931 overlapped.insert(at.clone());
3932 findings.push(Finding::new(Code::CarveOutOverlap, Some(name), at));
3933 }
3934 }
3935 keys
3936 } else {
3937 vec![format!("{root}/**")]
3938 };
3939 if !keys.is_empty() {
3940 denies.push(push_deny(format!("{}:{iface}", token.as_str()), keys));
3941 }
3942 }
3943 by_token.insert(t, denies);
3944 }
3945 deny.extend(by_token.into_values().flatten());
3946
3947 let crosses = |iface: &str, r: &Res| {
3949 crossing_of(iface, r).crosses() && !overlapped.contains(&res_name(iface, r))
3950 };
3951
3952 let mut rules = Vec::new();
3956 if let Some(freq) = face.freq() {
3957 for s in services.iter().filter(|s| s.device_face != Some(name)) {
3958 for iface in &deployment.implements[s.key] {
3959 for r in resources_of(iface) {
3960 if is_stream(r.token) && r.frame.is_none() && crosses(iface, r) {
3962 rules.push(Rule {
3963 key_expr: format!(
3964 "zk2/{}/{iface}/{}/{}",
3965 s.address,
3966 r.token.as_str(),
3967 r.template.as_str()
3968 ),
3969 freq,
3970 });
3971 }
3972 }
3973 }
3974 }
3975 rules.sort_by(|a, b| a.key_expr.cmp(&b.key_expr));
3976 rules.dedup_by(|a, b| a.key_expr == b.key_expr);
3977 for iface in listed {
3978 for r in resources_of(iface) {
3979 if r.frame.is_some() {
3980 continue;
3981 }
3982 if let (true, Some(ttl), Some(n)) = (
3983 is_stream(r.token) && crosses(iface, r),
3984 horizon(r).ttl(),
3985 face.interval_s,
3986 ) && u128::from(n) * 2 > u128::from(ttl.as_secs())
3987 {
3988 findings.push(Finding::new(
3989 Code::IntervalOverHorizon,
3990 Some(name),
3991 res_name(iface, r),
3992 ));
3993 }
3994 }
3995 }
3996 }
3997 let mut listed_frames = Vec::new();
4001 let mut cadences: Vec<u64> = Vec::new();
4002 for iface in listed {
4003 for r in resources_of(iface) {
4004 let Some(f) = r.frame.filter(|_| crosses(iface, r)) else {
4005 continue;
4006 };
4007 let at = || res_name(iface, r);
4008 let entry = face.frames.as_ref().and_then(|l| l.get(&at())).copied();
4009 let cadence_ms = entry.map_or(f.interval_ms, |e| Some(e.every_s * 1000));
4010 cadences.extend(cadence_ms);
4011 if let Some(e) = entry {
4012 listed_frames.push(ListedFrame {
4013 resource: at(),
4014 cadence: e,
4015 });
4016 if let Some(k) = e.keyframe_s
4019 && u128::from(k) > u128::from(f.keyframe_every) * u128::from(e.every_s)
4020 {
4021 errors.push(Finding::new(Code::KeyframeUnreachable, Some(name), at()));
4022 }
4023 }
4024 if let (Some(i), Some(n)) = (cadence_ms, face.interval_s)
4025 && u128::from(i) < u128::from(n) * 1000
4026 {
4027 findings.push(Finding::new(Code::FrameOverInterval, Some(name), at()));
4028 }
4029 if f.largest_bytes.is_some_and(|b| !fits(b, r.qos())) {
4032 findings.push(Finding::new(Code::FrameOverBatch, Some(name), at()));
4033 }
4034 if r.history {
4035 findings.push(Finding::new(Code::HistoryOnFrame, Some(name), at()));
4036 }
4037 if let (Some(ttl), Some(i)) = (horizon(r).ttl(), cadence_ms)
4038 && u128::from(i) * 2 > ttl.as_millis()
4039 {
4040 findings.push(Finding::new(Code::IntervalOverHorizon, Some(name), at()));
4041 }
4042 if let (true, Some(ttl), Some(h)) = (v2, horizon(r).ttl(), face.horizon_s)
4043 && ttl.as_secs() < h
4044 {
4045 findings.push(Finding::new(Code::HorizonUnderFace, Some(name), at()));
4046 }
4047 }
4048 }
4049 let mut crossing: BTreeSet<String> = listed
4052 .iter()
4053 .flat_map(|iface| {
4054 resources_of(iface)
4055 .iter()
4056 .filter(|r| crosses(iface, r))
4057 .map(|r| res_name(iface, r))
4058 })
4059 .collect();
4060 crossing.extend(
4061 heartbeat_crosses
4062 .iter()
4063 .filter(|(_, c)| **c)
4064 .map(|(i, _)| heartbeat_name(i)),
4065 );
4066 let owner_link = v2 && heartbeat_crosses.values().any(|c| *c);
4069 let owner_at = || owner_heartbeat_name(crate::heartbeat::Class::Link);
4070 if owner_link {
4071 crossing.insert(owner_at());
4072 }
4073 if v2 {
4075 for iface in listed {
4076 for r in resources_of(iface).iter().filter(|r| crosses(iface, r)) {
4077 facts.crossing.insert(res_name(iface, r));
4078 facts.ifaces.insert((*iface).to_owned());
4079 if !r.packed {
4080 findings.push(Finding::new(
4081 Code::NotPacked,
4082 Some(name),
4083 res_name(iface, r),
4084 ));
4085 }
4086 if r.block && r.longest_bytes.is_some_and(|b| !fits(b, r.qos())) {
4087 findings.push(Finding::new(
4088 Code::BlockOverBatch,
4089 Some(name),
4090 res_name(iface, r),
4091 ));
4092 }
4093 }
4094 }
4095 for (iface, crosses) in &heartbeat_crosses {
4098 if !crosses {
4099 continue;
4100 }
4101 facts.ifaces.insert(iface.clone());
4102 let Some(ttl) = heartbeat_horizon(view, iface) else {
4103 continue;
4104 };
4105 cadences.push(ttl.as_secs() * 500);
4106 if face.horizon_s.is_some_and(|h| ttl.as_secs() < h) {
4107 findings.push(Finding::new(
4108 Code::HorizonUnderFace,
4109 Some(name),
4110 heartbeat_name(iface),
4111 ));
4112 }
4113 }
4114 if owner_link {
4118 let (mut under, mut over) = (false, false);
4119 for s in services {
4120 let ifaces = &deployment.implements[s.key];
4121 if ifaces
4126 .iter()
4127 .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
4128 && let Some(ttl) = owner_heartbeat_horizon(view, &heartbeat_crosses, ifaces)
4129 {
4130 cadences.push(ttl.as_secs() * 500);
4131 under |= face.horizon_s.is_some_and(|h| ttl.as_secs() < h);
4132 }
4133 over |=
4137 owner_heartbeat_longest(view, &heartbeat_crosses, ifaces).is_some_and(|b| {
4138 u64::try_from(b)
4139 .ok()
4140 .is_none_or(|b| !fits(b, PutQos::DATA_DROP))
4141 });
4142 }
4143 if under {
4144 findings.push(Finding::new(Code::HorizonUnderFace, Some(name), owner_at()));
4145 }
4146 if over {
4147 findings.push(Finding::new(Code::BlockOverBatch, Some(name), owner_at()));
4148 }
4149 }
4150 if let (Some(t), Some(c)) = (&policy.transport, cadences.iter().min())
4155 && u128::from(*c) * u128::from(t.keep_alive) >= u128::from(t.lease_ms)
4156 {
4157 findings.push(Finding::new(
4158 Code::KeepAliveNotSuppressed,
4159 Some(name),
4160 TransportKey::KeepAlive.at(),
4161 ));
4162 }
4163 }
4164 listed_frames.sort_by(|a, b| a.resource.cmp(&b.resource));
4165 let downsampling = (!rules.is_empty()).then(|| Downsampling {
4166 id: name.to_owned(),
4167 link_protocols: face.link_protocols.clone(),
4168 flows: vec!["egress"],
4169 messages: vec!["put"],
4170 rules,
4171 });
4172
4173 let mut windows = Vec::new();
4175 let mut liveness = Vec::new();
4176 for s in services {
4177 let ifaces = &deployment.implements[s.key];
4178 let resources = || {
4179 ifaces
4180 .iter()
4181 .flat_map(|i| resources_of(i).iter().map(move |r| (i, r)))
4182 };
4183 if resources().any(|(_, r)| is_state(r.token) && (!v2 || r.tombstone_only)) {
4187 windows.push(Window {
4188 service: s.address.clone(),
4189 min_s: face.max_outage_s,
4190 });
4191 }
4192 let mut evidence: Vec<String> = resources()
4193 .filter(|(i, r)| crosses(i, r) && horizon(r).ttl().is_some())
4194 .map(|(i, r)| res_name(i, r))
4195 .collect();
4196 if !v2
4202 && deployment.owner_heartbeats.contains(s.key)
4203 && ifaces
4204 .iter()
4205 .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
4206 {
4207 findings.push(Finding::new(Code::OwnerHeartbeatDenied, Some(name), s.key));
4208 }
4209 evidence.extend(
4212 ifaces
4213 .iter()
4214 .filter(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
4215 .map(|i| heartbeat_name(i)),
4216 );
4217 if owner_link
4221 && ifaces
4222 .iter()
4223 .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
4224 {
4225 evidence.push(owner_at());
4226 }
4227 evidence.sort();
4228 evidence.dedup();
4229 liveness.push(Liveness {
4230 service: s.address.clone(),
4231 evidence,
4232 });
4233 }
4234
4235 sort_findings(&mut findings);
4236 let plan = FacePlan {
4237 name: name.to_owned(),
4238 far: face.far.clone(),
4239 attach: match &face.attach {
4240 Attach::Client => AttachPlan::Client,
4241 Attach::SouthRegion { region } => AttachPlan::SouthRegion {
4242 region: region.clone(),
4243 gateway: gateway(region),
4244 },
4245 Attach::Device { devices } => AttachPlan::Device {
4246 devices: devices.clone(),
4247 },
4248 },
4249 deny,
4250 downsampling,
4251 windows,
4252 liveness,
4253 reply_timeout_ms: face.reply_timeout_ms,
4254 frames: face.frames.as_ref().map(|_| listed_frames),
4255 findings,
4256 crossing,
4257 };
4258 (plan, facts)
4259}
4260
4261fn horizon(r: &Res) -> Horizon {
4262 freshness::horizon(kind_of(r.token), &r.annotations)
4263}
4264
4265fn heartbeat_horizon(view: &View, iface: &str) -> Option<std::time::Duration> {
4268 view.get(iface)?
4269 .0
4270 .iter()
4271 .filter(|r| is_state(r.token))
4272 .filter_map(|r| horizon(r).ttl())
4273 .min()
4274}
4275
4276fn is_collection(r: &Res) -> bool {
4279 is_state(r.token) && horizon(r).ttl().is_some()
4280}
4281
4282fn is_link(r: &Res) -> bool {
4286 exposure(kind_of(r.token), &r.annotations) == Exposure::Link
4287}
4288
4289fn owner_heartbeat_groups<'a>(
4296 view: &'a View,
4297 heartbeats: &'a BTreeMap<String, bool>,
4298 ifaces: &'a [String],
4299) -> impl Iterator<Item = &'a [Res]> {
4300 let mut seen = BTreeSet::new();
4301 ifaces
4302 .iter()
4303 .filter(move |i| heartbeats.contains_key(i.as_str()) && seen.insert(i.as_str()))
4304 .filter_map(|i| view.get(i.as_str()))
4305 .map(|(resources, _)| resources.as_slice())
4306 .filter(|rs| rs.iter().any(|r| is_collection(r) && is_link(r)))
4307}
4308
4309fn owner_heartbeat_horizon(
4312 view: &View,
4313 heartbeats: &BTreeMap<String, bool>,
4314 ifaces: &[String],
4315) -> Option<std::time::Duration> {
4316 owner_heartbeat_groups(view, heartbeats, ifaces)
4317 .flatten()
4318 .filter(|r| is_collection(r) && is_link(r))
4319 .filter_map(|r| horizon(r).ttl())
4320 .min()
4321}
4322
4323fn owner_heartbeat_longest(
4337 view: &View,
4338 heartbeats: &BTreeMap<String, bool>,
4339 ifaces: &[String],
4340) -> Option<u128> {
4341 use crate::heartbeat::{GROUPS_BITS, INDEX_BITS, TIME_BITS};
4342 let mut body = u128::from(TIME_BITS + GROUPS_BITS);
4343 let mut groups = 0;
4344 for resources in owner_heartbeat_groups(view, heartbeats, ifaces) {
4345 let collections = || resources.iter().filter(|r| is_collection(r));
4346 let sections: u128 = collections().count() as u128
4347 + collections()
4348 .filter(|r| is_link(r))
4349 .map(|r| {
4350 crate::heartbeat::longest_section_bits(
4351 r.template
4352 .has_params()
4353 .then(|| r.cardinality.unwrap_or(u64::from(u32::MAX))),
4354 )
4355 })
4356 .sum::<u128>();
4357 body += u128::from(INDEX_BITS + 4) + crate::heartbeat::size_bits(sections) + sections;
4358 groups += 1;
4359 }
4360 (groups > 0).then(|| u128::from(ENVELOPE_BYTES) + body.div_ceil(8))
4361}
4362
4363fn heartbeats_of(
4369 deployment: &Deployment,
4370 listed: &BTreeSet<&str>,
4371 view: &View,
4372 crosses: &dyn Fn(&str, &Res) -> bool,
4373) -> BTreeMap<String, bool> {
4374 let mut out = BTreeMap::new();
4375 for iface in listed {
4376 if !deployment.heartbeats.contains(*iface) {
4377 continue;
4378 }
4379 let collections: Vec<&Res> = view[*iface]
4380 .0
4381 .iter()
4382 .filter(|r| is_state(r.token) && horizon(r).ttl().is_some())
4383 .collect();
4384 if collections.is_empty() {
4385 continue;
4386 }
4387 out.insert(
4388 (*iface).to_owned(),
4389 collections.iter().any(|r| crosses(iface, r)),
4390 );
4391 }
4392 out
4393}
4394
4395fn plane(id: &str, key: &str) -> Deny {
4396 Deny {
4397 id: id.to_owned(),
4398 flows: FLOWS.to_vec(),
4399 messages: MESSAGES.to_vec(),
4400 key_exprs: vec![key.to_owned()],
4401 }
4402}
4403
4404pub const OWN_PAIRS: [(&str, &str); 7] = [
4409 ("ingress", "put"),
4410 ("ingress", "delete"),
4411 ("ingress", "declare_queryable"),
4412 ("ingress", "reply"),
4413 ("ingress", "liveliness_token"),
4414 ("egress", "query"),
4415 ("egress", "declare_subscriber"),
4416];
4417
4418pub const ZK_CARVED: [&str; 3] = [
4421 "zk2/*/*/@zk/alive/**",
4422 "zk2/*/*/@zk/member/**",
4423 "zk2/@zk/**",
4424];
4425
4426pub const ZK_INSTANCE: &str = "zk2/*/*/@zk/instance/**";
4429
4430fn outside_own(flow: &str) -> Vec<&'static str> {
4433 MESSAGES
4434 .iter()
4435 .copied()
4436 .filter(|m| !OWN_PAIRS.contains(&(flow, *m)))
4437 .collect()
4438}
4439
4440#[must_use]
4446pub fn zk_carve() -> Vec<Deny> {
4447 let mut out = vec![Deny {
4448 id: "zk".to_owned(),
4449 flows: FLOWS.to_vec(),
4450 messages: MESSAGES.to_vec(),
4451 key_exprs: ZK_CARVED.iter().map(|k| (*k).to_owned()).collect(),
4452 }];
4453 for flow in FLOWS {
4454 out.push(Deny {
4455 id: format!("zk:instance:{flow}"),
4456 flows: vec![flow],
4457 messages: outside_own(flow),
4458 key_exprs: vec![ZK_INSTANCE.to_owned()],
4459 });
4460 }
4461 out
4462}
4463
4464fn push_deny(id: String, mut key_exprs: Vec<String>) -> Deny {
4465 key_exprs.sort();
4466 key_exprs.dedup();
4467 Deny {
4468 id,
4469 flows: FLOWS.to_vec(),
4470 messages: PUSH_MESSAGES.to_vec(),
4471 key_exprs,
4472 }
4473}
4474
4475#[must_use]
4478pub fn gateway(region: &str) -> Gateway {
4479 Gateway {
4480 south: vec![
4481 South {
4482 filters: vec![Filter {
4483 modes: vec!["peer".to_owned(), "client".to_owned()],
4484 region_names: Vec::new(),
4485 }],
4486 },
4487 South {
4488 filters: vec![Filter {
4489 modes: Vec::new(),
4490 region_names: vec![region.to_owned()],
4491 }],
4492 },
4493 ],
4494 }
4495}
4496
4497struct Item<'a> {
4500 template: &'a Template,
4501 crosses: bool,
4502}
4503
4504#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
4506enum Seg {
4507 Lit(String),
4508 Param,
4509 Rest,
4510}
4511
4512impl Seg {
4513 fn of(s: &Segment) -> Self {
4514 match s {
4515 Segment::Literal(l) => Seg::Lit(l.clone()),
4516 Segment::Param(_) => Seg::Param,
4517 Segment::Rest(_) => Seg::Rest,
4518 }
4519 }
4520
4521 fn kind(&self) -> u8 {
4522 match self {
4523 Seg::Lit(_) => 0,
4524 Seg::Param => 1,
4525 Seg::Rest => 2,
4526 }
4527 }
4528
4529 fn pattern(&self) -> &str {
4531 match self {
4532 Seg::Lit(l) => l,
4533 Seg::Param => "*",
4534 Seg::Rest => "*/**",
4535 }
4536 }
4537}
4538
4539fn key(root: &str, prefix: &[Seg], suffix: &str) -> String {
4542 let mut k = root.to_owned();
4543 for s in prefix {
4544 k.push('/');
4545 k.push_str(s.pattern());
4546 }
4547 k.push_str(suffix);
4548 while k.contains("/**/**") {
4549 k = k.replace("/**/**", "/**");
4550 }
4551 k
4552}
4553
4554fn carve(root: &str, items: &[Item<'_>]) -> (Vec<String>, Vec<usize>) {
4558 let mut keys = Vec::new();
4559 let mut exact = Vec::new();
4560 let all: Vec<usize> = (0..items.len()).collect();
4561 carve_at(root, items, &[], &all, &mut keys, &mut exact);
4562 keys.sort();
4563 keys.dedup();
4564 (keys, exact)
4565}
4566
4567fn carve_at(
4568 root: &str,
4569 items: &[Item<'_>],
4570 prefix: &[Seg],
4571 here: &[usize],
4572 keys: &mut Vec<String>,
4573 exact: &mut Vec<usize>,
4574) {
4575 let d = prefix.len();
4576 let crosses = |i: &usize| items[*i].crosses;
4577 if !here.iter().any(crosses) {
4579 keys.push(key(root, prefix, "/**"));
4580 return;
4581 }
4582 if here.iter().all(crosses) {
4584 return;
4585 }
4586 let segs = |i: usize| items[i].template.segments();
4587 let (equal, longer): (Vec<usize>, Vec<usize>) = here.iter().partition(|&&i| segs(i).len() == d);
4588 if equal.iter().any(|i| !crosses(i)) {
4590 keys.push(key(root, prefix, ""));
4591 }
4592 if !longer.iter().any(crosses) {
4594 keys.push(key(root, prefix, "/*/**"));
4595 return;
4596 }
4597 let kinds: BTreeSet<u8> = longer
4599 .iter()
4600 .map(|&i| Seg::of(&segs(i)[d]).kind())
4601 .collect();
4602 if kinds.len() > 1 {
4603 for &i in &longer {
4604 if !items[i].crosses {
4605 let pattern: Vec<Seg> = segs(i).iter().map(Seg::of).collect();
4606 keys.push(key(root, &pattern, ""));
4607 exact.push(i);
4608 }
4609 }
4610 return;
4611 }
4612 let mut groups: BTreeMap<Seg, Vec<usize>> = BTreeMap::new();
4614 for &i in &longer {
4615 groups.entry(Seg::of(&segs(i)[d])).or_default().push(i);
4616 }
4617 for (seg, group) in groups {
4618 let mut p = prefix.to_vec();
4619 p.push(seg);
4620 carve_at(root, items, &p, &group, keys, exact);
4621 }
4622}
4623
4624#[must_use]
4631pub fn check_windows(
4632 policy: &FacePolicy,
4633 deployment: &Deployment,
4634 windows: &BTreeMap<String, u64>,
4635) -> Vec<Finding> {
4636 let mut out = Vec::new();
4637 for s in policy.owners() {
4639 let Some(ifaces) = deployment.implements.get(s.key) else {
4640 continue;
4641 };
4642 let v2 = policy.profile == Profile::V2;
4645 let owns_state = ifaces.iter().any(|i| {
4646 deployment.interfaces.get(i).is_some_and(|revs| {
4647 revs.iter()
4648 .flatten()
4649 .any(|r| is_state(r.token) && (!v2 || r.tombstone_only))
4650 })
4651 });
4652 if !owns_state {
4653 continue;
4654 }
4655 let addr = s.address;
4656 let w = windows.get(&addr).copied().unwrap_or(DEFAULT_WINDOW_S);
4657 for (name, face) in &policy.faces {
4658 if w < face.max_outage_s {
4659 out.push(Finding::new(
4660 Code::WindowUnderOutage,
4661 Some(name),
4662 addr.clone(),
4663 ));
4664 }
4665 }
4666 }
4667 sort_findings(&mut out);
4668 out
4669}
4670
4671#[derive(Debug, Clone, Default, PartialEq, Eq)]
4675pub struct BlockDeny {
4676 pub flows: Vec<String>,
4677 pub messages: Vec<String>,
4678 pub key_exprs: Vec<String>,
4679}
4680
4681#[derive(Debug, Clone, PartialEq)]
4683pub struct BlockRule {
4684 pub key_expr: String,
4685 pub freq: f64,
4686}
4687
4688#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4690pub enum Posture {
4691 Deny,
4692 Allow,
4693}
4694
4695#[derive(Debug, Clone, Default, PartialEq, Eq)]
4699pub struct BlockSubject {
4700 pub id: String,
4701 pub usernames: Vec<String>,
4702 pub cert_common_names: Vec<String>,
4703 pub link_protocols: Option<Vec<String>>,
4707 pub interfaces: Vec<String>,
4708 pub zids: Vec<String>,
4709}
4710
4711impl BlockSubject {
4712 fn bound(&self) -> bool {
4714 !self.usernames.is_empty() || !self.cert_common_names.is_empty()
4715 }
4716
4717 fn protocols(&self) -> Option<&[String]> {
4720 self.link_protocols.as_deref().filter(|p| !p.is_empty())
4721 }
4722
4723 fn selects(&self, p: &str) -> bool {
4725 self.protocols().is_none_or(|l| l.iter().any(|x| x == p))
4726 }
4727
4728 fn on_face(&self, face: &Face) -> bool {
4733 self.protocols()
4734 .is_none_or(|l| l.iter().any(|x| face.link_protocols.contains(x)))
4735 }
4736
4737 fn far_alone(&self, far: &str) -> bool {
4744 let only = |v: &[String]| !v.is_empty() && v.iter().all(|x| x == far);
4745 match (self.usernames.is_empty(), self.cert_common_names.is_empty()) {
4746 (false, true) => only(&self.usernames),
4747 (true, false) => only(&self.cert_common_names),
4748 _ => false,
4749 }
4750 }
4751
4752 fn answers(&self, name: &str, kind: NameKind) -> bool {
4758 if !self.interfaces.is_empty() || !self.zids.is_empty() {
4759 return false;
4760 }
4761 if !self.bound() {
4762 return true;
4763 }
4764 let has = |v: &[String]| v.iter().any(|x| x == name);
4765 match kind {
4766 NameKind::User => self.cert_common_names.is_empty() && has(&self.usernames),
4767 NameKind::Cn => self.usernames.is_empty() && has(&self.cert_common_names),
4768 NameKind::Unbound => false,
4769 }
4770 }
4771}
4772
4773#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
4777enum NameKind {
4778 User,
4779 Cn,
4780 Unbound,
4781}
4782
4783#[derive(Debug, Clone, Default, PartialEq, Eq)]
4787pub struct BlockPolicy {
4788 pub subjects: Vec<String>,
4789}
4790
4791#[derive(Debug, Clone, PartialEq, Eq)]
4794pub struct BlockSubjects {
4795 pub posture: Posture,
4796 pub subjects: Vec<BlockSubject>,
4797 pub policies: Vec<BlockPolicy>,
4798}
4799
4800impl BlockSubjects {
4801 fn listing(&self, id: &str) -> BTreeSet<usize> {
4803 self.policies
4804 .iter()
4805 .enumerate()
4806 .filter(|(_, p)| p.subjects.iter().any(|s| s == id))
4807 .map(|(i, _)| i)
4808 .collect()
4809 }
4810}
4811
4812#[derive(Debug, Clone, Default, PartialEq)]
4814pub struct Block {
4815 pub namespace: String,
4817 pub enabled: Option<bool>,
4822 pub deny: Vec<BlockDeny>,
4826 pub downsampling: Vec<BlockRule>,
4828 pub subjects: Option<BlockSubjects>,
4832}
4833
4834#[must_use]
4841pub fn check_block(face: &str, device: bool, block: &Block) -> Vec<Finding> {
4842 let mut out = Vec::new();
4843 if block.enabled == Some(false) {
4844 out.push(Finding::new(Code::BlockDisabled, Some(face), "enabled"));
4845 }
4846 let ns = block.namespace.trim_matches('/');
4847 let with_ns = |k: &str| {
4848 if ns.is_empty() {
4849 k.to_owned()
4850 } else {
4851 format!("{ns}/{k}")
4852 }
4853 };
4854 let denied = if device {
4855 ZK_CARVED
4856 .iter()
4857 .all(|k| zk_denied_on(&with_ns(k), &block.deny, |_, _| true))
4858 && zk_denied_on(&with_ns(ZK_INSTANCE), &block.deny, |f, m| {
4859 !OWN_PAIRS.contains(&(f, m))
4860 })
4861 } else {
4862 zk_denied_on(&with_ns(ZK_DENY), &block.deny, |_, _| true)
4863 };
4864 if !denied {
4865 out.push(Finding::new(Code::ZkNotDenied, Some(face), "@zk"));
4866 }
4867 let parsed: Vec<Option<&keyexpr>> = block
4868 .downsampling
4869 .iter()
4870 .map(|r| keyexpr::new(r.key_expr.as_str()).ok())
4871 .collect();
4872 for (j, r) in block.downsampling.iter().enumerate() {
4873 if parsed[j].is_none_or(|k| k.as_str().contains('*')) {
4875 out.push(Finding::new(
4876 Code::WildcardDownsampling,
4877 Some(face),
4878 r.key_expr.clone(),
4879 ));
4880 }
4881 let hit = (0..j).any(|i| match (parsed[i], parsed[j]) {
4882 (Some(a), Some(b)) => a.intersects(b),
4883 _ => false,
4884 });
4885 if hit {
4886 out.push(Finding::new(
4887 Code::IntersectingDownsampling,
4888 Some(face),
4889 r.key_expr.clone(),
4890 ));
4891 }
4892 }
4893 sort_findings(&mut out);
4894 out
4895}
4896
4897fn zk_denied_on(target: &str, deny: &[BlockDeny], pairs: impl Fn(&str, &str) -> bool) -> bool {
4901 let Ok(target) = keyexpr::new(target) else {
4902 return false;
4903 };
4904 FLOWS.iter().all(|flow| {
4905 MESSAGES.iter().filter(|m| pairs(flow, m)).all(|m| {
4906 deny.iter().any(|d| {
4907 d.flows.iter().any(|f| f == flow)
4908 && d.messages.iter().any(|x| x == m)
4909 && d.key_exprs
4910 .iter()
4911 .any(|k| keyexpr::new(k.as_str()).is_ok_and(|k| k.includes(target)))
4912 })
4913 })
4914 })
4915}
4916
4917#[must_use]
4940pub fn check_subjects(name: &str, face: &Face, block: &BlockSubjects) -> Vec<Finding> {
4941 let mut out = Vec::new();
4942 let on_face: Vec<&BlockSubject> = block.subjects.iter().filter(|s| s.on_face(face)).collect();
4943 let far_policies: BTreeSet<usize> = on_face
4946 .iter()
4947 .filter(|s| s.far_alone(&face.far))
4948 .flat_map(|s| block.listing(&s.id))
4949 .collect();
4950 for s in &on_face {
4951 let mut found = |code: Code| out.push(Finding::new(code, Some(name), s.id.clone()));
4952 if s.bound() {
4953 if !s.far_alone(&face.far) {
4954 found(Code::NearSubjectOnFace);
4955 }
4956 continue;
4957 }
4958 if s.protocols()
4959 .is_none_or(|l| l.iter().any(|x| !face.link_protocols.contains(x)))
4960 {
4961 found(Code::FaceSubjectBeyondFace);
4962 }
4963 let listed = block.listing(&s.id);
4964 if listed.is_empty() || listed != far_policies {
4965 found(Code::FaceSubjectMisplaced);
4966 }
4967 }
4968 if block.posture == Posture::Allow {
4969 for p in &face.link_protocols {
4970 let selected = block.subjects.iter().any(|s| {
4971 !s.bound()
4972 && s.interfaces.is_empty()
4973 && s.zids.is_empty()
4974 && s.protocols().is_some_and(|l| l.contains(p))
4975 });
4976 if !selected {
4977 out.push(Finding::new(
4978 Code::FaceSubjectMissing,
4979 Some(name),
4980 p.clone(),
4981 ));
4982 }
4983 }
4984 }
4985 sort_findings(&mut out);
4986 out
4987}
4988
4989#[must_use]
5005pub fn check_narrowing(policy: &FacePolicy, block: &BlockSubjects) -> Vec<Finding> {
5006 let mut out = Vec::new();
5007 if block.posture != Posture::Allow {
5008 return out;
5009 }
5010 let mut names: BTreeSet<(&str, NameKind)> = BTreeSet::new();
5011 for s in &block.subjects {
5012 names.extend(s.usernames.iter().map(|u| (u.as_str(), NameKind::User)));
5013 names.extend(
5014 s.cert_common_names
5015 .iter()
5016 .map(|c| (c.as_str(), NameKind::Cn)),
5017 );
5018 }
5019 for f in policy.faces.values() {
5020 let bound = block.subjects.iter().any(|s| {
5023 s.usernames
5024 .iter()
5025 .chain(&s.cert_common_names)
5026 .any(|x| *x == f.far)
5027 });
5028 if !bound {
5029 names.insert((f.far.as_str(), NameKind::Unbound));
5030 }
5031 }
5032 let mut bare_names: BTreeSet<&str> = BTreeSet::new();
5033 for (name, kind) in names {
5034 let kept: Vec<String> =
5035 narrowed(policy, |f| policy.faces[f].far == name).unwrap_or_else(|| {
5036 policy
5037 .binding
5038 .protocols()
5039 .iter()
5040 .map(|p| (*p).to_owned())
5041 .collect()
5042 });
5043 let bare = kept.iter().any(|p| {
5044 !block
5045 .subjects
5046 .iter()
5047 .any(|s| s.answers(name, kind) && s.selects(p))
5048 });
5049 if bare {
5050 bare_names.insert(name);
5051 }
5052 }
5053 for name in bare_names {
5054 out.push(Finding::new(Code::NarrowedTooFar, None, name));
5055 }
5056 sort_findings(&mut out);
5057 out
5058}
5059
5060#[must_use]
5067pub fn narrowed(policy: &FacePolicy, is_far: impl Fn(&str) -> bool) -> Option<Vec<String>> {
5068 let excluded: BTreeSet<&str> = policy
5069 .faces
5070 .iter()
5071 .filter(|(name, _)| !is_far(name))
5072 .flat_map(|(_, f)| f.link_protocols.iter().map(String::as_str))
5073 .collect();
5074 (!excluded.is_empty()).then(|| {
5075 policy
5076 .binding
5077 .protocols()
5078 .iter()
5079 .filter(|p| !excluded.contains(*p))
5080 .map(|p| (*p).to_owned())
5081 .collect()
5082 })
5083}
5084
5085#[derive(Debug, Clone, Copy, Default)]
5089pub struct LintInput<'a> {
5090 pub text: &'a str,
5091 pub deployment: Option<&'a Deployment>,
5093 pub windows: Option<&'a BTreeMap<String, u64>>,
5096 pub block: Option<(&'a str, &'a Block)>,
5098}
5099
5100#[must_use]
5104pub fn lint(input: &LintInput<'_>) -> Vec<Finding> {
5105 let parsed = parse(input.text);
5106 let mut out = parsed.findings;
5107 let Some(policy) = parsed.policy else {
5108 return out;
5109 };
5110 if let Some(d) = input.deployment {
5111 match plan(&policy, d) {
5112 Ok(plans) => out.extend(plans.into_iter().flat_map(|p| p.findings)),
5113 Err(f) => out.extend(f),
5114 }
5115 if let Some(w) = input.windows {
5116 out.extend(check_windows(&policy, d, w));
5117 }
5118 }
5119 if let Some((face, block)) = input.block {
5120 let device = policy.faces.get(face).is_some_and(|f| f.attach.is_device());
5121 out.extend(check_block(face, device, block));
5122 if let Some(s) = &block.subjects {
5123 if let Some(f) = policy.faces.get(face) {
5124 out.extend(check_subjects(face, f, s));
5125 }
5126 out.extend(check_narrowing(&policy, s));
5127 }
5128 }
5129 sort_findings(&mut out);
5130 out
5131}
5132
5133#[cfg(test)]
5134mod tests {
5135 use super::*;
5136
5137 fn ke(s: &str) -> &keyexpr {
5138 keyexpr::new(s).unwrap()
5139 }
5140
5141 #[test]
5144 fn a_binding_deserializes_by_its_name() {
5145 for b in Binding::ALL {
5146 let read: Binding = serde_json::from_value(Value::from(b.as_str())).unwrap();
5147 assert_eq!(read, b);
5148 assert_eq!(serde_json::to_value(b).unwrap(), Value::from(b.as_str()));
5149 }
5150 let e = serde_json::from_value::<Binding>(Value::from("zenoh-1.10.0"))
5151 .unwrap_err()
5152 .to_string();
5153 assert!(
5154 e.contains("zenoh-1.10.0")
5155 && e.contains("`zenoh-1.10.1`")
5156 && e.contains("`zenoh-1.10.2`")
5157 && e.contains("`zm-1.10.2-r1`"),
5158 "{e}"
5159 );
5160 assert!(serde_json::from_value::<Binding>(Value::from(1)).is_err());
5161 }
5162
5163 #[test]
5167 fn a_binding_parses_by_its_name() {
5168 assert_eq!(Binding::NAMES, Binding::ALL.map(Binding::as_str));
5169 for b in Binding::ALL {
5170 assert_eq!(b.as_str().parse::<Binding>(), Ok(b));
5171 assert_eq!(b.to_string().parse::<Binding>(), Ok(b));
5172 }
5173 let e = "zenoh-1.10.0".parse::<Binding>().unwrap_err();
5174 assert_eq!(e, UnknownBinding("zenoh-1.10.0".to_owned()));
5175 assert_eq!(
5176 e.to_string(),
5177 "not a binding; one of: zenoh-1.10.1, zenoh-1.10.2, zm-1.10.2-r1, or zm-1.10.2-r<n> \
5178 for a later release of the fork"
5179 );
5180 assert!("".parse::<Binding>().is_err());
5181 assert!(
5182 "Zenoh-1.10.1".parse::<Binding>().is_err(),
5183 "names are exact"
5184 );
5185 }
5186
5187 #[test]
5193 fn a_later_release_of_the_fork_names_its_binding() {
5194 for name in ["zm-1.10.2-r2", "zm-1.10.2-r10", "zm-1.10.2-r123"] {
5195 assert_eq!(Binding::parse(name), Some(Binding::Zm1_10_2R1), "{name}");
5196 assert_eq!(name.parse::<Binding>(), Ok(Binding::Zm1_10_2R1), "{name}");
5197 assert_eq!(
5198 serde_json::from_value::<Binding>(Value::from(name)).ok(),
5199 Some(Binding::Zm1_10_2R1),
5200 "{name}"
5201 );
5202 }
5203 for name in [
5204 "zm-1.10.2-r0",
5205 "zm-1.10.2-r01",
5206 "zm-1.10.2-r",
5207 "zm-1.10.2-r2x",
5208 "zm-1.10.2-r-2",
5209 "zm-1.10.3-r1",
5210 "zm-1.10.2",
5211 ] {
5212 assert_eq!(Binding::parse(name), None, "{name}");
5213 }
5214 let policy = |binding: &str| {
5215 format!(
5216 "profile = \"link.v2\"\nsystem = \"lab\"\nservices = [\"radio-a\"]\n\
5217 binding = \"{binding}\"\n\n[transport]\nlease_ms = 240000\n\
5218 keep_alive = 4\nwait_before_close_ms = 240000\n\
5219 sequence = \"16bit\"\nbatch_bytes = 222\n\n[face.radio]\n\
5220 far = \"ground\"\nattach = \"client\"\n\
5221 select = {{ link_protocols = [\"unixsock-dgram\"] }}\n\
5222 class = \"constrained\"\nexpose = \"link\"\n\
5223 interval_s = 60\nmax_outage_s = 3600\nlink_bps = 2400\n\
5224 loss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n"
5225 )
5226 };
5227 let r1 = parse(&policy("zm-1.10.2-r1"));
5228 let r2 = parse(&policy("zm-1.10.2-r2"));
5229 assert_eq!(
5230 r2.findings, r1.findings,
5231 "the same findings: none on unixsock-dgram"
5232 );
5233 let (r1, mut r2) = (r1.policy.expect("r1 reads"), r2.policy.expect("r2 reads"));
5234 assert_eq!(r2.binding, Binding::Zm1_10_2R1);
5235 assert_eq!(r2.binding_name, "zm-1.10.2-r2");
5237 assert_eq!(r1.binding_name, "zm-1.10.2-r1");
5238 r2.binding_name = r1.binding_name.clone();
5239 assert_eq!(
5240 r2, r1,
5241 "but for its name, a policy naming r2 reads as one naming r1"
5242 );
5243 }
5244
5245 #[test]
5250 fn zenoh_1_10_2_is_a_binding_that_reads_as_1_10_1() {
5251 let (stock, next, fork) = (
5252 Binding::Zenoh1_10_1,
5253 Binding::Zenoh1_10_2,
5254 Binding::Zm1_10_2R1,
5255 );
5256 assert_eq!(Binding::ALL, [stock, next, fork], "v2 §2.4's order");
5257 assert_eq!(next.protocols(), stock.protocols());
5258 assert!(!next.protocols().contains(&"unixsock-dgram"));
5259 assert!(fork.protocols().contains(&"unixsock-dgram"));
5260 assert_eq!(next.defaults(), stock.defaults());
5261 assert_eq!(next.defaults().wait_before_close_ms, 5_000);
5262 assert_ne!(next.defaults(), fork.defaults());
5263 assert_eq!(
5264 Binding::default(),
5265 stock,
5266 "a link.v1 policy reads as 1.10.1"
5267 );
5268
5269 let policy = |protocol: &str| {
5270 format!(
5271 "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5272 binding = \"zenoh-1.10.2\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
5273 wait_before_close_ms = 10000\nsequence = \"16bit\"\nbatch_bytes = 222\n\
5274 [face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
5275 select = {{ link_protocols = [\"{protocol}\"] }}\n\
5276 class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
5277 link_bps = 2400\nloss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n"
5278 )
5279 };
5280 let read = parse(&policy("unixsock-stream"));
5281 assert!(read.findings.is_empty(), "{:?}", read.findings);
5282 assert_eq!(read.policy.map(|p| p.binding), Some(next));
5283 let refused = parse(&policy("unixsock-dgram"));
5284 assert_eq!(
5285 refused.findings.iter().map(|f| f.code).collect::<Vec<_>>(),
5286 [Code::UnknownProtocol],
5287 "{:?}",
5288 refused.findings
5289 );
5290 }
5291
5292 #[test]
5294 fn key_expression_facts() {
5295 assert!(ke("zk2/*/*/m.v1/stream/a/**").includes(ke("zk2/h/s/m.v1/stream/a")));
5298 assert!(ke(ZK_DENY).includes(ke("zk2/@zk/contract/m.v1/abc")));
5299 assert!(ke(ZK_DENY).includes(ke("zk2/h/s/@zk/instance/0123456789abcdef")));
5300 assert!(ke("**/@zk/**").includes(ke(ZK_DENY)));
5301 assert!(!ke("zk2/*/*/m.v1/events/logs/*/**").includes(ke("zk2/h/s/m.v1/events/logs")));
5303 assert!(ke("zk2/*/*/m.v1/events/logs/*/**").includes(ke("zk2/h/s/m.v1/events/logs/a/b")));
5304 assert!(!ke("zk2/*/*/*/stream/**").includes(ke("zk2/h/s/m.v1/@stream/x")));
5306 assert!(ke("zk2/*/*/*/@stream/**").includes(ke("zk2/h/s/m.v1/@stream/x")));
5307 assert!(ke(ADV_DENY).includes(ke("zk2/h/s/m.v1/stream/x/@adv/pub/abc")));
5308 }
5309
5310 #[test]
5313 fn the_carve_lets_an_instance_key_cross_on_the_own_pairs_alone() {
5314 let carve = zk_carve();
5315 let denied = |key: &str, flow: &str, m: &str| {
5316 carve.iter().any(|d| {
5317 d.flows.contains(&flow)
5318 && d.messages.contains(&m)
5319 && d.key_exprs.iter().any(|k| ke(k).includes(ke(key)))
5320 })
5321 };
5322 let instance = "zk2/lab/probe-a/@zk/instance/0123456789abcdef";
5323 let mut open = Vec::new();
5324 for flow in FLOWS {
5325 for m in MESSAGES {
5326 for key in [
5327 "zk2/lab/probe-a/@zk/alive/probe.v1",
5328 "zk2/lab/probe-a/@zk/member/0123456789abcdef/x",
5329 "zk2/@zk/contract/probe.v1/abc",
5330 ] {
5331 assert!(denied(key, flow, m), "{key} {flow} {m}");
5332 }
5333 if !denied(instance, flow, m) {
5334 open.push((flow, m));
5335 }
5336 }
5337 }
5338 open.sort_unstable();
5339 let mut own = OWN_PAIRS.to_vec();
5340 own.sort_unstable();
5341 assert_eq!(open, own);
5342 assert!(
5344 carve
5345 .iter()
5346 .flat_map(|d| &d.key_exprs)
5347 .all(|k| k.starts_with("zk2/*/*/") || k == "zk2/@zk/**")
5348 );
5349 }
5350
5351 #[test]
5352 fn keys_collapse_a_trailing_rest() {
5353 assert_eq!(
5354 key("r", &[Seg::Lit("x".into()), Seg::Rest], "/**"),
5355 "r/x/*/**"
5356 );
5357 assert_eq!(key("r", &[], "/**"), "r/**");
5358 assert_eq!(key("r", &[Seg::Lit("a".into())], "/*/**"), "r/a/*/**");
5359 }
5360
5361 fn res(template: &str, annotations: Value) -> Res {
5362 Res::new(
5363 Template::parse(template).unwrap(),
5364 KindToken::Stream,
5365 serde_json::from_value(annotations).unwrap(),
5366 )
5367 }
5368
5369 #[test]
5373 fn revisions_are_read_together_failing_closed() {
5374 let a = vec![
5375 res(
5376 "x",
5377 serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 10}),
5378 ),
5379 res(
5380 "y",
5381 serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 10}),
5382 ),
5383 res("w", serde_json::json!({"link.exposure": "LINK"})),
5384 ];
5385 let b = vec![
5386 res("x", serde_json::json!({"freshness.ttl_s": 4})),
5387 res(
5388 "y",
5389 serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 0}),
5390 ),
5391 res("w", serde_json::json!({})),
5392 res("z", serde_json::json!({"link.exposure": "link"})),
5393 ];
5394 let (m, disagree) = merge(&[a, b]);
5395 let read = |t: &str| {
5396 let r = m.iter().find(|r| r.template.as_str() == t).unwrap();
5397 (exposure_of_res(r), horizon(r).ttl().map(|d| d.as_secs()))
5398 };
5399 assert_eq!(read("x"), (Exposure::Host, Some(4)));
5400 assert_eq!(read("y"), (Exposure::Link, None));
5401 assert_eq!(read("z"), (Exposure::Link, None));
5402 assert_eq!(disagree, BTreeSet::from([0]));
5404 }
5405
5406 #[test]
5410 fn link_v2_judges_each_revision_alone() {
5411 let raw = res("s", serde_json::json!({"link.exposure": "link"}));
5412 let mut packed = raw.clone();
5413 packed.packed = true;
5414 packed.block = true;
5415 packed.longest_bytes = Some(300);
5416 let mut timed = raw.clone();
5417 timed.packed = true;
5418 timed.longest_bytes = Some(400);
5419 timed
5420 .annotations
5421 .insert(crate::timing::DEADLINE_MS.to_owned(), Value::from(2000));
5422 for revs in [
5423 [vec![raw.clone()], vec![packed.clone()], vec![timed.clone()]],
5424 [vec![timed.clone()], vec![packed.clone()], vec![raw.clone()]],
5425 ] {
5426 let (m, _) = merge(&revs);
5427 let r = &m[0];
5428 assert!(!r.packed, "one revision's raw type");
5429 assert!(r.shape().timed, "one revision's deadline");
5430 assert!(r.block);
5431 assert_eq!(r.longest_bytes, Some(300), "the block revision's");
5432 }
5433 let (m, _) = merge(&[vec![packed.clone()], vec![timed.clone()]]);
5434 assert!(m[0].packed, "packed in every revision");
5435 let (m, _) = merge(&[vec![timed.clone()], vec![raw]]);
5436 assert_eq!(m[0].longest_bytes, Some(400), "none block: the longest");
5437 }
5438
5439 fn exposure_of_res(r: &Res) -> Exposure {
5440 match exposure(kind_of(r.token), &r.annotations) {
5441 Exposure::Invalid(_) => Exposure::Host,
5442 e => e,
5443 }
5444 }
5445
5446 fn face(far: &str, protocols: &[&str]) -> Face {
5447 Face {
5448 far: far.to_owned(),
5449 attach: Attach::Client,
5450 link_protocols: protocols.iter().map(|p| (*p).to_owned()).collect(),
5451 expose: Expose::Link,
5452 interval_s: Some(1),
5453 max_outage_s: 1,
5454 batch_bytes: 1,
5455 link_bps: 1,
5456 lease_ms: DEFAULT_LEASE_MS,
5457 loss_ppm: None,
5458 arq: None,
5459 reply_timeout_ms: None,
5460 frames: None,
5461 events: None,
5462 horizon_s: None,
5463 opens: Opens::Far,
5464 }
5465 }
5466
5467 #[test]
5470 fn a_subject_is_narrowed_off_the_faces_it_is_not_far_of() {
5471 let policy = |faces: Vec<(&str, Face)>| FacePolicy {
5472 profile: Profile::V1,
5473 system: "lab".into(),
5474 services: vec![],
5475 faces: faces.into_iter().map(|(n, f)| (n.to_owned(), f)).collect(),
5476 binding: Binding::Zenoh1_10_1,
5477 binding_name: Binding::Zenoh1_10_1.as_str().to_owned(),
5478 transport: None,
5479 catalog: None,
5480 };
5481 let two = policy(vec![
5482 ("radio", face("ground", &["unixsock-stream"])),
5483 ("sat", face("sat", &["serial", "unixpipe"])),
5484 ]);
5485 let of = |p: &str| narrowed(&two, |name| two.faces[name].far == p);
5486 assert_eq!(
5487 of("local").unwrap(),
5488 ["tcp", "udp", "tls", "quic", "vsock", "ws"]
5489 );
5490 assert_eq!(
5491 of("ground").unwrap(),
5492 [
5493 "tcp",
5494 "udp",
5495 "tls",
5496 "quic",
5497 "unixsock-stream",
5498 "vsock",
5499 "ws"
5500 ]
5501 );
5502 let one = policy(vec![("radio", face("ground", &["unixsock-stream"]))]);
5503 assert_eq!(narrowed(&one, |_| true), None);
5504 let all = policy(vec![("x", face("x", Binding::Zenoh1_10_1.protocols()))]);
5505 assert_eq!(narrowed(&all, |_| false), Some(Vec::new()));
5506 let fork = FacePolicy {
5509 binding: Binding::Zm1_10_2R1,
5510 binding_name: Binding::Zm1_10_2R1.as_str().to_owned(),
5511 ..policy(vec![("radio", face("ground", &["unixsock-stream"]))])
5512 };
5513 assert_eq!(
5514 narrowed(&fork, |_| false).unwrap(),
5515 [
5516 "tcp",
5517 "udp",
5518 "tls",
5519 "quic",
5520 "serial",
5521 "unixpipe",
5522 "unixsock-dgram",
5523 "vsock",
5524 "ws"
5525 ]
5526 );
5527 }
5528
5529 #[test]
5533 fn the_keep_alive_lint_is_exact() {
5534 assert!(!flaps(240_000, 4, 50_000));
5535 assert!(!flaps(120_000, 4, 50_000));
5536 assert!(!flaps(1_080_000, 4, 50_000));
5537 assert!(flaps(120_000, 2, 50_000));
5538 assert!(flaps(60_000, 2, 50_000));
5539 assert!(!flaps(3_600_000, 2, 0));
5540 assert!(flaps(3_600_000, 1, 0));
5541 assert!(!flaps(86_400, 4, 50_000));
5543 assert!(flaps(86_399, 4, 50_000));
5544 assert!(flaps(MAX_U32, MAX_KEEP_ALIVE, MAX_LOSS_PPM - 1));
5546 assert!(!flaps(MAX_U32, MAX_KEEP_ALIVE, 0));
5547 }
5548
5549 #[test]
5553 fn a_bad_transport_refuses_a_good_face() {
5554 let face = "[face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
5555 select = { link_protocols = [\"unixsock-stream\"] }\n\
5556 class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
5557 link_bps = 2400\nloss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n";
5558 let head = "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5559 binding = \"zenoh-1.10.1\"\n";
5560 let good = "[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
5561 wait_before_close_ms = 10000\nsequence = \"16bit\"\n";
5562 let ok = parse(&format!("{head}{good}{face}"));
5563 assert!(ok.policy.is_some(), "{:?}", ok.findings);
5564 for (transport, code, at) in [
5565 ("", Code::TransportMissing, "transport"),
5566 ("transport = 1\n", Code::BadValue, "transport"),
5567 (
5568 &good.replace("lease_ms = 10000", "lease_ms = 0"),
5569 Code::BadValue,
5570 "transport.lease_ms",
5571 ),
5572 (
5573 &good.replace("lease_ms = 10000\n", ""),
5574 Code::MissingField,
5575 "transport.lease_ms",
5576 ),
5577 (
5578 &format!("{good}batch_bytes = 65536\n"),
5579 Code::BadValue,
5580 "transport.batch_bytes",
5581 ),
5582 ] {
5583 let p = parse(&format!("{head}{transport}{face}"));
5584 assert!(p.policy.is_none(), "{transport:?}");
5585 assert!(
5586 p.findings
5587 .iter()
5588 .any(|f| f.code == code && f.at == at && f.face.is_none()),
5589 "{transport:?}: {:?}",
5590 p.findings
5591 );
5592 }
5593 }
5594
5595 #[test]
5599 fn wait_under_lease_reads_integers_and_a_wrong_type_differs() {
5600 let p = parse(
5601 "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5602 binding = \"zenoh-1.10.1\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
5603 wait_before_close_ms = 10000\nsequence = \"32bit\"\n[face.rf]\n\
5604 far = \"ground\"\nattach = \"client\"\n\
5605 select = { link_protocols = [\"unixsock-stream\"] }\nclass = \"constrained\"\n\
5606 expose = \"none\"\nmax_outage_s = 3600\nlink_bps = 1000000\nloss_ppm = 0\n\
5607 arq = true\nreply_timeout_ms = 15000\n",
5608 )
5609 .policy
5610 .expect("a policy");
5611 let wbc = TransportKey::WaitBeforeClose.path();
5612 let lease = TransportKey::Lease.path();
5613 let found = |pairs: &[(&str, Value)]| -> Vec<(&'static str, String)> {
5614 let stated = StatedTransport(
5616 pairs
5617 .iter()
5618 .map(|(k, v)| ((*k).to_owned(), v.clone()))
5619 .chain([("timestamping/enabled".to_owned(), Value::from(false))])
5620 .collect(),
5621 );
5622 check_transport(&p, &stated, None)
5623 .into_iter()
5624 .map(|f| (f.code.as_str(), f.at))
5625 .collect()
5626 };
5627 let at = || "transport.wait_before_close_ms".to_owned();
5628 let differs = || ("transport_differs", at());
5629 let under = || ("wait_under_lease", at());
5630 assert_eq!(found(&[(wbc, Value::from(10_000_000u64))]), []);
5631 assert_eq!(found(&[(wbc, Value::from(u64::MAX))]), [differs()]);
5632 assert_eq!(found(&[(wbc, Value::from(-1i64))]), [differs(), under()]);
5633 assert_eq!(found(&[(wbc, Value::from("10000000"))]), [differs()]);
5634 assert_eq!(found(&[(wbc, Value::from(1.0e7))]), [differs()]);
5635 assert_eq!(
5636 found(&[
5637 (lease, Value::from("10000")),
5638 (wbc, Value::from(10_000_000u64))
5639 ]),
5640 [("transport_differs", "transport.lease_ms".to_owned())]
5641 );
5642 }
5643
5644 #[test]
5649 fn a_null_reads_as_left_out_at_the_interests_timeout_alone() {
5650 let policy = |interests_ms: u64| {
5651 parse(&format!(
5652 "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5653 binding = \"zenoh-1.10.1\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
5654 wait_before_close_ms = 10000\nsequence = \"32bit\"\n\
5655 interests_timeout_ms = {interests_ms}\n[face.rf]\n\
5656 far = \"ground\"\nattach = \"client\"\n\
5657 select = {{ link_protocols = [\"unixsock-stream\"] }}\nclass = \"constrained\"\n\
5658 expose = \"none\"\nmax_outage_s = 3600\nlink_bps = 1000000\nloss_ppm = 0\n\
5659 arq = true\nreply_timeout_ms = 15000\n"
5660 ))
5661 .policy
5662 .expect("a policy")
5663 };
5664 let router = |null_at: TransportKey| {
5667 let mut tree = serde_json::json!({
5668 "transport": {
5669 "link": {"tx": {
5670 "lease": 10_000, "keep_alive": 4, "batch_size": 65_535,
5671 "sequence_number_resolution": "32bit",
5672 "queue": {"congestion_control": {"block": {
5673 "wait_before_close": 10_000_000,
5674 }}},
5675 }},
5676 "unicast": {"open_timeout": 10_000, "accept_timeout": 10_000},
5677 },
5678 "routing": {"interests": {"timeout": 10_000}},
5679 "timestamping": {"enabled": false},
5680 });
5681 let mut node = &mut tree;
5682 for part in null_at.path().split('/') {
5683 node = node.get_mut(part).expect("the path");
5684 }
5685 *node = Value::Null;
5686 StatedTransport::read(&tree)
5687 };
5688 let found = |p: &FacePolicy, r: &StatedTransport| -> Vec<(&'static str, String)> {
5689 check_transport(p, r, None)
5690 .into_iter()
5691 .map(|f| (f.code.as_str(), f.at))
5692 .collect()
5693 };
5694 let defaults = Binding::Zenoh1_10_1.defaults();
5695 let interests = TransportKey::InterestsTimeout;
5696
5697 let r = router(interests);
5699 assert_eq!(r.0.get(interests.path()), Some(&Value::Null));
5700 assert!(r.null_left_out(interests));
5701 assert!(!r.states(interests));
5702 assert_eq!(r.runs(interests, &defaults), Value::from(10_000u64));
5703 assert_eq!(found(&policy(10_000), &r), []);
5705 assert_eq!(
5707 found(&policy(40_000), &r),
5708 [("transport_differs", interests.at())]
5709 );
5710 assert_eq!(
5712 r.runs(interests, &Binding::Zm1_10_2R1.defaults()),
5713 Value::from(10_000u64)
5714 );
5715
5716 for key in TransportKey::ALL {
5718 if key == interests {
5719 continue;
5720 }
5721 let r = router(key);
5722 assert!(!r.null_left_out(key), "{}", key.key());
5723 assert!(r.states(key), "{}", key.key());
5724 assert_eq!(r.runs(key, &defaults), Value::Null, "{}", key.key());
5725 assert_eq!(
5727 found(&policy(10_000), &r),
5728 [("transport_differs", key.at())],
5729 "{}",
5730 key.key()
5731 );
5732 }
5733
5734 let omitted = StatedTransport::default();
5736 assert!(!omitted.states(interests) && !omitted.null_left_out(interests));
5737 assert_eq!(
5738 omitted.runs(interests, &defaults),
5739 r.runs(interests, &defaults)
5740 );
5741 }
5742
5743 #[test]
5748 fn a_routers_timestamping_is_read_at_its_mode() {
5749 let stamps = |mode: Option<&str>, enabled: Option<Value>| {
5750 let mut m = BTreeMap::new();
5751 if let Some(mode) = mode {
5752 m.insert("mode".to_owned(), Value::from(mode));
5753 }
5754 if let Some(e) = enabled {
5755 m.insert("timestamping/enabled".to_owned(), e);
5756 }
5757 StatedTransport(m).stamps()
5758 };
5759 assert!(stamps(None, None), "zenohd's router stamps by default");
5760 assert!(stamps(Some("router"), None));
5761 assert!(!stamps(Some("peer"), None));
5762 assert!(!stamps(Some("client"), None));
5763 assert!(stamps(Some("peer"), Some(Value::from(true))));
5764 assert!(!stamps(Some("router"), Some(Value::from(false))));
5765 let off = serde_json::json!({"router": false, "peer": false});
5766 assert!(!stamps(None, Some(off.clone())));
5767 assert!(!stamps(Some("peer"), Some(off)));
5768 assert!(stamps(
5770 Some("router"),
5771 Some(serde_json::json!({"peer": false}))
5772 ));
5773 assert!(stamps(
5774 Some("peer"),
5775 Some(serde_json::json!({"peer": true}))
5776 ));
5777 let written = StatedTransport::read(&serde_json::json!({
5779 "mode": "router",
5780 "timestamping": {"enabled": {"router": false, "peer": false}},
5781 }));
5782 assert!(!written.stamps());
5783 assert_eq!(TIMESTAMPING_OFF.len(), 2);
5784 for path in ["timestamping/enabled/router", "timestamping/enabled/peer"] {
5786 assert!(
5787 TIMESTAMPING_OFF.contains(&(path, false)),
5788 "{path} in {TIMESTAMPING_OFF:?}"
5789 );
5790 }
5791 assert!(stamps(Some("router"), Some(serde_json::Value::Null)));
5793 assert!(stamps(
5794 Some("router"),
5795 Some(serde_json::json!({"router": null, "peer": false}))
5796 ));
5797 assert!(!stamps(
5798 Some("peer"),
5799 Some(serde_json::json!({"router": false, "peer": null}))
5800 ));
5801 let null_mode = StatedTransport::read(&serde_json::json!({
5802 "mode": null,
5803 "timestamping": {"enabled": {"peer": false}},
5804 }));
5805 assert!(null_mode.stamps(), "a `null` mode runs as a router");
5806 for refused in [
5810 serde_json::json!("bogus"),
5811 serde_json::json!("Router"),
5812 serde_json::json!(5),
5813 ] {
5814 let read = |enabled: Option<Value>| {
5815 let mut m = BTreeMap::from([("mode".to_owned(), refused.clone())]);
5816 if let Some(e) = enabled {
5817 m.insert("timestamping/enabled".to_owned(), e);
5818 }
5819 StatedTransport(m).stamps()
5820 };
5821 assert!(read(None), "{refused}: a router's default, on");
5822 assert!(
5823 read(Some(serde_json::json!({"peer": false}))),
5824 "{refused}: the router's value left out"
5825 );
5826 assert!(
5827 !read(Some(serde_json::json!({"router": false, "peer": false}))),
5828 "{refused}: off at the mode read"
5829 );
5830 assert!(!read(Some(Value::from(false))), "{refused}");
5831 assert!(
5833 read(Some(serde_json::json!({"bogus": false, "5": false}))),
5834 "{refused}"
5835 );
5836 }
5837 }
5838
5839 #[test]
5842 fn the_keep_alive_interval_says_when_it_rounds() {
5843 let t = |lease_ms, keep_alive| Transport {
5844 lease_ms,
5845 keep_alive,
5846 ..Binding::Zenoh1_10_1.defaults()
5847 };
5848 assert_eq!(t(240_000, 4).keep_alive_interval_words(), "60000 ms");
5849 assert_eq!(t(2_000, 3).keep_alive_interval_words(), "about 666 ms");
5850 }
5851
5852 #[test]
5857 fn a_puts_allowance_is_the_measured_bound() {
5858 let lane = ["unixsock-stream".to_owned()];
5859 let block = PutQos {
5860 block: true,
5861 ..PutQos::DATA_DROP
5862 };
5863 let express = PutQos {
5864 express: true,
5865 ..PutQos::DATA_DROP
5866 };
5867 let low = PutQos {
5868 priority_data: false,
5869 ..PutQos::DATA_DROP
5870 };
5871 for (qos, bit16, bit32) in [
5872 (PutQos::DATA_DROP, 212, 210),
5873 (block, 210, 208),
5874 (express, 210, 208),
5875 (low, 208, 206),
5876 ] {
5877 for (sequence, largest) in [(Sequence::Bit16, bit16), (Sequence::Bit32, bit32)] {
5878 assert!(
5879 fits_batch(largest, 222, qos, sequence, &lane),
5880 "{qos:?} {sequence:?}"
5881 );
5882 assert!(!fits_batch(largest + 1, 222, qos, sequence, &lane));
5883 }
5884 }
5885 assert_eq!(allowance(100, PutQos::DATA_DROP, Sequence::Bit16, &lane), 9);
5888 assert_eq!(
5889 allowance(16_384, PutQos::DATA_DROP, Sequence::Bit16, &lane),
5890 11
5891 );
5892 let serial = ["serial".to_owned(), "ws".to_owned()];
5893 assert_eq!(
5894 allowance(200, PutQos::DATA_DROP, Sequence::Bit16, &serial),
5895 8
5896 );
5897 let mixed = ["serial".to_owned(), "udp".to_owned()];
5898 assert_eq!(
5899 allowance(200, PutQos::DATA_DROP, Sequence::Bit16, &mixed),
5900 10
5901 );
5902 assert_eq!(allowance(200, PutQos::DATA_DROP, Sequence::Bit8, &lane), 9);
5903 assert_eq!(
5904 allowance(200, PutQos::DATA_DROP, Sequence::Bit64, &lane),
5905 13
5906 );
5907 }
5908
5909 #[test]
5912 fn the_sequence_window_and_the_handshake_are_integer_arithmetic() {
5913 assert!(!window_filled(Sequence::Bit16, 222, 240_000, 2_400));
5914 assert!(window_filled(Sequence::Bit8, 222, 240_000, 2_400));
5915 assert!(under_handshake(10_000, 293));
5916 assert!(!under_handshake(40_000, 293));
5917 assert!(!under_handshake(2_560, 2_400));
5918 assert!(under_handshake(2_559, 2_400));
5919 assert!(!reply_short(15_000, 2_400, 222));
5920 assert!(reply_short(11_000, 2_400, 222));
5921 }
5922
5923 #[test]
5927 fn an_empty_link_protocol_list_reads_as_absent() {
5928 let radio = face("ground", &["unixsock-stream"]);
5929 let block = |links: Option<Vec<String>>| BlockSubjects {
5930 posture: Posture::Deny,
5931 subjects: vec![BlockSubject {
5932 id: "local".into(),
5933 usernames: vec!["local".into()],
5934 link_protocols: links,
5935 ..BlockSubject::default()
5936 }],
5937 policies: vec![BlockPolicy {
5938 subjects: vec!["local".into()],
5939 }],
5940 };
5941 let found = |links| check_subjects("radio", &radio, &block(links));
5942 assert_eq!(found(Some(Vec::new())), found(None));
5943 assert_eq!(found(None).len(), 1);
5944 }
5945
5946 #[test]
5947 fn the_batch_against_the_lease_is_integer_arithmetic() {
5948 assert!(within_lease(1000, 2400, 10_000));
5949 assert!(!within_lease(1024, 2400, 10_000));
5950 assert!(within_lease(65_535, MAX_U32, MAX_U32));
5951 }
5952
5953 #[test]
5958 fn a_far_side_reads_its_face_of_a_link_v2_policy() {
5959 use std::time::Duration;
5960 let text = "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5961 binding = \"zenoh-1.10.1\"\n\
5962 [transport]\nlease_ms = 240000\nkeep_alive = 4\n\
5963 wait_before_close_ms = 240000\nsequence = \"16bit\"\nbatch_bytes = 222\n\
5964 [face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
5965 select = { link_protocols = [\"unixsock-stream\"] }\n\
5966 class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
5967 link_bps = 2400\nloss_ppm = 50000\narq = false\nreply_timeout_ms = 15000\n";
5968 let parsed = parse(text);
5969 let policy = parsed.policy.expect("a policy");
5970 let far = policy.far_side("rf").expect("its face");
5971 assert_eq!(far.reply_timeout(), Duration::from_secs(15));
5972 assert_eq!(
5973 far.at_least(Duration::from_secs(1)),
5974 Duration::from_secs(15)
5975 );
5976 assert_eq!(
5977 far.at_least(Duration::from_secs(30)),
5978 Duration::from_secs(30)
5979 );
5980 assert!(
5981 far.redeclares(),
5982 "no ARQ: a silent subscription is declared again"
5983 );
5984 assert_eq!(
5985 FarSide::silence(Duration::from_secs(300)),
5986 Duration::from_secs(600)
5987 );
5988 let keys = far.session_keys();
5989 assert_eq!(keys.len(), 8);
5990 assert_eq!(
5991 keys[2],
5992 (TransportKey::WaitBeforeClose, Value::from(240_000_000u64)),
5993 "wait_before_close in µs"
5994 );
5995 assert!(matches!(
5996 policy.far_side("sbd"),
5997 Err(FarSideRefusal::NoFace { faces, .. }) if faces == ["rf"]
5998 ));
5999 let v1 = FacePolicy {
6000 profile: Profile::V1,
6001 transport: None,
6002 ..policy
6003 };
6004 assert_eq!(v1.far_side("rf"), Err(FarSideRefusal::NotV2));
6005 }
6006}