Skip to main content

modem_device/
conformance.rs

1//! A conformance kit for device implementors (#131).
2//!
3//! The owner's IP driver implements [`Device`], [`Netdev`] and [`Configure`]
4//! outside the code that shaped them, and the tests that kept this
5//! workspace's implementors honest were written against specific media —
6//! `modem-driver`'s decorator check, the edge-triggered event checks, the
7//! "registry does not lie" test. This module is those tests with the medium
8//! taken out: an implementor calls them from its own suite, and a decorator
9//! wrapped around any device is checked the same way. The wire-level half —
10//! against a running management plane — is `modem_mgmt::conformance`.
11//!
12//! Every check returns the [`Failure`]s it found rather than panicking, so
13//! the kit's own tests can hand it a deliberately broken implementor and
14//! read what it says; [`assert_clean`] is the one-line form for a suite.
15//! Nothing here needs a runtime: the checks that wait take a deadline or a
16//! tick future from the caller and race it themselves, so a paused clock
17//! works.
18//!
19//! **What it cannot check** is that `report`, `oper` and `identity` do no
20//! I/O. Their signatures are sync, and a device that blocks in them stalls
21//! the plane's publish task rather than failing a test. The kit checks what
22//! follows from the contract instead: two calls in a row agree, and a report
23//! that carries a reading says how old it is.
24
25use std::collections::BTreeSet;
26use std::fmt;
27use std::future::Future;
28use std::pin::{Pin, pin};
29use std::sync::{Arc, Mutex};
30use std::task::Poll;
31
32use crate::action::{ActionError, ActionOutcome, ActionSpec, Actions, CostModel};
33use crate::config::{
34    ConfigError, ConfigValue, Configure, Effective, ParamClass, ParamKind, ParamSpec, Schema,
35};
36use crate::{
37    Capabilities, Counter, Device, DeviceError, DeviceEvent, Duplex, Edge, EndpointId, Guarantee,
38    Identity, LaneKey, Medium, Metrics, Netdev, NetdevStats, OperStatus, Report, Scope, Sdu,
39    SecurityProperties,
40};
41
42pub mod layer;
43
44/// One thing an implementor got wrong, by the check that found it.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Failure {
47    /// Which check: a stable kebab-case name, so a suite can match on it.
48    pub check: &'static str,
49    /// What was seen, in enough words to fix it.
50    pub detail: String,
51}
52
53impl Failure {
54    fn new(check: &'static str, detail: impl Into<String>) -> Self {
55        Self {
56            check,
57            detail: detail.into(),
58        }
59    }
60}
61
62impl fmt::Display for Failure {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(f, "{}: {}", self.check, self.detail)
65    }
66}
67
68/// Panic with every failure listed, or return.
69///
70/// # Panics
71///
72/// If `failures` is not empty, naming `what` and each failure on its own line.
73pub fn assert_clean(what: &str, failures: &[Failure]) {
74    assert!(
75        failures.is_empty(),
76        "{what} fails {} conformance check(s):\n{}",
77        failures.len(),
78        failures
79            .iter()
80            .map(|f| format!("  - {f}"))
81            .collect::<Vec<_>>()
82            .join("\n")
83    );
84}
85
86// --- decorators -------------------------------------------------------------
87
88/// Every method of [`Device`]. All defaulted, so a decorator that forgets
89/// one compiles and answers for itself.
90pub const DEVICE_METHODS: [&str; 9] = [
91    "report",
92    "oper",
93    "identity",
94    "next_event",
95    "close",
96    "configuration",
97    "actions",
98    "security",
99    "counters",
100];
101
102/// Every method of [`Medium`], the [`Device`] ones included. The ones with
103/// no default are listed too, so this need not be edited on the day one of
104/// them gains one — which is the change that would reopen the hole.
105pub const MEDIUM_METHODS: [&str; 14] = [
106    "report",
107    "oper",
108    "identity",
109    "next_event",
110    "close",
111    "configuration",
112    "actions",
113    "security",
114    "counters",
115    "capabilities",
116    "send",
117    "recv",
118    "metrics",
119    "configure_lanes",
120];
121
122/// Every method of [`Netdev`], the [`Device`] ones included.
123pub const NETDEV_METHODS: [&str; 13] = [
124    "report",
125    "oper",
126    "identity",
127    "next_event",
128    "close",
129    "configuration",
130    "actions",
131    "security",
132    "counters",
133    "interface",
134    "statistics",
135    "epoch",
136    "destinations",
137];
138
139/// An inner device that records which methods reached it, and answers each
140/// with a value nothing else would produce — so one fixture asserts two
141/// things: that the call *arrived*, and that what the decorator handed back
142/// is what the inner device said rather than something it invented.
143struct Recording {
144    config: RecordedConfig,
145    actions: RecordedActions,
146    seen: Mutex<BTreeSet<&'static str>>,
147}
148
149impl Recording {
150    fn new() -> Self {
151        Self {
152            config: RecordedConfig,
153            actions: RecordedActions,
154            seen: Mutex::new(BTreeSet::new()),
155        }
156    }
157
158    fn mark(&self, method: &'static str) {
159        self.seen.lock().expect("not poisoned").insert(method);
160    }
161
162    fn seen(&self) -> BTreeSet<&'static str> {
163        self.seen.lock().expect("not poisoned").clone()
164    }
165
166    fn caps() -> Capabilities {
167        Capabilities::new(218, 217, Duplex::Half, false)
168    }
169
170    fn security() -> SecurityProperties {
171        SecurityProperties::new("recorded", Scope::Hop).guarantee(Guarantee::Integrity)
172    }
173
174    fn counters() -> Vec<Counter> {
175        vec![Counter::new("recorded", "calls_total", 3)]
176    }
177
178    fn report() -> Report {
179        Report::new().age_ms(17).retransmits(5)
180    }
181
182    fn oper() -> OperStatus {
183        OperStatus::down("recorded", true)
184    }
185
186    fn identity() -> Identity {
187        Identity::unknown().model_name("recorded")
188    }
189
190    fn lane() -> LaneKey {
191        LaneKey {
192            endpoint: EndpointId::new("b"),
193            reliable: false,
194            rank: 0,
195        }
196    }
197
198    fn stats() -> NetdevStats {
199        NetdevStats::new().in_octets(4242)
200    }
201}
202
203struct RecordedConfig;
204
205#[async_trait::async_trait]
206impl Configure for RecordedConfig {
207    fn schema(&self) -> Schema {
208        Schema::new()
209    }
210    fn effective(&self) -> Effective {
211        Effective::default()
212    }
213}
214
215struct RecordedActions;
216
217#[async_trait::async_trait]
218impl Actions for RecordedActions {
219    fn specs(&self) -> Vec<ActionSpec> {
220        vec![ActionSpec::new("recorded", "", CostModel::Free)]
221    }
222    async fn invoke(
223        &self,
224        _name: &str,
225        _arguments: &std::collections::BTreeMap<String, ConfigValue>,
226    ) -> Result<ActionOutcome, ActionError> {
227        Ok(ActionOutcome::new("recorded"))
228    }
229}
230
231#[async_trait::async_trait]
232impl Device for Recording {
233    fn report(&self) -> Report {
234        self.mark("report");
235        Self::report()
236    }
237    fn oper(&self) -> OperStatus {
238        self.mark("oper");
239        Self::oper()
240    }
241    fn identity(&self) -> Identity {
242        self.mark("identity");
243        Self::identity()
244    }
245    fn configuration(&self) -> Option<&dyn Configure> {
246        self.mark("configuration");
247        Some(&self.config)
248    }
249    fn actions(&self) -> Option<&dyn Actions> {
250        self.mark("actions");
251        Some(&self.actions)
252    }
253    async fn close(&self) -> Result<(), DeviceError> {
254        self.mark("close");
255        Ok(())
256    }
257    async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
258        self.mark("next_event");
259        Ok(DeviceEvent::raised("recorded"))
260    }
261    fn security(&self) -> Option<SecurityProperties> {
262        self.mark("security");
263        Some(Self::security())
264    }
265    fn counters(&self) -> Vec<Counter> {
266        self.mark("counters");
267        Self::counters()
268    }
269}
270
271#[async_trait::async_trait]
272impl Medium for Recording {
273    fn capabilities(&self) -> Capabilities {
274        self.mark("capabilities");
275        Self::caps()
276    }
277    async fn send(&self, _lane: &LaneKey, _sdu: &[u8]) -> Result<(), DeviceError> {
278        self.mark("send");
279        Ok(())
280    }
281    async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError> {
282        self.mark("recv");
283        Ok((Self::lane(), vec![0xAB]))
284    }
285    fn metrics(&self) -> Metrics {
286        self.mark("metrics");
287        Metrics::new().tx_sdus(7)
288    }
289    async fn configure_lanes(&self, _lanes: &[LaneKey]) -> Result<(), DeviceError> {
290        self.mark("configure_lanes");
291        Ok(())
292    }
293}
294
295impl Netdev for Recording {
296    fn interface(&self) -> &'static str {
297        self.mark("interface");
298        "recorded0"
299    }
300    fn statistics(&self) -> NetdevStats {
301        self.mark("statistics");
302        Self::stats()
303    }
304    fn epoch(&self) -> u64 {
305        self.mark("epoch");
306        42
307    }
308    fn destinations(&self) -> Option<Vec<crate::Destination>> {
309        self.mark("destinations");
310        Some(vec![crate::Destination::new("recorded-neighbour")])
311    }
312}
313
314/// The [`Device`] half of a forwarding check: everything but `close`, which
315/// the caller does last.
316async fn device_calls(name: &str, dev: &dyn Device, out: &mut Vec<Failure>) {
317    let report = dev.report();
318    let oper = dev.oper();
319    let identity = dev.identity();
320    let configuration = dev.configuration().is_some();
321    let actions = dev.actions().is_some();
322    let event = dev.next_event().await;
323    if report != Recording::report() {
324        out.push(Failure::new(
325            "decorator-forwards",
326            format!("{name} rewrote report: {report:?}"),
327        ));
328    }
329    if oper != Recording::oper() {
330        out.push(Failure::new(
331            "decorator-forwards",
332            format!("{name} rewrote oper: {oper:?}"),
333        ));
334    }
335    if identity != Recording::identity() {
336        out.push(Failure::new(
337            "decorator-forwards",
338            format!("{name} rewrote identity: {identity:?}"),
339        ));
340    }
341    if !configuration {
342        out.push(Failure::new(
343            "decorator-forwards",
344            format!("{name} answers None for configuration: the wrapped device has a plane"),
345        ));
346    }
347    if !actions {
348        out.push(Failure::new(
349            "decorator-forwards",
350            format!("{name} answers None for actions: the wrapped device offers one"),
351        ));
352    }
353    if event.as_ref().ok() != Some(&DeviceEvent::raised("recorded")) {
354        out.push(Failure::new(
355            "decorator-forwards",
356            format!("{name} rewrote next_event: {event:?}"),
357        ));
358    }
359    let security = dev.security();
360    if security.as_ref() != Some(&Recording::security()) {
361        out.push(Failure::new(
362            "decorator-forwards",
363            format!("{name} rewrote security: {security:?}"),
364        ));
365    }
366    let counters = dev.counters();
367    if counters != Recording::counters() {
368        out.push(Failure::new(
369            "decorator-forwards",
370            format!("{name} rewrote counters: {counters:?}"),
371        ));
372    }
373}
374
375fn missing(name: &str, methods: &[&'static str], inner: &Recording, out: &mut Vec<Failure>) {
376    let seen = inner.seen();
377    let missing: Vec<&str> = methods
378        .iter()
379        .copied()
380        .filter(|m| !seen.contains(m))
381        .collect();
382    if !missing.is_empty() {
383        out.push(Failure::new(
384            "decorator-forwards",
385            format!(
386                "{name} does not forward {missing:?}, so it answers for itself rather than for \
387                 the device it wraps"
388            ),
389        ));
390    }
391}
392
393/// Does the decorator `wrap` builds forward every method of [`Device`]?
394///
395/// Written against the decorator rather than a list of method names,
396/// because the failure being caught is "somebody wrote a new decorator and
397/// stopped at the methods they needed", and only a decorator can exhibit it.
398pub async fn device_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
399where
400    F: FnOnce(Arc<dyn Device>) -> Arc<dyn Device>,
401{
402    let inner = Arc::new(Recording::new());
403    let dev = wrap(inner.clone() as Arc<dyn Device>);
404    let mut out = Vec::new();
405    device_calls(name, dev.as_ref(), &mut out).await;
406    if let Err(e) = dev.close().await {
407        out.push(Failure::new(
408            "decorator-forwards",
409            format!("{name} failed close: {e}"),
410        ));
411    }
412    missing(name, &DEVICE_METHODS, &inner, &mut out);
413    out
414}
415
416/// Does the decorator `wrap` builds forward every method of [`Medium`]?
417pub async fn medium_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
418where
419    F: FnOnce(Arc<dyn Medium>) -> Arc<dyn Medium>,
420{
421    let inner = Arc::new(Recording::new());
422    let medium = wrap(inner.clone() as Arc<dyn Medium>);
423    let mut out = Vec::new();
424    device_calls(name, medium.as_ref(), &mut out).await;
425    let caps = medium.capabilities();
426    if caps != Recording::caps() {
427        out.push(Failure::new(
428            "decorator-forwards",
429            format!("{name} rewrote capabilities: {caps:?}"),
430        ));
431    }
432    if let Err(e) = medium.send(&Recording::lane(), b"payload").await {
433        out.push(Failure::new(
434            "decorator-forwards",
435            format!("{name} failed send: {e}"),
436        ));
437    }
438    match medium.recv().await {
439        Ok((_, sdu)) if sdu == vec![0xAB] => {}
440        other => out.push(Failure::new(
441            "decorator-forwards",
442            format!("{name} rewrote recv: {other:?}"),
443        )),
444    }
445    let metrics = medium.metrics();
446    if metrics.tx_sdus != 7 {
447        out.push(Failure::new(
448            "decorator-forwards",
449            format!("{name} rewrote metrics: {metrics:?}"),
450        ));
451    }
452    if let Err(e) = medium.configure_lanes(&[Recording::lane()]).await {
453        out.push(Failure::new(
454            "decorator-forwards",
455            format!("{name} failed configure_lanes: {e}"),
456        ));
457    }
458    if let Err(e) = medium.close().await {
459        out.push(Failure::new(
460            "decorator-forwards",
461            format!("{name} failed close: {e}"),
462        ));
463    }
464    missing(name, &MEDIUM_METHODS, &inner, &mut out);
465    out
466}
467
468/// Does the decorator `wrap` builds forward every method of [`Netdev`]?
469pub async fn netdev_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
470where
471    F: FnOnce(Arc<dyn Netdev>) -> Arc<dyn Netdev>,
472{
473    let inner = Arc::new(Recording::new());
474    let dev = wrap(inner.clone() as Arc<dyn Netdev>);
475    let mut out = Vec::new();
476    device_calls(name, dev.as_ref(), &mut out).await;
477    if dev.interface() != "recorded0" {
478        out.push(Failure::new(
479            "decorator-forwards",
480            format!("{name} rewrote interface: {:?}", dev.interface()),
481        ));
482    }
483    if dev.statistics() != Recording::stats() {
484        out.push(Failure::new(
485            "decorator-forwards",
486            format!("{name} rewrote statistics: {:?}", dev.statistics()),
487        ));
488    }
489    if dev.epoch() != 42 {
490        out.push(Failure::new(
491            "decorator-forwards",
492            format!("{name} rewrote epoch: {}", dev.epoch()),
493        ));
494    }
495    if dev.destinations() != Some(vec![crate::Destination::new("recorded-neighbour")]) {
496        out.push(Failure::new(
497            "decorator-forwards",
498            format!("{name} rewrote destinations: {:?}", dev.destinations()),
499        ));
500    }
501    if let Err(e) = dev.close().await {
502        out.push(Failure::new(
503            "decorator-forwards",
504            format!("{name} failed close: {e}"),
505        ));
506    }
507    missing(name, &NETDEV_METHODS, &inner, &mut out);
508    out
509}
510
511// --- the core plane ---------------------------------------------------------
512
513/// `report`, `oper` and `identity` are sync and cached: two calls in a row
514/// agree, and a report that carries any reading says how old it is
515/// ([`Report::age_ms`]), which is how a cached answer is honest about being
516/// one.
517///
518/// A report's age may tick between the two calls; it is the one field left
519/// out of the comparison.
520#[must_use]
521pub fn core(dev: &dyn Device) -> Vec<Failure> {
522    let mut out = Vec::new();
523    let ageless = |mut r: Report| {
524        r.age_ms = None;
525        r
526    };
527    let (a, b) = (dev.report(), dev.report());
528    if ageless(a) != ageless(b) {
529        out.push(Failure::new(
530            "report-is-cached",
531            format!("two calls in a row disagree: {a:?} then {b:?}"),
532        ));
533    }
534    if ageless(a) != Report::default() && a.age_ms.is_none() {
535        out.push(Failure::new(
536            "report-says-its-age",
537            format!("the report carries a reading and no age_ms: {a:?}"),
538        ));
539    }
540    let (a, b) = (dev.oper(), dev.oper());
541    if a != b {
542        out.push(Failure::new(
543            "oper-is-cached",
544            format!("two calls in a row disagree: {a:?} then {b:?}"),
545        ));
546    }
547    let (a, b) = (dev.identity(), dev.identity());
548    if a != b {
549        out.push(Failure::new(
550            "identity-is-cached",
551            format!("two calls in a row disagree: {a:?} then {b:?}"),
552        ));
553    }
554    out
555}
556
557/// Race `fut` against a deadline: `Some` if it finished first.
558async fn until<T>(
559    fut: impl Future<Output = T>,
560    mut deadline: Pin<&mut impl Future<Output = ()>>,
561) -> Option<T> {
562    let mut fut = pin!(fut);
563    std::future::poll_fn(|cx| {
564        if let Poll::Ready(v) = fut.as_mut().poll(cx) {
565            return Poll::Ready(Some(v));
566        }
567        match deadline.as_mut().poll(cx) {
568            Poll::Ready(()) => Poll::Ready(None),
569            Poll::Pending => Poll::Pending,
570        }
571    })
572    .await
573}
574
575/// `next_event` is edge-triggered (the [`Edge`] contract): the same words
576/// with the same edge twice in a row on one lane, with nothing between, is
577/// a condition being repeated while it persists — the stream no `rate`
578/// declaration could cover.
579///
580/// Drains events until `deadline` resolves; an `Err` from `next_event` ends
581/// the drain and is not a finding, since a device may say it has closed. A
582/// device with nothing to report passes trivially, so an implementor's own
583/// test should provoke a condition first where it can.
584pub async fn events_are_edge_triggered(
585    dev: &dyn Device,
586    deadline: impl Future<Output = ()>,
587) -> Vec<Failure> {
588    let mut deadline = pin!(deadline);
589    let mut out = Vec::new();
590    let mut last: Vec<(Option<LaneKey>, DeviceEvent)> = Vec::new();
591    // An `Err` ends the drain: a device may say it has closed.
592    while let Some(Ok(ev)) = until(dev.next_event(), deadline.as_mut()).await {
593        if let Some((_, prev)) = last.iter().find(|(lane, _)| *lane == ev.lane)
594            && prev.edge == ev.edge
595            && prev.detail == ev.detail
596        {
597            out.push(Failure::new(
598                "events-are-edge-triggered",
599                format!(
600                    "{:?} {:?} was reported twice in a row with no {:?} between: a condition \
601                     is one event when it starts and one when it stops",
602                    ev.edge,
603                    ev.detail,
604                    match ev.edge {
605                        Edge::Raised => Edge::Cleared,
606                        _ => Edge::Raised,
607                    }
608                ),
609            ));
610        }
611        last.retain(|(lane, _)| *lane != ev.lane);
612        last.push((ev.lane.clone(), ev));
613    }
614    out
615}
616
617// --- the configuration plane ------------------------------------------------
618
619fn plain_chunk(s: &str) -> bool {
620    !s.is_empty()
621        && s.chars()
622            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
623}
624
625/// The schema is well-formed: unique group and parameter names that can be
626/// spelled in a key, a description on each, at least one parameter per
627/// group, and integer bounds that do not cross.
628///
629/// A unit is not required on an integer: the vocabulary says `None` is a
630/// count.
631#[must_use]
632pub fn schema_is_valid(schema: &Schema) -> Vec<Failure> {
633    let mut out = Vec::new();
634    let mut groups = BTreeSet::new();
635    for g in &schema.groups {
636        if !plain_chunk(g.name) {
637            out.push(Failure::new(
638                "schema-is-valid",
639                format!(
640                    "group {:?} is not a plain chunk (lowercase, digits, `_`, `-`): it is \
641                     spelled in the write key",
642                    g.name
643                ),
644            ));
645        }
646        if !groups.insert(g.name) {
647            out.push(Failure::new(
648                "schema-is-valid",
649                format!("group {:?} is declared twice", g.name),
650            ));
651        }
652        if g.description.trim().is_empty() {
653            out.push(Failure::new(
654                "schema-is-valid",
655                format!("group {:?} has no description", g.name),
656            ));
657        }
658        if g.parameters.is_empty() {
659            out.push(Failure::new(
660                "schema-is-valid",
661                format!("group {:?} declares no parameter", g.name),
662            ));
663        }
664        let mut names = BTreeSet::new();
665        for p in &g.parameters {
666            if !plain_chunk(p.name) {
667                out.push(Failure::new(
668                    "schema-is-valid",
669                    format!("{}/{:?} is not a plain chunk", g.name, p.name),
670                ));
671            }
672            if !names.insert(p.name) {
673                out.push(Failure::new(
674                    "schema-is-valid",
675                    format!("{}/{} is declared twice", g.name, p.name),
676                ));
677            }
678            if p.description.trim().is_empty() {
679                out.push(Failure::new(
680                    "schema-is-valid",
681                    format!("{}/{} has no description", g.name, p.name),
682                ));
683            }
684            if let ParamKind::Integer {
685                min: Some(min),
686                max: Some(max),
687                ..
688            } = p.kind
689                && min > max
690            {
691                out.push(Failure::new(
692                    "schema-is-valid",
693                    format!("{}/{}: min {min} is above max {max}", g.name, p.name),
694                ));
695            }
696        }
697    }
698    out
699}
700
701/// What the device runs with is within what it declares: every value in
702/// `effective` names a declared parameter and passes its bound, and no
703/// sensitive parameter is read back.
704#[must_use]
705pub fn effective_within_schema(schema: &Schema, effective: &Effective) -> Vec<Failure> {
706    let mut out = Vec::new();
707    for (group, params) in effective {
708        for (name, value) in params {
709            if let Err(e) = schema.check(group, name, value) {
710                out.push(Failure::new(
711                    "effective-within-schema",
712                    format!("effective carries {group}/{name} = {value}: {e}"),
713                ));
714            }
715        }
716    }
717    out.extend(sensitive_absent(schema, effective));
718    out
719}
720
721fn sensitive_absent(schema: &Schema, effective: &Effective) -> Vec<Failure> {
722    let mut out = Vec::new();
723    for g in &schema.groups {
724        for p in g.parameters.iter().filter(|p| p.sensitive) {
725            if effective
726                .get(g.name)
727                .is_some_and(|values| values.contains_key(p.name))
728            {
729                out.push(Failure::new(
730                    "sensitive-never-read-back",
731                    format!(
732                        "{}/{} is sensitive and effective carries a value for it",
733                        g.name, p.name
734                    ),
735                ));
736            }
737        }
738    }
739    out
740}
741
742/// A value the spec accepts that differs from `current`.
743fn other_value(spec: &ParamSpec, current: Option<&ConfigValue>) -> ConfigValue {
744    match (&spec.kind, current) {
745        (ParamKind::Bool, Some(ConfigValue::Bool(b))) => ConfigValue::Bool(!b),
746        (ParamKind::Bool, _) => ConfigValue::Bool(true),
747        (ParamKind::Integer { min, max, .. }, cur) => {
748            let cur = match cur {
749                Some(ConfigValue::Integer(i)) => *i,
750                _ => min.unwrap_or(0),
751            };
752            let up = cur.saturating_add(1);
753            if max.is_none_or(|m| up <= m) {
754                ConfigValue::Integer(up)
755            } else {
756                ConfigValue::Integer(cur.saturating_sub(1).max(min.unwrap_or(i64::MIN)))
757            }
758        }
759        (ParamKind::Text, Some(ConfigValue::Text(t))) => {
760            ConfigValue::Text(format!("{t}-conformance"))
761        }
762        (_, _) => ConfigValue::Text("conformance".into()),
763    }
764}
765
766/// Every contract group is refused at runtime with the restart named
767/// ([`ConfigError::Contract`]): a change to what the transport was started
768/// against belongs in the startup file.
769pub async fn contract_refused(cfg: &dyn Configure) -> Vec<Failure> {
770    let mut out = Vec::new();
771    let schema = cfg.schema();
772    let effective = cfg.effective();
773    for g in schema
774        .groups
775        .iter()
776        .filter(|g| g.class == ParamClass::Contract)
777    {
778        let Some(p) = g.parameters.first() else {
779            continue;
780        };
781        let current = effective.get(g.name).and_then(|v| v.get(p.name));
782        let value = other_value(p, current);
783        let change = [(p.name.to_string(), value.clone())].into_iter().collect();
784        match cfg.apply(g.name, &change).await {
785            Err(ConfigError::Contract(_)) => {}
786            Ok(_) => out.push(Failure::new(
787                "contract-refused",
788                format!(
789                    "contract group {:?} accepted {}={} at runtime; it is part of what the \
790                     transport was started against and belongs in the startup file",
791                    g.name, p.name, value
792                ),
793            )),
794            Err(e) => out.push(Failure::new(
795                "contract-refused",
796                format!(
797                    "contract group {:?} was refused for another reason than the contract, so \
798                     the caller is not told to restart: {e}",
799                    g.name
800                ),
801            )),
802        }
803    }
804    out
805}
806
807/// The read-back rule (architecture §4.6): after `apply`, `effective` shows
808/// the change; after applying the `Undo` it answered, the previous values
809/// are back. Every non-sensitive parameter of every hot and reach group,
810/// one at a time, with a value the schema accepts.
811///
812/// A group the device answers [`ConfigError::Unsupported`] for is skipped:
813/// declaring a group before being able to change it is what that error
814/// means, and it is honest.
815pub async fn read_back_and_undo(cfg: &dyn Configure) -> Vec<Failure> {
816    let mut out = Vec::new();
817    let schema = cfg.schema();
818    for g in schema
819        .groups
820        .iter()
821        .filter(|g| g.class != ParamClass::Contract)
822    {
823        for p in g.parameters.iter().filter(|p| !p.sensitive) {
824            let before = cfg.effective();
825            let current = before.get(g.name).and_then(|v| v.get(p.name));
826            let value = other_value(p, current);
827            let change = [(p.name.to_string(), value.clone())].into_iter().collect();
828            let undo = match cfg.apply(g.name, &change).await {
829                Ok(undo) => undo,
830                Err(ConfigError::Unsupported(_)) => break,
831                Err(e) => {
832                    out.push(Failure::new(
833                        "read-back",
834                        format!(
835                            "the schema says {}/{} accepts {value}; the device refused it: {e}",
836                            g.name, p.name
837                        ),
838                    ));
839                    continue;
840                }
841            };
842            let after = cfg.effective();
843            let read_back = after.get(g.name).and_then(|v| v.get(p.name));
844            if read_back != Some(&value) {
845                out.push(Failure::new(
846                    "read-back",
847                    format!(
848                        "after apply {}/{}={value}, effective says {}: a change is not done \
849                         until it can be read back",
850                        g.name,
851                        p.name,
852                        read_back.map_or("nothing".to_string(), ToString::to_string)
853                    ),
854                ));
855            }
856            if let Err(e) = cfg.apply(g.name, &undo).await {
857                out.push(Failure::new(
858                    "undo-restores",
859                    format!("the undo for {}/{} was refused: {e}", g.name, p.name),
860                ));
861                continue;
862            }
863            let restored = cfg.effective();
864            if restored != before {
865                out.push(Failure::new(
866                    "undo-restores",
867                    format!(
868                        "after apply {}/{}={value} and its undo {undo:?}, effective is not what \
869                         it was: {restored:?} vs {before:?}",
870                        g.name, p.name
871                    ),
872                ));
873            }
874        }
875    }
876    out
877}
878
879/// A sensitive parameter is write-only: after a value is applied, it is in
880/// none of `effective`, its `Debug`, or the `Debug` of the report, the
881/// operational status and the identity.
882///
883/// Text parameters carry a marker nothing else would contain; a sensitive
884/// integer or switch is only checked to be absent from `effective`, because
885/// a number cannot be told from any other.
886pub async fn sensitive_never_read_back(dev: &dyn Device) -> Vec<Failure> {
887    let Some(cfg) = dev.configuration() else {
888        return Vec::new();
889    };
890    let schema = cfg.schema();
891    let mut out = sensitive_absent(&schema, &cfg.effective());
892    let marker = format!(
893        "conformance-{}",
894        std::time::SystemTime::now()
895            .duration_since(std::time::UNIX_EPOCH)
896            .map_or(0, |d| d.as_nanos())
897    );
898    for g in schema
899        .groups
900        .iter()
901        .filter(|g| g.class != ParamClass::Contract)
902    {
903        for p in g
904            .parameters
905            .iter()
906            .filter(|p| p.sensitive && p.kind == ParamKind::Text)
907        {
908            let change = [(p.name.to_string(), ConfigValue::Text(marker.clone()))]
909                .into_iter()
910                .collect();
911            let undo = match cfg.apply(g.name, &change).await {
912                Ok(undo) => undo,
913                Err(ConfigError::Unsupported(_)) => break,
914                Err(e) => {
915                    out.push(Failure::new(
916                        "sensitive-never-read-back",
917                        format!(
918                            "the schema says {}/{} takes text; the device refused it: {e}",
919                            g.name, p.name
920                        ),
921                    ));
922                    continue;
923                }
924            };
925            let effective = cfg.effective();
926            let leaks = [
927                ("effective", format!("{effective:?}")),
928                ("the schema", format!("{:?}", cfg.schema())),
929                ("the report", format!("{:?}", dev.report())),
930                ("oper", format!("{:?}", dev.oper())),
931                ("the identity", format!("{:?}", dev.identity())),
932            ];
933            for (what, text) in leaks {
934                if text.contains(&marker) {
935                    out.push(Failure::new(
936                        "sensitive-never-read-back",
937                        format!(
938                            "the value written to sensitive {}/{} appears in {what}: {text}",
939                            g.name, p.name
940                        ),
941                    ));
942                }
943            }
944            if !undo.is_empty()
945                && let Err(e) = cfg.apply(g.name, &undo).await
946            {
947                out.push(Failure::new(
948                    "sensitive-never-read-back",
949                    format!("the undo for {}/{} was refused: {e}", g.name, p.name),
950                ));
951            }
952        }
953    }
954    out
955}
956
957/// The whole configuration plane, for a device that has one; nothing to
958/// check for one that does not.
959pub async fn configuration(dev: &dyn Device) -> Vec<Failure> {
960    let Some(cfg) = dev.configuration() else {
961        return Vec::new();
962    };
963    let schema = cfg.schema();
964    let mut out = schema_is_valid(&schema);
965    out.extend(effective_within_schema(&schema, &cfg.effective()));
966    out.extend(contract_refused(cfg).await);
967    out.extend(read_back_and_undo(cfg).await);
968    out.extend(sensitive_never_read_back(dev).await);
969    out
970}
971
972// --- a netdev -----------------------------------------------------------------
973
974/// One counter of a [`NetdevStats`].
975type StatRead = fn(&NetdevStats) -> Option<u64>;
976
977/// Each counter by name.
978const COUNTERS: [(&str, StatRead); 9] = [
979    ("in_octets", |s| s.in_octets),
980    ("out_octets", |s| s.out_octets),
981    ("in_errors", |s| s.in_errors),
982    ("out_errors", |s| s.out_errors),
983    ("in_discards", |s| s.in_discards),
984    ("out_discards", |s| s.out_discards),
985    ("in_multicast_pkts", |s| s.in_multicast_pkts),
986    ("in_pkts", |s| s.in_pkts),
987    ("out_pkts", |s| s.out_pkts),
988];
989
990/// The interface has a name, and within one presence epoch no counter goes
991/// backwards: `samples` readings, `tick` awaited between each — a sleep, or
992/// whatever lets the device's poller run.
993///
994/// A counter that does decrease is the device's cue to move its epoch,
995/// which is the one reset the registry sanctions; a decrease without one
996/// is what this catches.
997pub async fn netdev<Fut>(
998    dev: &dyn Netdev,
999    samples: usize,
1000    mut tick: impl FnMut() -> Fut,
1001) -> Vec<Failure>
1002where
1003    Fut: Future<Output = ()>,
1004{
1005    let mut out = Vec::new();
1006    if dev.interface().trim().is_empty() {
1007        out.push(Failure::new(
1008            "netdev-is-named",
1009            "interface() is empty: a netdev is named as the kernel spells it",
1010        ));
1011    }
1012    let mut prev = (dev.epoch(), dev.statistics());
1013    for _ in 0..samples {
1014        tick().await;
1015        let now = (dev.epoch(), dev.statistics());
1016        if now.0 == prev.0 {
1017            for (name, read) in COUNTERS {
1018                if let (Some(a), Some(b)) = (read(&prev.1), read(&now.1))
1019                    && b < a
1020                {
1021                    out.push(Failure::new(
1022                        "counters-never-decrease",
1023                        format!(
1024                            "{name} went from {a} to {b} within epoch {}: a counter that resets \
1025                             moves the epoch",
1026                            now.0
1027                        ),
1028                    ));
1029                }
1030            }
1031        }
1032        prev = now;
1033    }
1034    out
1035}
1036
1037/// Everything a [`Device`] is held to: [`core()`], [`events_are_edge_triggered`]
1038/// until `event_deadline`, and [`configuration`].
1039pub async fn device(dev: &dyn Device, event_deadline: impl Future<Output = ()>) -> Vec<Failure> {
1040    let mut out = core(dev);
1041    out.extend(events_are_edge_triggered(dev, event_deadline).await);
1042    out.extend(configuration(dev).await);
1043    out
1044}
1045
1046#[cfg(test)]
1047mod tests {
1048    //! One deliberately broken implementor per check, and a clean one that
1049    //! passes them all.
1050    use std::collections::BTreeMap;
1051    use std::sync::atomic::{AtomicU64, Ordering};
1052    use std::time::Duration;
1053
1054    use super::*;
1055    use crate::config::{ConfigGroup, Undo};
1056
1057    fn checks(failures: &[Failure]) -> Vec<&'static str> {
1058        failures.iter().map(|f| f.check).collect()
1059    }
1060
1061    fn detail(failures: &[Failure], check: &str) -> String {
1062        failures
1063            .iter()
1064            .filter(|f| f.check == check)
1065            .map(|f| f.detail.clone())
1066            .collect::<Vec<_>>()
1067            .join("\n")
1068    }
1069
1070    // --- decorators ---------------------------------------------------------
1071
1072    /// Forwards everything but `oper`.
1073    struct ForgetsOper(Arc<dyn Device>);
1074
1075    #[async_trait::async_trait]
1076    impl Device for ForgetsOper {
1077        fn report(&self) -> Report {
1078            self.0.report()
1079        }
1080        fn identity(&self) -> Identity {
1081            self.0.identity()
1082        }
1083        fn configuration(&self) -> Option<&dyn Configure> {
1084            self.0.configuration()
1085        }
1086        fn actions(&self) -> Option<&dyn Actions> {
1087            self.0.actions()
1088        }
1089        async fn close(&self) -> Result<(), DeviceError> {
1090            self.0.close().await
1091        }
1092        async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1093            self.0.next_event().await
1094        }
1095        fn security(&self) -> Option<SecurityProperties> {
1096            self.0.security()
1097        }
1098        fn counters(&self) -> Vec<Counter> {
1099            self.0.counters()
1100        }
1101    }
1102
1103    /// Forwards everything but `metrics`.
1104    struct ForgetsMetrics(Arc<dyn Medium>);
1105
1106    #[async_trait::async_trait]
1107    impl Device for ForgetsMetrics {
1108        fn report(&self) -> Report {
1109            self.0.report()
1110        }
1111        fn oper(&self) -> OperStatus {
1112            self.0.oper()
1113        }
1114        fn identity(&self) -> Identity {
1115            self.0.identity()
1116        }
1117        fn configuration(&self) -> Option<&dyn Configure> {
1118            self.0.configuration()
1119        }
1120        fn actions(&self) -> Option<&dyn Actions> {
1121            self.0.actions()
1122        }
1123        async fn close(&self) -> Result<(), DeviceError> {
1124            self.0.close().await
1125        }
1126        async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1127            self.0.next_event().await
1128        }
1129        fn security(&self) -> Option<SecurityProperties> {
1130            self.0.security()
1131        }
1132        fn counters(&self) -> Vec<Counter> {
1133            self.0.counters()
1134        }
1135    }
1136
1137    #[async_trait::async_trait]
1138    impl Medium for ForgetsMetrics {
1139        fn capabilities(&self) -> Capabilities {
1140            self.0.capabilities()
1141        }
1142        async fn send(&self, lane: &LaneKey, sdu: &[u8]) -> Result<(), DeviceError> {
1143            self.0.send(lane, sdu).await
1144        }
1145        async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError> {
1146            self.0.recv().await
1147        }
1148        fn metrics(&self) -> Metrics {
1149            Metrics::default()
1150        }
1151        async fn configure_lanes(&self, lanes: &[LaneKey]) -> Result<(), DeviceError> {
1152            self.0.configure_lanes(lanes).await
1153        }
1154    }
1155
1156    /// Forwards everything but `epoch`.
1157    struct ForgetsEpoch(Arc<dyn Netdev>);
1158
1159    #[async_trait::async_trait]
1160    impl Device for ForgetsEpoch {
1161        fn report(&self) -> Report {
1162            self.0.report()
1163        }
1164        fn oper(&self) -> OperStatus {
1165            self.0.oper()
1166        }
1167        fn identity(&self) -> Identity {
1168            self.0.identity()
1169        }
1170        fn configuration(&self) -> Option<&dyn Configure> {
1171            self.0.configuration()
1172        }
1173        fn actions(&self) -> Option<&dyn Actions> {
1174            self.0.actions()
1175        }
1176        async fn close(&self) -> Result<(), DeviceError> {
1177            self.0.close().await
1178        }
1179        async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1180            self.0.next_event().await
1181        }
1182        fn security(&self) -> Option<SecurityProperties> {
1183            self.0.security()
1184        }
1185        fn counters(&self) -> Vec<Counter> {
1186            self.0.counters()
1187        }
1188    }
1189
1190    impl Netdev for ForgetsEpoch {
1191        fn interface(&self) -> &str {
1192            self.0.interface()
1193        }
1194        fn statistics(&self) -> NetdevStats {
1195            self.0.statistics()
1196        }
1197        fn destinations(&self) -> Option<Vec<crate::Destination>> {
1198            self.0.destinations()
1199        }
1200    }
1201
1202    #[tokio::test]
1203    async fn a_decorator_that_forgets_a_method_is_named_with_the_method() {
1204        let f =
1205            device_decorator_forwards("ForgetsOper", |inner| Arc::new(ForgetsOper(inner))).await;
1206        assert_eq!(checks(&f), ["decorator-forwards", "decorator-forwards"]);
1207        let d = detail(&f, "decorator-forwards");
1208        assert!(
1209            d.contains("rewrote oper") && d.contains("[\"oper\"]"),
1210            "{d}"
1211        );
1212
1213        let f =
1214            medium_decorator_forwards("ForgetsMetrics", |inner| Arc::new(ForgetsMetrics(inner)))
1215                .await;
1216        assert!(
1217            detail(&f, "decorator-forwards").contains("[\"metrics\"]"),
1218            "{f:?}"
1219        );
1220
1221        let f =
1222            netdev_decorator_forwards("ForgetsEpoch", |inner| Arc::new(ForgetsEpoch(inner))).await;
1223        assert!(
1224            detail(&f, "decorator-forwards").contains("[\"epoch\"]"),
1225            "{f:?}"
1226        );
1227
1228        // The identity decorator forwards everything, three times over.
1229        assert!(
1230            device_decorator_forwards("id", |inner| inner)
1231                .await
1232                .is_empty()
1233        );
1234        assert!(
1235            medium_decorator_forwards("id", |inner| inner)
1236                .await
1237                .is_empty()
1238        );
1239        assert!(
1240            netdev_decorator_forwards("id", |inner| inner)
1241                .await
1242                .is_empty()
1243        );
1244    }
1245
1246    // --- the core plane -----------------------------------------------------
1247
1248    /// `oper` alternates between two answers: not a cache.
1249    struct Flickers(AtomicU64);
1250
1251    impl Device for Flickers {
1252        fn oper(&self) -> OperStatus {
1253            if self.0.fetch_add(1, Ordering::Relaxed).is_multiple_of(2) {
1254                OperStatus::up()
1255            } else {
1256                OperStatus::unknown()
1257            }
1258        }
1259    }
1260
1261    /// A reading without an age: an answer from I/O pretending to be cached.
1262    struct Ageless;
1263
1264    impl Device for Ageless {
1265        fn report(&self) -> Report {
1266            Report::new().rssi(-70_000)
1267        }
1268    }
1269
1270    #[test]
1271    fn a_status_that_changes_between_two_calls_and_a_reading_without_an_age_are_findings() {
1272        assert_eq!(
1273            checks(&core(&Flickers(AtomicU64::new(0)))),
1274            ["oper-is-cached"]
1275        );
1276        assert_eq!(checks(&core(&Ageless)), ["report-says-its-age"]);
1277        assert!(core(&Recording::new()).is_empty());
1278    }
1279
1280    // --- events ---------------------------------------------------------------
1281
1282    /// Says the same thing `n` times, then falls silent.
1283    struct Repeats {
1284        script: Vec<DeviceEvent>,
1285        at: AtomicU64,
1286    }
1287
1288    #[async_trait::async_trait]
1289    impl Device for Repeats {
1290        async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1291            #[allow(clippy::cast_possible_truncation)]
1292            let i = self.at.fetch_add(1, Ordering::Relaxed) as usize;
1293            match self.script.get(i) {
1294                Some(ev) => Ok(ev.clone()),
1295                None => std::future::pending().await,
1296            }
1297        }
1298    }
1299
1300    #[tokio::test(start_paused = true)]
1301    async fn a_condition_reported_twice_without_the_opposite_edge_is_a_finding() {
1302        let nags = Repeats {
1303            script: vec![
1304                DeviceEvent::raised("+CME ERROR 3"),
1305                DeviceEvent::raised("+CME ERROR 3"),
1306                DeviceEvent::cleared("+CME ERROR 3"),
1307            ],
1308            at: AtomicU64::new(0),
1309        };
1310        let f = events_are_edge_triggered(&nags, tokio::time::sleep(Duration::from_secs(1))).await;
1311        assert_eq!(checks(&f), ["events-are-edge-triggered"]);
1312        assert!(f[0].detail.contains("twice in a row"), "{f:?}");
1313
1314        // Different words for the two edges, as a netdev spells a carrier,
1315        // and a condition that comes back after clearing: no finding.
1316        let edgy = Repeats {
1317            script: vec![
1318                DeviceEvent::raised("no carrier"),
1319                DeviceEvent::cleared("carrier"),
1320                DeviceEvent::raised("no carrier"),
1321                DeviceEvent::raised("registration lost"),
1322            ],
1323            at: AtomicU64::new(0),
1324        };
1325        assert!(
1326            events_are_edge_triggered(&edgy, tokio::time::sleep(Duration::from_secs(1)))
1327                .await
1328                .is_empty()
1329        );
1330    }
1331
1332    // --- the configuration plane --------------------------------------------
1333
1334    #[derive(Clone, Copy, Default)]
1335    #[allow(clippy::struct_excessive_bools)] // one switch per way to get it wrong
1336    struct Faults {
1337        /// Accepts a change and changes nothing.
1338        nods: bool,
1339        /// Answers an empty undo.
1340        forgets_undo: bool,
1341        /// Accepts a change to the contract group.
1342        bends: bool,
1343        /// Reads the PIN back.
1344        leaks: bool,
1345        /// Puts the PIN in the identity.
1346        echoes: bool,
1347        /// Reads back a parameter the schema does not declare.
1348        off_schema: bool,
1349        /// Declares a group twice and a bound that crosses.
1350        bad_schema: bool,
1351    }
1352
1353    /// A device with three groups: hot `tune`, hot `auth` with a sensitive
1354    /// PIN, contract `port`. Each fault is one way to get it wrong.
1355    struct Knobs {
1356        faults: Faults,
1357        state: Mutex<BTreeMap<&'static str, ConfigValue>>,
1358    }
1359
1360    impl Knobs {
1361        fn new(faults: Faults) -> Self {
1362            Self {
1363                faults,
1364                state: Mutex::new(
1365                    [
1366                        ("level", ConfigValue::Integer(3)),
1367                        ("label", ConfigValue::Text("lab".into())),
1368                        ("pin", ConfigValue::Text("0000".into())),
1369                        ("baud", ConfigValue::Integer(9600)),
1370                    ]
1371                    .into_iter()
1372                    .collect(),
1373                ),
1374            }
1375        }
1376
1377        fn get(&self, name: &str) -> ConfigValue {
1378            self.state.lock().expect("not poisoned")[name].clone()
1379        }
1380    }
1381
1382    impl Device for Knobs {
1383        fn identity(&self) -> Identity {
1384            if self.faults.echoes {
1385                Identity::unknown().serial_num(self.get("pin").to_string())
1386            } else {
1387                Identity::unknown()
1388            }
1389        }
1390        fn configuration(&self) -> Option<&dyn Configure> {
1391            Some(self)
1392        }
1393    }
1394
1395    #[async_trait::async_trait]
1396    impl Configure for Knobs {
1397        fn schema(&self) -> Schema {
1398            let mut s = Schema::new()
1399                .with(
1400                    ConfigGroup::new("tune", ParamClass::Hot, "tuning")
1401                        .with(ParamSpec::new(
1402                            "level",
1403                            ParamKind::integer(Some(0), Some(10), None),
1404                            "a level",
1405                        ))
1406                        .with(ParamSpec::new("label", ParamKind::Text, "a label")),
1407                )
1408                .with(
1409                    ConfigGroup::new("auth", ParamClass::Hot, "the PIN")
1410                        .with(ParamSpec::new("pin", ParamKind::Text, "the SIM PIN").sensitive()),
1411                )
1412                .with(
1413                    ConfigGroup::new("port", ParamClass::Contract, "the port").with(
1414                        ParamSpec::new(
1415                            "baud",
1416                            ParamKind::integer(Some(1200), Some(115_200), Some("bit/s")),
1417                            "the rate",
1418                        ),
1419                    ),
1420                );
1421            if self.faults.bad_schema {
1422                s = s.with(ConfigGroup::new("tune", ParamClass::Hot, "again").with(
1423                    ParamSpec::new("x", ParamKind::integer(Some(10), Some(1), None), "crossed"),
1424                ));
1425            }
1426            s
1427        }
1428
1429        fn effective(&self) -> Effective {
1430            let mut tune: BTreeMap<String, ConfigValue> = [
1431                ("level".to_string(), self.get("level")),
1432                ("label".to_string(), self.get("label")),
1433            ]
1434            .into_iter()
1435            .collect();
1436            if self.faults.off_schema {
1437                tune.insert("bogus".into(), ConfigValue::Bool(true));
1438            }
1439            let mut auth = BTreeMap::new();
1440            if self.faults.leaks {
1441                auth.insert("pin".to_string(), self.get("pin"));
1442            }
1443            [
1444                ("tune".to_string(), tune),
1445                ("auth".to_string(), auth),
1446                (
1447                    "port".to_string(),
1448                    [("baud".to_string(), self.get("baud"))]
1449                        .into_iter()
1450                        .collect(),
1451                ),
1452            ]
1453            .into_iter()
1454            .collect()
1455        }
1456
1457        async fn apply(
1458            &self,
1459            group: &str,
1460            values: &BTreeMap<String, ConfigValue>,
1461        ) -> Result<Undo, ConfigError> {
1462            if group == "port" && !self.faults.bends {
1463                return Err(ConfigError::Contract(group.into()));
1464            }
1465            let mut state = self.state.lock().expect("not poisoned");
1466            let mut undo = Undo::new();
1467            for (name, v) in values {
1468                let key: &'static str = match name.as_str() {
1469                    "level" => "level",
1470                    "label" => "label",
1471                    "pin" => "pin",
1472                    "baud" => "baud",
1473                    other => {
1474                        return Err(ConfigError::UnknownParameter {
1475                            group: group.into(),
1476                            name: other.into(),
1477                        });
1478                    }
1479                };
1480                if !self.faults.forgets_undo {
1481                    undo.insert(name.clone(), state[key].clone());
1482                }
1483                if !self.faults.nods {
1484                    state.insert(key, v.clone());
1485                }
1486            }
1487            Ok(undo)
1488        }
1489    }
1490
1491    #[tokio::test]
1492    async fn each_configuration_fault_is_found_and_a_device_without_one_passes() {
1493        assert!(
1494            configuration(&Knobs::new(Faults::default()))
1495                .await
1496                .is_empty()
1497        );
1498
1499        let cases: [(&str, Faults, &str, &str); 7] = [
1500            (
1501                "nods",
1502                Faults {
1503                    nods: true,
1504                    ..Faults::default()
1505                },
1506                "read-back",
1507                "not done until it can be read back",
1508            ),
1509            (
1510                "forgets_undo",
1511                Faults {
1512                    forgets_undo: true,
1513                    ..Faults::default()
1514                },
1515                "undo-restores",
1516                "not what it was",
1517            ),
1518            (
1519                "bends",
1520                Faults {
1521                    bends: true,
1522                    ..Faults::default()
1523                },
1524                "contract-refused",
1525                "accepted",
1526            ),
1527            (
1528                "leaks",
1529                Faults {
1530                    leaks: true,
1531                    ..Faults::default()
1532                },
1533                "sensitive-never-read-back",
1534                "effective",
1535            ),
1536            (
1537                "echoes",
1538                Faults {
1539                    echoes: true,
1540                    ..Faults::default()
1541                },
1542                "sensitive-never-read-back",
1543                "the identity",
1544            ),
1545            (
1546                "off_schema",
1547                Faults {
1548                    off_schema: true,
1549                    ..Faults::default()
1550                },
1551                "effective-within-schema",
1552                "tune/bogus",
1553            ),
1554            (
1555                "bad_schema",
1556                Faults {
1557                    bad_schema: true,
1558                    ..Faults::default()
1559                },
1560                "schema-is-valid",
1561                "declared twice",
1562            ),
1563        ];
1564        for (name, faults, check, words) in cases {
1565            let f = configuration(&Knobs::new(faults)).await;
1566            let d = detail(&f, check);
1567            assert!(
1568                !d.is_empty() && d.contains(words),
1569                "{name}: expected {check} saying {words:?}; got {f:?}"
1570            );
1571        }
1572        // The crossed bound is a second finding of the bad schema.
1573        let f = schema_is_valid(
1574            &Knobs::new(Faults {
1575                bad_schema: true,
1576                ..Faults::default()
1577            })
1578            .schema(),
1579        );
1580        assert!(
1581            detail(&f, "schema-is-valid").contains("min 10 is above max 1"),
1582            "{f:?}"
1583        );
1584    }
1585
1586    // --- a netdev ---------------------------------------------------------
1587
1588    /// Counters that go backwards; with `honest`, the epoch moves when they do.
1589    struct Rewinds {
1590        honest: bool,
1591        reads: AtomicU64,
1592    }
1593
1594    impl Device for Rewinds {}
1595
1596    impl Netdev for Rewinds {
1597        fn interface(&self) -> &'static str {
1598            "wwan0"
1599        }
1600        fn statistics(&self) -> NetdevStats {
1601            let n = self.reads.fetch_add(1, Ordering::Relaxed);
1602            NetdevStats::new().in_octets(if n < 2 { 1_000 } else { 10 })
1603        }
1604        fn epoch(&self) -> u64 {
1605            u64::from(self.honest && self.reads.load(Ordering::Relaxed) >= 2)
1606        }
1607    }
1608
1609    #[tokio::test]
1610    async fn a_counter_that_goes_backwards_without_moving_the_epoch_is_a_finding() {
1611        let f = netdev(
1612            &Rewinds {
1613                honest: false,
1614                reads: AtomicU64::new(0),
1615            },
1616            3,
1617            || async {},
1618        )
1619        .await;
1620        assert_eq!(checks(&f), ["counters-never-decrease"]);
1621        assert!(
1622            f[0].detail.contains("in_octets went from 1000 to 10"),
1623            "{f:?}"
1624        );
1625
1626        let f = netdev(
1627            &Rewinds {
1628                honest: true,
1629                reads: AtomicU64::new(0),
1630            },
1631            3,
1632            || async {},
1633        )
1634        .await;
1635        assert!(f.is_empty(), "{f:?}");
1636    }
1637}