use std::collections::BTreeSet;
use std::fmt;
use std::future::Future;
use std::pin::{Pin, pin};
use std::sync::{Arc, Mutex};
use std::task::Poll;
use crate::action::{ActionError, ActionOutcome, ActionSpec, Actions, CostModel};
use crate::config::{
ConfigError, ConfigValue, Configure, Effective, ParamClass, ParamKind, ParamSpec, Schema,
};
use crate::{
Capabilities, Counter, Device, DeviceError, DeviceEvent, Duplex, Edge, EndpointId, Guarantee,
Identity, LaneKey, Medium, Metrics, Netdev, NetdevStats, OperStatus, Report, Scope, Sdu,
SecurityProperties,
};
pub mod layer;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Failure {
pub check: &'static str,
pub detail: String,
}
impl Failure {
fn new(check: &'static str, detail: impl Into<String>) -> Self {
Self {
check,
detail: detail.into(),
}
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.check, self.detail)
}
}
pub fn assert_clean(what: &str, failures: &[Failure]) {
assert!(
failures.is_empty(),
"{what} fails {} conformance check(s):\n{}",
failures.len(),
failures
.iter()
.map(|f| format!(" - {f}"))
.collect::<Vec<_>>()
.join("\n")
);
}
pub const DEVICE_METHODS: [&str; 9] = [
"report",
"oper",
"identity",
"next_event",
"close",
"configuration",
"actions",
"security",
"counters",
];
pub const MEDIUM_METHODS: [&str; 14] = [
"report",
"oper",
"identity",
"next_event",
"close",
"configuration",
"actions",
"security",
"counters",
"capabilities",
"send",
"recv",
"metrics",
"configure_lanes",
];
pub const NETDEV_METHODS: [&str; 13] = [
"report",
"oper",
"identity",
"next_event",
"close",
"configuration",
"actions",
"security",
"counters",
"interface",
"statistics",
"epoch",
"destinations",
];
struct Recording {
config: RecordedConfig,
actions: RecordedActions,
seen: Mutex<BTreeSet<&'static str>>,
}
impl Recording {
fn new() -> Self {
Self {
config: RecordedConfig,
actions: RecordedActions,
seen: Mutex::new(BTreeSet::new()),
}
}
fn mark(&self, method: &'static str) {
self.seen.lock().expect("not poisoned").insert(method);
}
fn seen(&self) -> BTreeSet<&'static str> {
self.seen.lock().expect("not poisoned").clone()
}
fn caps() -> Capabilities {
Capabilities::new(218, 217, Duplex::Half, false)
}
fn security() -> SecurityProperties {
SecurityProperties::new("recorded", Scope::Hop).guarantee(Guarantee::Integrity)
}
fn counters() -> Vec<Counter> {
vec![Counter::new("recorded", "calls_total", 3)]
}
fn report() -> Report {
Report::new().age_ms(17).retransmits(5)
}
fn oper() -> OperStatus {
OperStatus::down("recorded", true)
}
fn identity() -> Identity {
Identity::unknown().model_name("recorded")
}
fn lane() -> LaneKey {
LaneKey {
endpoint: EndpointId::new("b"),
reliable: false,
rank: 0,
}
}
fn stats() -> NetdevStats {
NetdevStats::new().in_octets(4242)
}
}
struct RecordedConfig;
#[async_trait::async_trait]
impl Configure for RecordedConfig {
fn schema(&self) -> Schema {
Schema::new()
}
fn effective(&self) -> Effective {
Effective::default()
}
}
struct RecordedActions;
#[async_trait::async_trait]
impl Actions for RecordedActions {
fn specs(&self) -> Vec<ActionSpec> {
vec![ActionSpec::new("recorded", "", CostModel::Free)]
}
async fn invoke(
&self,
_name: &str,
_arguments: &std::collections::BTreeMap<String, ConfigValue>,
) -> Result<ActionOutcome, ActionError> {
Ok(ActionOutcome::new("recorded"))
}
}
#[async_trait::async_trait]
impl Device for Recording {
fn report(&self) -> Report {
self.mark("report");
Self::report()
}
fn oper(&self) -> OperStatus {
self.mark("oper");
Self::oper()
}
fn identity(&self) -> Identity {
self.mark("identity");
Self::identity()
}
fn configuration(&self) -> Option<&dyn Configure> {
self.mark("configuration");
Some(&self.config)
}
fn actions(&self) -> Option<&dyn Actions> {
self.mark("actions");
Some(&self.actions)
}
async fn close(&self) -> Result<(), DeviceError> {
self.mark("close");
Ok(())
}
async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
self.mark("next_event");
Ok(DeviceEvent::raised("recorded"))
}
fn security(&self) -> Option<SecurityProperties> {
self.mark("security");
Some(Self::security())
}
fn counters(&self) -> Vec<Counter> {
self.mark("counters");
Self::counters()
}
}
#[async_trait::async_trait]
impl Medium for Recording {
fn capabilities(&self) -> Capabilities {
self.mark("capabilities");
Self::caps()
}
async fn send(&self, _lane: &LaneKey, _sdu: &[u8]) -> Result<(), DeviceError> {
self.mark("send");
Ok(())
}
async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError> {
self.mark("recv");
Ok((Self::lane(), vec![0xAB]))
}
fn metrics(&self) -> Metrics {
self.mark("metrics");
Metrics::new().tx_sdus(7)
}
async fn configure_lanes(&self, _lanes: &[LaneKey]) -> Result<(), DeviceError> {
self.mark("configure_lanes");
Ok(())
}
}
impl Netdev for Recording {
fn interface(&self) -> &'static str {
self.mark("interface");
"recorded0"
}
fn statistics(&self) -> NetdevStats {
self.mark("statistics");
Self::stats()
}
fn epoch(&self) -> u64 {
self.mark("epoch");
42
}
fn destinations(&self) -> Option<Vec<crate::Destination>> {
self.mark("destinations");
Some(vec![crate::Destination::new("recorded-neighbour")])
}
}
async fn device_calls(name: &str, dev: &dyn Device, out: &mut Vec<Failure>) {
let report = dev.report();
let oper = dev.oper();
let identity = dev.identity();
let configuration = dev.configuration().is_some();
let actions = dev.actions().is_some();
let event = dev.next_event().await;
if report != Recording::report() {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote report: {report:?}"),
));
}
if oper != Recording::oper() {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote oper: {oper:?}"),
));
}
if identity != Recording::identity() {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote identity: {identity:?}"),
));
}
if !configuration {
out.push(Failure::new(
"decorator-forwards",
format!("{name} answers None for configuration: the wrapped device has a plane"),
));
}
if !actions {
out.push(Failure::new(
"decorator-forwards",
format!("{name} answers None for actions: the wrapped device offers one"),
));
}
if event.as_ref().ok() != Some(&DeviceEvent::raised("recorded")) {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote next_event: {event:?}"),
));
}
let security = dev.security();
if security.as_ref() != Some(&Recording::security()) {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote security: {security:?}"),
));
}
let counters = dev.counters();
if counters != Recording::counters() {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote counters: {counters:?}"),
));
}
}
fn missing(name: &str, methods: &[&'static str], inner: &Recording, out: &mut Vec<Failure>) {
let seen = inner.seen();
let missing: Vec<&str> = methods
.iter()
.copied()
.filter(|m| !seen.contains(m))
.collect();
if !missing.is_empty() {
out.push(Failure::new(
"decorator-forwards",
format!(
"{name} does not forward {missing:?}, so it answers for itself rather than for \
the device it wraps"
),
));
}
}
pub async fn device_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
where
F: FnOnce(Arc<dyn Device>) -> Arc<dyn Device>,
{
let inner = Arc::new(Recording::new());
let dev = wrap(inner.clone() as Arc<dyn Device>);
let mut out = Vec::new();
device_calls(name, dev.as_ref(), &mut out).await;
if let Err(e) = dev.close().await {
out.push(Failure::new(
"decorator-forwards",
format!("{name} failed close: {e}"),
));
}
missing(name, &DEVICE_METHODS, &inner, &mut out);
out
}
pub async fn medium_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
where
F: FnOnce(Arc<dyn Medium>) -> Arc<dyn Medium>,
{
let inner = Arc::new(Recording::new());
let medium = wrap(inner.clone() as Arc<dyn Medium>);
let mut out = Vec::new();
device_calls(name, medium.as_ref(), &mut out).await;
let caps = medium.capabilities();
if caps != Recording::caps() {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote capabilities: {caps:?}"),
));
}
if let Err(e) = medium.send(&Recording::lane(), b"payload").await {
out.push(Failure::new(
"decorator-forwards",
format!("{name} failed send: {e}"),
));
}
match medium.recv().await {
Ok((_, sdu)) if sdu == vec![0xAB] => {}
other => out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote recv: {other:?}"),
)),
}
let metrics = medium.metrics();
if metrics.tx_sdus != 7 {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote metrics: {metrics:?}"),
));
}
if let Err(e) = medium.configure_lanes(&[Recording::lane()]).await {
out.push(Failure::new(
"decorator-forwards",
format!("{name} failed configure_lanes: {e}"),
));
}
if let Err(e) = medium.close().await {
out.push(Failure::new(
"decorator-forwards",
format!("{name} failed close: {e}"),
));
}
missing(name, &MEDIUM_METHODS, &inner, &mut out);
out
}
pub async fn netdev_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
where
F: FnOnce(Arc<dyn Netdev>) -> Arc<dyn Netdev>,
{
let inner = Arc::new(Recording::new());
let dev = wrap(inner.clone() as Arc<dyn Netdev>);
let mut out = Vec::new();
device_calls(name, dev.as_ref(), &mut out).await;
if dev.interface() != "recorded0" {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote interface: {:?}", dev.interface()),
));
}
if dev.statistics() != Recording::stats() {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote statistics: {:?}", dev.statistics()),
));
}
if dev.epoch() != 42 {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote epoch: {}", dev.epoch()),
));
}
if dev.destinations() != Some(vec![crate::Destination::new("recorded-neighbour")]) {
out.push(Failure::new(
"decorator-forwards",
format!("{name} rewrote destinations: {:?}", dev.destinations()),
));
}
if let Err(e) = dev.close().await {
out.push(Failure::new(
"decorator-forwards",
format!("{name} failed close: {e}"),
));
}
missing(name, &NETDEV_METHODS, &inner, &mut out);
out
}
#[must_use]
pub fn core(dev: &dyn Device) -> Vec<Failure> {
let mut out = Vec::new();
let ageless = |mut r: Report| {
r.age_ms = None;
r
};
let (a, b) = (dev.report(), dev.report());
if ageless(a) != ageless(b) {
out.push(Failure::new(
"report-is-cached",
format!("two calls in a row disagree: {a:?} then {b:?}"),
));
}
if ageless(a) != Report::default() && a.age_ms.is_none() {
out.push(Failure::new(
"report-says-its-age",
format!("the report carries a reading and no age_ms: {a:?}"),
));
}
let (a, b) = (dev.oper(), dev.oper());
if a != b {
out.push(Failure::new(
"oper-is-cached",
format!("two calls in a row disagree: {a:?} then {b:?}"),
));
}
let (a, b) = (dev.identity(), dev.identity());
if a != b {
out.push(Failure::new(
"identity-is-cached",
format!("two calls in a row disagree: {a:?} then {b:?}"),
));
}
out
}
async fn until<T>(
fut: impl Future<Output = T>,
mut deadline: Pin<&mut impl Future<Output = ()>>,
) -> Option<T> {
let mut fut = pin!(fut);
std::future::poll_fn(|cx| {
if let Poll::Ready(v) = fut.as_mut().poll(cx) {
return Poll::Ready(Some(v));
}
match deadline.as_mut().poll(cx) {
Poll::Ready(()) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
})
.await
}
pub async fn events_are_edge_triggered(
dev: &dyn Device,
deadline: impl Future<Output = ()>,
) -> Vec<Failure> {
let mut deadline = pin!(deadline);
let mut out = Vec::new();
let mut last: Vec<(Option<LaneKey>, DeviceEvent)> = Vec::new();
while let Some(Ok(ev)) = until(dev.next_event(), deadline.as_mut()).await {
if let Some((_, prev)) = last.iter().find(|(lane, _)| *lane == ev.lane)
&& prev.edge == ev.edge
&& prev.detail == ev.detail
{
out.push(Failure::new(
"events-are-edge-triggered",
format!(
"{:?} {:?} was reported twice in a row with no {:?} between: a condition \
is one event when it starts and one when it stops",
ev.edge,
ev.detail,
match ev.edge {
Edge::Raised => Edge::Cleared,
_ => Edge::Raised,
}
),
));
}
last.retain(|(lane, _)| *lane != ev.lane);
last.push((ev.lane.clone(), ev));
}
out
}
fn plain_chunk(s: &str) -> bool {
!s.is_empty()
&& s.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
}
#[must_use]
pub fn schema_is_valid(schema: &Schema) -> Vec<Failure> {
let mut out = Vec::new();
let mut groups = BTreeSet::new();
for g in &schema.groups {
if !plain_chunk(g.name) {
out.push(Failure::new(
"schema-is-valid",
format!(
"group {:?} is not a plain chunk (lowercase, digits, `_`, `-`): it is \
spelled in the write key",
g.name
),
));
}
if !groups.insert(g.name) {
out.push(Failure::new(
"schema-is-valid",
format!("group {:?} is declared twice", g.name),
));
}
if g.description.trim().is_empty() {
out.push(Failure::new(
"schema-is-valid",
format!("group {:?} has no description", g.name),
));
}
if g.parameters.is_empty() {
out.push(Failure::new(
"schema-is-valid",
format!("group {:?} declares no parameter", g.name),
));
}
let mut names = BTreeSet::new();
for p in &g.parameters {
if !plain_chunk(p.name) {
out.push(Failure::new(
"schema-is-valid",
format!("{}/{:?} is not a plain chunk", g.name, p.name),
));
}
if !names.insert(p.name) {
out.push(Failure::new(
"schema-is-valid",
format!("{}/{} is declared twice", g.name, p.name),
));
}
if p.description.trim().is_empty() {
out.push(Failure::new(
"schema-is-valid",
format!("{}/{} has no description", g.name, p.name),
));
}
if let ParamKind::Integer {
min: Some(min),
max: Some(max),
..
} = p.kind
&& min > max
{
out.push(Failure::new(
"schema-is-valid",
format!("{}/{}: min {min} is above max {max}", g.name, p.name),
));
}
}
}
out
}
#[must_use]
pub fn effective_within_schema(schema: &Schema, effective: &Effective) -> Vec<Failure> {
let mut out = Vec::new();
for (group, params) in effective {
for (name, value) in params {
if let Err(e) = schema.check(group, name, value) {
out.push(Failure::new(
"effective-within-schema",
format!("effective carries {group}/{name} = {value}: {e}"),
));
}
}
}
out.extend(sensitive_absent(schema, effective));
out
}
fn sensitive_absent(schema: &Schema, effective: &Effective) -> Vec<Failure> {
let mut out = Vec::new();
for g in &schema.groups {
for p in g.parameters.iter().filter(|p| p.sensitive) {
if effective
.get(g.name)
.is_some_and(|values| values.contains_key(p.name))
{
out.push(Failure::new(
"sensitive-never-read-back",
format!(
"{}/{} is sensitive and effective carries a value for it",
g.name, p.name
),
));
}
}
}
out
}
fn other_value(spec: &ParamSpec, current: Option<&ConfigValue>) -> ConfigValue {
match (&spec.kind, current) {
(ParamKind::Bool, Some(ConfigValue::Bool(b))) => ConfigValue::Bool(!b),
(ParamKind::Bool, _) => ConfigValue::Bool(true),
(ParamKind::Integer { min, max, .. }, cur) => {
let cur = match cur {
Some(ConfigValue::Integer(i)) => *i,
_ => min.unwrap_or(0),
};
let up = cur.saturating_add(1);
if max.is_none_or(|m| up <= m) {
ConfigValue::Integer(up)
} else {
ConfigValue::Integer(cur.saturating_sub(1).max(min.unwrap_or(i64::MIN)))
}
}
(ParamKind::Text, Some(ConfigValue::Text(t))) => {
ConfigValue::Text(format!("{t}-conformance"))
}
(_, _) => ConfigValue::Text("conformance".into()),
}
}
pub async fn contract_refused(cfg: &dyn Configure) -> Vec<Failure> {
let mut out = Vec::new();
let schema = cfg.schema();
let effective = cfg.effective();
for g in schema
.groups
.iter()
.filter(|g| g.class == ParamClass::Contract)
{
let Some(p) = g.parameters.first() else {
continue;
};
let current = effective.get(g.name).and_then(|v| v.get(p.name));
let value = other_value(p, current);
let change = [(p.name.to_string(), value.clone())].into_iter().collect();
match cfg.apply(g.name, &change).await {
Err(ConfigError::Contract(_)) => {}
Ok(_) => out.push(Failure::new(
"contract-refused",
format!(
"contract group {:?} accepted {}={} at runtime; it is part of what the \
transport was started against and belongs in the startup file",
g.name, p.name, value
),
)),
Err(e) => out.push(Failure::new(
"contract-refused",
format!(
"contract group {:?} was refused for another reason than the contract, so \
the caller is not told to restart: {e}",
g.name
),
)),
}
}
out
}
pub async fn read_back_and_undo(cfg: &dyn Configure) -> Vec<Failure> {
let mut out = Vec::new();
let schema = cfg.schema();
for g in schema
.groups
.iter()
.filter(|g| g.class != ParamClass::Contract)
{
for p in g.parameters.iter().filter(|p| !p.sensitive) {
let before = cfg.effective();
let current = before.get(g.name).and_then(|v| v.get(p.name));
let value = other_value(p, current);
let change = [(p.name.to_string(), value.clone())].into_iter().collect();
let undo = match cfg.apply(g.name, &change).await {
Ok(undo) => undo,
Err(ConfigError::Unsupported(_)) => break,
Err(e) => {
out.push(Failure::new(
"read-back",
format!(
"the schema says {}/{} accepts {value}; the device refused it: {e}",
g.name, p.name
),
));
continue;
}
};
let after = cfg.effective();
let read_back = after.get(g.name).and_then(|v| v.get(p.name));
if read_back != Some(&value) {
out.push(Failure::new(
"read-back",
format!(
"after apply {}/{}={value}, effective says {}: a change is not done \
until it can be read back",
g.name,
p.name,
read_back.map_or("nothing".to_string(), ToString::to_string)
),
));
}
if let Err(e) = cfg.apply(g.name, &undo).await {
out.push(Failure::new(
"undo-restores",
format!("the undo for {}/{} was refused: {e}", g.name, p.name),
));
continue;
}
let restored = cfg.effective();
if restored != before {
out.push(Failure::new(
"undo-restores",
format!(
"after apply {}/{}={value} and its undo {undo:?}, effective is not what \
it was: {restored:?} vs {before:?}",
g.name, p.name
),
));
}
}
}
out
}
pub async fn sensitive_never_read_back(dev: &dyn Device) -> Vec<Failure> {
let Some(cfg) = dev.configuration() else {
return Vec::new();
};
let schema = cfg.schema();
let mut out = sensitive_absent(&schema, &cfg.effective());
let marker = format!(
"conformance-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos())
);
for g in schema
.groups
.iter()
.filter(|g| g.class != ParamClass::Contract)
{
for p in g
.parameters
.iter()
.filter(|p| p.sensitive && p.kind == ParamKind::Text)
{
let change = [(p.name.to_string(), ConfigValue::Text(marker.clone()))]
.into_iter()
.collect();
let undo = match cfg.apply(g.name, &change).await {
Ok(undo) => undo,
Err(ConfigError::Unsupported(_)) => break,
Err(e) => {
out.push(Failure::new(
"sensitive-never-read-back",
format!(
"the schema says {}/{} takes text; the device refused it: {e}",
g.name, p.name
),
));
continue;
}
};
let effective = cfg.effective();
let leaks = [
("effective", format!("{effective:?}")),
("the schema", format!("{:?}", cfg.schema())),
("the report", format!("{:?}", dev.report())),
("oper", format!("{:?}", dev.oper())),
("the identity", format!("{:?}", dev.identity())),
];
for (what, text) in leaks {
if text.contains(&marker) {
out.push(Failure::new(
"sensitive-never-read-back",
format!(
"the value written to sensitive {}/{} appears in {what}: {text}",
g.name, p.name
),
));
}
}
if !undo.is_empty()
&& let Err(e) = cfg.apply(g.name, &undo).await
{
out.push(Failure::new(
"sensitive-never-read-back",
format!("the undo for {}/{} was refused: {e}", g.name, p.name),
));
}
}
}
out
}
pub async fn configuration(dev: &dyn Device) -> Vec<Failure> {
let Some(cfg) = dev.configuration() else {
return Vec::new();
};
let schema = cfg.schema();
let mut out = schema_is_valid(&schema);
out.extend(effective_within_schema(&schema, &cfg.effective()));
out.extend(contract_refused(cfg).await);
out.extend(read_back_and_undo(cfg).await);
out.extend(sensitive_never_read_back(dev).await);
out
}
type StatRead = fn(&NetdevStats) -> Option<u64>;
const COUNTERS: [(&str, StatRead); 9] = [
("in_octets", |s| s.in_octets),
("out_octets", |s| s.out_octets),
("in_errors", |s| s.in_errors),
("out_errors", |s| s.out_errors),
("in_discards", |s| s.in_discards),
("out_discards", |s| s.out_discards),
("in_multicast_pkts", |s| s.in_multicast_pkts),
("in_pkts", |s| s.in_pkts),
("out_pkts", |s| s.out_pkts),
];
pub async fn netdev<Fut>(
dev: &dyn Netdev,
samples: usize,
mut tick: impl FnMut() -> Fut,
) -> Vec<Failure>
where
Fut: Future<Output = ()>,
{
let mut out = Vec::new();
if dev.interface().trim().is_empty() {
out.push(Failure::new(
"netdev-is-named",
"interface() is empty: a netdev is named as the kernel spells it",
));
}
let mut prev = (dev.epoch(), dev.statistics());
for _ in 0..samples {
tick().await;
let now = (dev.epoch(), dev.statistics());
if now.0 == prev.0 {
for (name, read) in COUNTERS {
if let (Some(a), Some(b)) = (read(&prev.1), read(&now.1))
&& b < a
{
out.push(Failure::new(
"counters-never-decrease",
format!(
"{name} went from {a} to {b} within epoch {}: a counter that resets \
moves the epoch",
now.0
),
));
}
}
}
prev = now;
}
out
}
pub async fn device(dev: &dyn Device, event_deadline: impl Future<Output = ()>) -> Vec<Failure> {
let mut out = core(dev);
out.extend(events_are_edge_triggered(dev, event_deadline).await);
out.extend(configuration(dev).await);
out
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use super::*;
use crate::config::{ConfigGroup, Undo};
fn checks(failures: &[Failure]) -> Vec<&'static str> {
failures.iter().map(|f| f.check).collect()
}
fn detail(failures: &[Failure], check: &str) -> String {
failures
.iter()
.filter(|f| f.check == check)
.map(|f| f.detail.clone())
.collect::<Vec<_>>()
.join("\n")
}
struct ForgetsOper(Arc<dyn Device>);
#[async_trait::async_trait]
impl Device for ForgetsOper {
fn report(&self) -> Report {
self.0.report()
}
fn identity(&self) -> Identity {
self.0.identity()
}
fn configuration(&self) -> Option<&dyn Configure> {
self.0.configuration()
}
fn actions(&self) -> Option<&dyn Actions> {
self.0.actions()
}
async fn close(&self) -> Result<(), DeviceError> {
self.0.close().await
}
async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
self.0.next_event().await
}
fn security(&self) -> Option<SecurityProperties> {
self.0.security()
}
fn counters(&self) -> Vec<Counter> {
self.0.counters()
}
}
struct ForgetsMetrics(Arc<dyn Medium>);
#[async_trait::async_trait]
impl Device for ForgetsMetrics {
fn report(&self) -> Report {
self.0.report()
}
fn oper(&self) -> OperStatus {
self.0.oper()
}
fn identity(&self) -> Identity {
self.0.identity()
}
fn configuration(&self) -> Option<&dyn Configure> {
self.0.configuration()
}
fn actions(&self) -> Option<&dyn Actions> {
self.0.actions()
}
async fn close(&self) -> Result<(), DeviceError> {
self.0.close().await
}
async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
self.0.next_event().await
}
fn security(&self) -> Option<SecurityProperties> {
self.0.security()
}
fn counters(&self) -> Vec<Counter> {
self.0.counters()
}
}
#[async_trait::async_trait]
impl Medium for ForgetsMetrics {
fn capabilities(&self) -> Capabilities {
self.0.capabilities()
}
async fn send(&self, lane: &LaneKey, sdu: &[u8]) -> Result<(), DeviceError> {
self.0.send(lane, sdu).await
}
async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError> {
self.0.recv().await
}
fn metrics(&self) -> Metrics {
Metrics::default()
}
async fn configure_lanes(&self, lanes: &[LaneKey]) -> Result<(), DeviceError> {
self.0.configure_lanes(lanes).await
}
}
struct ForgetsEpoch(Arc<dyn Netdev>);
#[async_trait::async_trait]
impl Device for ForgetsEpoch {
fn report(&self) -> Report {
self.0.report()
}
fn oper(&self) -> OperStatus {
self.0.oper()
}
fn identity(&self) -> Identity {
self.0.identity()
}
fn configuration(&self) -> Option<&dyn Configure> {
self.0.configuration()
}
fn actions(&self) -> Option<&dyn Actions> {
self.0.actions()
}
async fn close(&self) -> Result<(), DeviceError> {
self.0.close().await
}
async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
self.0.next_event().await
}
fn security(&self) -> Option<SecurityProperties> {
self.0.security()
}
fn counters(&self) -> Vec<Counter> {
self.0.counters()
}
}
impl Netdev for ForgetsEpoch {
fn interface(&self) -> &str {
self.0.interface()
}
fn statistics(&self) -> NetdevStats {
self.0.statistics()
}
fn destinations(&self) -> Option<Vec<crate::Destination>> {
self.0.destinations()
}
}
#[tokio::test]
async fn a_decorator_that_forgets_a_method_is_named_with_the_method() {
let f =
device_decorator_forwards("ForgetsOper", |inner| Arc::new(ForgetsOper(inner))).await;
assert_eq!(checks(&f), ["decorator-forwards", "decorator-forwards"]);
let d = detail(&f, "decorator-forwards");
assert!(
d.contains("rewrote oper") && d.contains("[\"oper\"]"),
"{d}"
);
let f =
medium_decorator_forwards("ForgetsMetrics", |inner| Arc::new(ForgetsMetrics(inner)))
.await;
assert!(
detail(&f, "decorator-forwards").contains("[\"metrics\"]"),
"{f:?}"
);
let f =
netdev_decorator_forwards("ForgetsEpoch", |inner| Arc::new(ForgetsEpoch(inner))).await;
assert!(
detail(&f, "decorator-forwards").contains("[\"epoch\"]"),
"{f:?}"
);
assert!(
device_decorator_forwards("id", |inner| inner)
.await
.is_empty()
);
assert!(
medium_decorator_forwards("id", |inner| inner)
.await
.is_empty()
);
assert!(
netdev_decorator_forwards("id", |inner| inner)
.await
.is_empty()
);
}
struct Flickers(AtomicU64);
impl Device for Flickers {
fn oper(&self) -> OperStatus {
if self.0.fetch_add(1, Ordering::Relaxed).is_multiple_of(2) {
OperStatus::up()
} else {
OperStatus::unknown()
}
}
}
struct Ageless;
impl Device for Ageless {
fn report(&self) -> Report {
Report::new().rssi(-70_000)
}
}
#[test]
fn a_status_that_changes_between_two_calls_and_a_reading_without_an_age_are_findings() {
assert_eq!(
checks(&core(&Flickers(AtomicU64::new(0)))),
["oper-is-cached"]
);
assert_eq!(checks(&core(&Ageless)), ["report-says-its-age"]);
assert!(core(&Recording::new()).is_empty());
}
struct Repeats {
script: Vec<DeviceEvent>,
at: AtomicU64,
}
#[async_trait::async_trait]
impl Device for Repeats {
async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
#[allow(clippy::cast_possible_truncation)]
let i = self.at.fetch_add(1, Ordering::Relaxed) as usize;
match self.script.get(i) {
Some(ev) => Ok(ev.clone()),
None => std::future::pending().await,
}
}
}
#[tokio::test(start_paused = true)]
async fn a_condition_reported_twice_without_the_opposite_edge_is_a_finding() {
let nags = Repeats {
script: vec![
DeviceEvent::raised("+CME ERROR 3"),
DeviceEvent::raised("+CME ERROR 3"),
DeviceEvent::cleared("+CME ERROR 3"),
],
at: AtomicU64::new(0),
};
let f = events_are_edge_triggered(&nags, tokio::time::sleep(Duration::from_secs(1))).await;
assert_eq!(checks(&f), ["events-are-edge-triggered"]);
assert!(f[0].detail.contains("twice in a row"), "{f:?}");
let edgy = Repeats {
script: vec![
DeviceEvent::raised("no carrier"),
DeviceEvent::cleared("carrier"),
DeviceEvent::raised("no carrier"),
DeviceEvent::raised("registration lost"),
],
at: AtomicU64::new(0),
};
assert!(
events_are_edge_triggered(&edgy, tokio::time::sleep(Duration::from_secs(1)))
.await
.is_empty()
);
}
#[derive(Clone, Copy, Default)]
#[allow(clippy::struct_excessive_bools)] struct Faults {
nods: bool,
forgets_undo: bool,
bends: bool,
leaks: bool,
echoes: bool,
off_schema: bool,
bad_schema: bool,
}
struct Knobs {
faults: Faults,
state: Mutex<BTreeMap<&'static str, ConfigValue>>,
}
impl Knobs {
fn new(faults: Faults) -> Self {
Self {
faults,
state: Mutex::new(
[
("level", ConfigValue::Integer(3)),
("label", ConfigValue::Text("lab".into())),
("pin", ConfigValue::Text("0000".into())),
("baud", ConfigValue::Integer(9600)),
]
.into_iter()
.collect(),
),
}
}
fn get(&self, name: &str) -> ConfigValue {
self.state.lock().expect("not poisoned")[name].clone()
}
}
impl Device for Knobs {
fn identity(&self) -> Identity {
if self.faults.echoes {
Identity::unknown().serial_num(self.get("pin").to_string())
} else {
Identity::unknown()
}
}
fn configuration(&self) -> Option<&dyn Configure> {
Some(self)
}
}
#[async_trait::async_trait]
impl Configure for Knobs {
fn schema(&self) -> Schema {
let mut s = Schema::new()
.with(
ConfigGroup::new("tune", ParamClass::Hot, "tuning")
.with(ParamSpec::new(
"level",
ParamKind::integer(Some(0), Some(10), None),
"a level",
))
.with(ParamSpec::new("label", ParamKind::Text, "a label")),
)
.with(
ConfigGroup::new("auth", ParamClass::Hot, "the PIN")
.with(ParamSpec::new("pin", ParamKind::Text, "the SIM PIN").sensitive()),
)
.with(
ConfigGroup::new("port", ParamClass::Contract, "the port").with(
ParamSpec::new(
"baud",
ParamKind::integer(Some(1200), Some(115_200), Some("bit/s")),
"the rate",
),
),
);
if self.faults.bad_schema {
s = s.with(ConfigGroup::new("tune", ParamClass::Hot, "again").with(
ParamSpec::new("x", ParamKind::integer(Some(10), Some(1), None), "crossed"),
));
}
s
}
fn effective(&self) -> Effective {
let mut tune: BTreeMap<String, ConfigValue> = [
("level".to_string(), self.get("level")),
("label".to_string(), self.get("label")),
]
.into_iter()
.collect();
if self.faults.off_schema {
tune.insert("bogus".into(), ConfigValue::Bool(true));
}
let mut auth = BTreeMap::new();
if self.faults.leaks {
auth.insert("pin".to_string(), self.get("pin"));
}
[
("tune".to_string(), tune),
("auth".to_string(), auth),
(
"port".to_string(),
[("baud".to_string(), self.get("baud"))]
.into_iter()
.collect(),
),
]
.into_iter()
.collect()
}
async fn apply(
&self,
group: &str,
values: &BTreeMap<String, ConfigValue>,
) -> Result<Undo, ConfigError> {
if group == "port" && !self.faults.bends {
return Err(ConfigError::Contract(group.into()));
}
let mut state = self.state.lock().expect("not poisoned");
let mut undo = Undo::new();
for (name, v) in values {
let key: &'static str = match name.as_str() {
"level" => "level",
"label" => "label",
"pin" => "pin",
"baud" => "baud",
other => {
return Err(ConfigError::UnknownParameter {
group: group.into(),
name: other.into(),
});
}
};
if !self.faults.forgets_undo {
undo.insert(name.clone(), state[key].clone());
}
if !self.faults.nods {
state.insert(key, v.clone());
}
}
Ok(undo)
}
}
#[tokio::test]
async fn each_configuration_fault_is_found_and_a_device_without_one_passes() {
assert!(
configuration(&Knobs::new(Faults::default()))
.await
.is_empty()
);
let cases: [(&str, Faults, &str, &str); 7] = [
(
"nods",
Faults {
nods: true,
..Faults::default()
},
"read-back",
"not done until it can be read back",
),
(
"forgets_undo",
Faults {
forgets_undo: true,
..Faults::default()
},
"undo-restores",
"not what it was",
),
(
"bends",
Faults {
bends: true,
..Faults::default()
},
"contract-refused",
"accepted",
),
(
"leaks",
Faults {
leaks: true,
..Faults::default()
},
"sensitive-never-read-back",
"effective",
),
(
"echoes",
Faults {
echoes: true,
..Faults::default()
},
"sensitive-never-read-back",
"the identity",
),
(
"off_schema",
Faults {
off_schema: true,
..Faults::default()
},
"effective-within-schema",
"tune/bogus",
),
(
"bad_schema",
Faults {
bad_schema: true,
..Faults::default()
},
"schema-is-valid",
"declared twice",
),
];
for (name, faults, check, words) in cases {
let f = configuration(&Knobs::new(faults)).await;
let d = detail(&f, check);
assert!(
!d.is_empty() && d.contains(words),
"{name}: expected {check} saying {words:?}; got {f:?}"
);
}
let f = schema_is_valid(
&Knobs::new(Faults {
bad_schema: true,
..Faults::default()
})
.schema(),
);
assert!(
detail(&f, "schema-is-valid").contains("min 10 is above max 1"),
"{f:?}"
);
}
struct Rewinds {
honest: bool,
reads: AtomicU64,
}
impl Device for Rewinds {}
impl Netdev for Rewinds {
fn interface(&self) -> &'static str {
"wwan0"
}
fn statistics(&self) -> NetdevStats {
let n = self.reads.fetch_add(1, Ordering::Relaxed);
NetdevStats::new().in_octets(if n < 2 { 1_000 } else { 10 })
}
fn epoch(&self) -> u64 {
u64::from(self.honest && self.reads.load(Ordering::Relaxed) >= 2)
}
}
#[tokio::test]
async fn a_counter_that_goes_backwards_without_moving_the_epoch_is_a_finding() {
let f = netdev(
&Rewinds {
honest: false,
reads: AtomicU64::new(0),
},
3,
|| async {},
)
.await;
assert_eq!(checks(&f), ["counters-never-decrease"]);
assert!(
f[0].detail.contains("in_octets went from 1000 to 10"),
"{f:?}"
);
let f = netdev(
&Rewinds {
honest: true,
reads: AtomicU64::new(0),
},
3,
|| async {},
)
.await;
assert!(f.is_empty(), "{f:?}");
}
}