use std::io::Write;
#[cfg(feature = "async")]
use async_trait::async_trait;
use rscni_types::{
error::Error,
types::{CNI_COMMAND, CNIResult, Cmd, ErrorResult},
version::{PluginInfo, SpecVersion},
};
use crate::{
args::Args,
util::{Env, Io, OsEnv, StdIo, result_json},
};
#[cfg_attr(feature = "async", async_trait)]
pub trait Cni {
async fn add(&self, args: Args) -> Result<CNIResult, Error>;
async fn del(&self, args: Args) -> Result<(), Error>;
async fn check(&self, args: Args) -> Result<(), Error>;
async fn status(&self, args: Args) -> Result<(), Error>;
async fn gc(&self, args: Args) -> Result<(), Error>;
}
#[derive(Debug, Default)]
pub struct Plugin {
info: PluginInfo,
msg: Option<String>,
}
impl Plugin {
#[must_use]
pub const fn new(ver: SpecVersion, versions: Vec<SpecVersion>) -> Self {
Self {
info: PluginInfo::new(ver, versions),
msg: None,
}
}
#[must_use]
pub fn msg(mut self, msg: &str) -> Self {
self.msg = Some(msg.to_string());
self
}
#[allow(clippy::future_not_send)]
pub async fn run<T: Cni>(&self, cni: &T) -> Result<(), Error> {
self.run_with::<T, OsEnv, StdIo>(cni).await
}
fn version_json(&self) -> Result<String, Error> {
serde_json::to_string(&self.info).map_err(|e| Error::FailedToDecode(e.to_string()))
}
fn print_about<I: Io>(&self) -> Result<(), Error> {
let msg = self
.msg
.as_deref()
.ok_or_else(|| Error::missing_env(&[CNI_COMMAND]))?;
let help = format!(
"{msg}\nCNI protocol versions supported: {}\n",
self.info
.supported_versions()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
);
let _ = I::io_err().write_all(help.as_bytes());
Ok(())
}
#[allow(clippy::future_not_send)]
async fn run_with<C: Cni, E: Env, I: Io>(&self, cni: &C) -> Result<(), Error> {
match self.inner_run::<C, E, I>(cni).await {
Ok(res) => {
let mut out = I::io_out();
out.write_all(res.as_bytes())
.and_then(|()| out.flush())
.map_err(|e| Error::IOFailure(e.to_string()))
}
Err(err) => {
let error_result = ErrorResult::new(self.info.cni_version(), &err);
let mut out = I::io_out();
if serde_json::to_writer(&mut out, &error_result).is_err() || out.flush().is_err() {
let _ = I::io_err().write_all(b"Error writing error JSON to stdout\n");
}
Err(err)
}
}
}
#[allow(clippy::future_not_send)]
async fn inner_run<C: Cni, E: Env, I: Io>(&self, cni: &C) -> Result<String, Error> {
let Some(raw_cmd) = E::get::<String>(CNI_COMMAND)? else {
self.print_about::<I>()?;
return Ok(String::new());
};
let cmd: Cmd = raw_cmd.parse()?;
match cmd {
Cmd::Add => {
let args = Args::from_env::<E, I>(cmd)?;
let cni_version = self.info.negotiate(args.config(), cmd)?;
if !cni_version.is_supported() {
return Err(Error::IncompatibleVersion(format!(
"unsupported CNI result version \"{cni_version}\""
)));
}
let res = cni.add(args).await?;
result_json(cni_version, res)
}
Cmd::Del => {
let args = Args::from_env::<E, I>(cmd)?;
self.info.negotiate(args.config(), cmd)?;
cni.del(args).await?;
Ok(String::new())
}
Cmd::Check => {
let args = Args::from_env::<E, I>(cmd)?;
self.info.negotiate(args.config(), cmd)?;
cni.check(args).await?;
Ok(String::new())
}
Cmd::Status => {
let args = Args::from_env::<E, I>(cmd)?;
self.info.negotiate(args.config(), cmd)?;
cni.status(args).await?;
Ok(String::new())
}
Cmd::Gc => {
let args = Args::from_env::<E, I>(cmd)?;
self.info.negotiate(args.config(), cmd)?;
cni.gc(args).await?;
Ok(String::new())
}
Cmd::Version => self.version_json(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{Dns, Interface, IpConfig, Route};
use rscni_types::ipnet::{IpNet, Ipv4Net};
use rstest::rstest;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::io::{Cursor, Read, Write};
use std::net::{IpAddr, Ipv4Addr};
use std::str::FromStr;
thread_local! {
static MOCK_ENV: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
}
struct MockEnv;
impl Env for MockEnv {
fn get<T>(name: &str) -> Result<Option<T>, Error>
where
T: FromStr,
T::Err: std::error::Error + 'static,
{
MOCK_ENV.with(|env| match env.borrow().get(name) {
None => Ok(None),
Some(v) if v.is_empty() => Ok(None),
Some(v) => v
.parse::<T>()
.map(Some)
.map_err(|e| Error::InvalidEnvValue(e.to_string())),
})
}
}
thread_local! {
static MOCK_INPUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
static MOCK_OUTPUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
static MOCK_OUTPUT_BROKEN: Cell<bool> = const { Cell::new(false) };
}
struct MockIo;
struct MockOut;
impl Write for MockOut {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if MOCK_OUTPUT_BROKEN.with(Cell::get) {
return Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"mock stdout is broken",
));
}
MOCK_OUTPUT.with(|out| out.borrow_mut().extend_from_slice(buf));
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn break_mock_output() {
MOCK_OUTPUT_BROKEN.with(|broken| broken.set(true));
}
impl Io for MockIo {
fn io_in() -> impl Read {
MOCK_INPUT.with(|input| {
let data = input.borrow().clone();
Cursor::new(data)
})
}
fn io_out() -> impl Write {
MockOut
}
fn io_err() -> impl Write {
Vec::new()
}
}
fn take_mock_output() -> String {
MOCK_OUTPUT.with(|out| String::from_utf8_lossy(&out.borrow_mut().split_off(0)).into_owned())
}
fn set_mock_env(key: &str, value: &str) {
MOCK_ENV.with(|env| {
env.borrow_mut().insert(key.to_string(), value.to_string());
});
}
fn set_mock_input(data: &str) {
MOCK_INPUT.with(|input| {
*input.borrow_mut() = data.as_bytes().to_vec();
});
}
const ADDRESS: IpNet = IpNet::V4(Ipv4Net::new_assert(Ipv4Addr::new(10, 1, 0, 5), 16));
const DEFAULT_ROUTE: IpNet = IpNet::V4(Ipv4Net::new_assert(Ipv4Addr::UNSPECIFIED, 0));
const GATEWAY: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 1, 0, 1));
struct MockCni;
#[cfg_attr(feature = "async", async_trait)]
impl Cni for MockCni {
async fn add(&self, _args: Args) -> Result<CNIResult, Error> {
Ok(CNIResult {
interfaces: vec![Interface {
name: "eth0".to_string(),
mac: "00:11:22:33:44:55".to_string(),
sandbox: Some("/var/run/netns/test".to_string()),
mtu: None,
socket_path: None,
pci_id: None,
}],
ips: vec![IpConfig {
interface: Some(0),
address: ADDRESS,
gateway: Some(GATEWAY),
}],
routes: vec![Route {
dst: DEFAULT_ROUTE,
gw: Some(GATEWAY),
mtu: None,
advmss: None,
priority: None,
table: None,
scope: None,
}],
dns: Some(Dns {
nameservers: vec!["10.1.0.1".to_string()],
domain: None,
search: None,
options: None,
}),
})
}
async fn del(&self, _args: Args) -> Result<(), Error> {
Ok(())
}
async fn check(&self, _args: Args) -> Result<(), Error> {
Ok(())
}
async fn status(&self, _args: Args) -> Result<(), Error> {
Ok(())
}
async fn gc(&self, _args: Args) -> Result<(), Error> {
Ok(())
}
}
#[cfg(feature = "async")]
#[rstest]
#[case::del("DEL", "1.1.0")]
#[case::check_at_floor("CHECK", "0.4.0")]
#[case::check_above_floor("CHECK", "1.1.0")]
#[case::gc_at_floor("GC", "1.1.0")]
#[case::status_at_floor("STATUS", "1.1.0")]
#[tokio::test]
async fn test_plugin_inner_run_accepted(
#[case] command: &str,
#[case] config_version: &str,
) -> Result<(), Box<dyn std::error::Error>> {
set_dispatch_env(command, "test-container", "/var/run/netns/test", "eth0");
set_mock_env("CNI_PATH", "/opt/cni/bin");
set_mock_config_version(config_version);
let output = Plugin::default()
.inner_run::<MockCni, MockEnv, MockIo>(&MockCni)
.await
.map_err(|e| format!("{command} must succeed: {e}"))?;
assert!(output.is_empty(), "{command} got: {output}");
Ok(())
}
#[cfg(feature = "async")]
#[rstest]
#[case("1.0.0", None)]
#[case("0.4.0", Some("4"))]
#[tokio::test]
async fn test_plugin_inner_run_add_echoes_cni_version(
#[case] version: &str,
#[case] legacy_ip_family: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
set_dispatch_env("ADD", "test-container", "/var/run/netns/test", "eth0");
set_mock_config_version(version);
let plugin = Plugin::default();
let output = plugin
.inner_run::<MockCni, MockEnv, MockIo>(&MockCni)
.await?;
let parsed: serde_json::Value = serde_json::from_str(&output)?;
assert_eq!(parsed["cniVersion"], version);
assert_eq!(parsed["interfaces"][0]["name"], "eth0");
assert_eq!(
parsed["ips"][0].get("version").and_then(|v| v.as_str()),
legacy_ip_family
);
Ok(())
}
#[cfg(feature = "async")]
#[tokio::test]
async fn test_plugin_inner_run_version() -> Result<(), Box<dyn std::error::Error>> {
set_dispatch_env("VERSION", "", "", "");
let plugin = Plugin::default();
let mock_cni = MockCni;
let json_output = plugin
.inner_run::<MockCni, MockEnv, MockIo>(&mock_cni)
.await?;
assert!(json_output.contains("cniVersion"));
assert!(json_output.contains("supportedVersions"));
Ok(())
}
#[cfg(feature = "async")]
#[tokio::test]
async fn test_plugin_inner_run_unset_prints_help() -> Result<(), Error> {
set_dispatch_env("", "", "", "");
let plugin = Plugin::default().msg("Test Plugin v1.0.0");
let out = plugin
.inner_run::<MockCni, MockEnv, MockIo>(&MockCni)
.await?;
assert!(out.is_empty());
Ok(())
}
#[cfg(feature = "async")]
#[tokio::test]
async fn test_plugin_inner_run_unset_without_about_text_is_code_4() {
set_dispatch_env("", "", "", "");
let result = Plugin::default()
.inner_run::<MockCni, MockEnv, MockIo>(&MockCni)
.await;
assert!(
matches!(result, Err(Error::InvalidEnvValue(_))),
"got: {result:?}"
);
}
fn set_dispatch_env(command: &str, container_id: &str, netns: &str, ifname: &str) {
MOCK_ENV.with(|env| env.borrow_mut().clear());
MOCK_OUTPUT.with(|out| out.borrow_mut().clear());
MOCK_OUTPUT_BROKEN.with(|broken| broken.set(false));
let vars = [
("CNI_COMMAND", command),
("CNI_CONTAINERID", container_id),
("CNI_NETNS", netns),
("CNI_IFNAME", ifname),
];
for (key, value) in vars {
if !value.is_empty() {
set_mock_env(key, value);
}
}
set_mock_config_version("1.1.0");
}
fn set_mock_config_version(version: &str) {
set_mock_input(&format!(
r#"{{"cniVersion":"{version}","name":"test-network","type":"test"}}"#
));
}
#[cfg(feature = "async")]
async fn dispatch_with_env(
command: &str,
container_id: &str,
netns: &str,
ifname: &str,
) -> Result<String, Error> {
set_dispatch_env(command, container_id, netns, ifname);
Plugin::default()
.inner_run::<MockCni, MockEnv, MockIo>(&MockCni)
.await
}
#[cfg(feature = "async")]
#[rstest]
#[case::add_without_netns("ADD", "c1", "", "eth0", "CNI_NETNS")]
#[case::add_without_container_id("ADD", "", "/ns", "eth0", "CNI_CONTAINERID")]
#[case::del_without_container_id("DEL", "", "", "eth0", "CNI_CONTAINERID")]
#[case::del_without_ifname("DEL", "c1", "", "", "CNI_IFNAME")]
#[case::gc_without_path("GC", "", "", "", "CNI_PATH")]
#[case::add_bare("ADD", "", "", "", "[CNI_CONTAINERID,CNI_NETNS,CNI_IFNAME]")]
#[case::check_bare("CHECK", "", "", "", "[CNI_CONTAINERID,CNI_NETNS,CNI_IFNAME]")]
#[case::invalid_container_id(
"ADD",
"bad*id",
"/ns",
"eth0",
"invalid characters in containerID"
)]
#[case::invalid_ifname(
"ADD",
"c1",
"/ns",
"eth0:0",
"interface name contains / or : or whitespace"
)]
#[tokio::test]
async fn test_plugin_inner_run_env_matrix_rejected(
#[case] command: &str,
#[case] container_id: &str,
#[case] netns: &str,
#[case] ifname: &str,
#[case] missing: &str,
) {
match dispatch_with_env(command, container_id, netns, ifname).await {
Err(Error::InvalidEnvValue(details)) => assert!(
details.contains(missing),
"{command}: details must name {missing}, got: {details}"
),
other => panic!("{command} must fail naming {missing}, got: {other:?}"),
}
}
#[cfg(feature = "async")]
#[rstest]
#[case::success_puts_the_result("c1", false, 0, r#""interfaces""#)]
#[case::failure_puts_the_error_result("", false, 4, r#""code":4"#)]
#[case::broken_stdout_keeps_the_plugin_error("", true, 4, "")]
#[case::broken_stdout_fails_a_success("c1", true, 5, "")]
#[tokio::test]
async fn test_plugin_run_writes_stdout(
#[case] container_id: &str,
#[case] broken_stdout: bool,
#[case] code: u32,
#[case] expected: &str,
) {
set_dispatch_env("ADD", container_id, "/ns", "eth0");
if broken_stdout {
break_mock_output();
}
let result = Plugin::default()
.run_with::<MockCni, MockEnv, MockIo>(&MockCni)
.await;
let got = result.as_ref().map_or_else(u32::from, |()| 0);
assert_eq!(got, code, "got: {result:?}");
let stdout = take_mock_output();
if expected.is_empty() {
assert!(stdout.is_empty(), "stdout: {stdout}");
} else {
assert!(stdout.contains(expected), "stdout: {stdout}");
}
}
#[cfg(feature = "async")]
#[rstest]
#[case::add_required_only("ADD", "c1", "/ns", "eth0")]
#[case::del_without_netns("DEL", "c1", "", "eth0")]
#[case::status_bare("STATUS", "", "", "")]
#[tokio::test]
async fn test_plugin_inner_run_env_matrix_accepted(
#[case] command: &str,
#[case] container_id: &str,
#[case] netns: &str,
#[case] ifname: &str,
) -> Result<(), Error> {
dispatch_with_env(command, container_id, netns, ifname).await?;
Ok(())
}
#[cfg(feature = "async")]
#[rstest]
#[case::null_config("null", 7)]
#[case::malformed_version(
r#"{"cniVersion":"not-a-version","name":"test-network","type":"test"}"#,
6
)]
#[case::missing_network_name(r#"{"cniVersion":"1.1.0","type":"test"}"#, 7)]
#[case::invalid_network_name(r#"{"cniVersion":"1.1.0","name":"bad*name","type":"test"}"#, 7)]
#[case::non_boolean_capability(
r#"{"cniVersion":"1.1.0","name":"test-network","type":"test","capabilities":{"portMappings":"true"}}"#,
6
)]
#[tokio::test]
async fn test_plugin_inner_run_broken_stdin_rejected(#[case] stdin: &str, #[case] code: u32) {
set_dispatch_env("ADD", "test-container", "/var/run/netns/test", "eth0");
set_mock_input(stdin);
let Err(err) = Plugin::default()
.inner_run::<MockCni, MockEnv, MockIo>(&MockCni)
.await
else {
panic!("ADD must reject this stdin");
};
assert_eq!(u32::from(&err), code, "got: {err:?}");
}
#[cfg(feature = "async")]
#[rstest]
#[case::check_below_floor(
Plugin::default(),
"CHECK",
"0.3.1",
"config version does not allow CHECK"
)]
#[case::gc_below_floor(Plugin::default(), "GC", "1.0.0", "config version does not allow GC")]
#[case::status_below_floor(
Plugin::default(),
"STATUS",
"1.0.0",
"config version does not allow STATUS"
)]
#[case::add_unsupported_version(
Plugin::new(SpecVersion::new(1, 0, 0), vec![SpecVersion::new(1, 0, 0)]),
"ADD",
"0.4.0",
r#"config is "0.4.0""#
)]
#[case::del_unsupported_version(
Plugin::new(SpecVersion::new(1, 0, 0), vec![SpecVersion::new(1, 0, 0)]),
"DEL",
"0.4.0",
r#"config is "0.4.0""#
)]
#[tokio::test]
async fn test_plugin_inner_run_version_rejected(
#[case] plugin: Plugin,
#[case] command: &str,
#[case] config_version: &str,
#[case] expected_details: &str,
) {
set_dispatch_env(command, "test-container", "/var/run/netns/test", "eth0");
set_mock_env("CNI_PATH", "/opt/cni/bin");
set_mock_config_version(config_version);
match plugin.inner_run::<MockCni, MockEnv, MockIo>(&MockCni).await {
Err(Error::IncompatibleVersion(details)) => {
assert!(details.contains(expected_details), "got: {details}");
}
other => panic!("expected IncompatibleVersion, got {other:?}"),
}
}
#[cfg(feature = "async")]
#[rstest]
#[case::rejected_without_010_support(Plugin::default(), "plugin supports")]
#[case::layout_unsupported_despite_010_support(
Plugin::new(
SpecVersion::new(1, 1, 0),
vec![SpecVersion::new(0, 1, 0), SpecVersion::new(1, 1, 0)]
),
"unsupported CNI result version \"0.1.0\""
)]
#[tokio::test]
async fn test_plugin_inner_run_missing_cni_version(
#[case] plugin: Plugin,
#[case] details_contain: &str,
) {
set_dispatch_env("ADD", "test-container", "/var/run/netns/test", "eth0");
set_mock_input(r#"{"name":"test-network","type":"test"}"#);
let result = plugin.inner_run::<MockCni, MockEnv, MockIo>(&MockCni).await;
match result {
Err(Error::IncompatibleVersion(details)) => {
assert!(details.contains(details_contain), "got: {details}");
}
other => panic!("expected IncompatibleVersion, got {other:?}"),
}
}
}