#![cfg(feature = "security")]
#[path = "../examples/hello_world/greeting.rs"]
mod greeting;
use std::time::{Duration, Instant};
use greeting::Greeting;
use rustorb_dds::{
DataReaderQos, DomainParticipant, Error, History, ParticipantConfig, SecurityConfig,
};
const WAIT: Duration = Duration::from_secs(10);
const CERTS: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../rustorb-dds-security/tests/certs/"
);
fn security(who: &str) -> SecurityConfig {
let f = |n: &str| format!("file:{CERTS}{n}");
SecurityConfig {
identity_ca: f("identity_ca.pem"),
identity_certificate: f(&format!("{who}_cert.pem")),
private_key: f(&format!("{who}_key.pem")),
permissions_ca: f("permissions_ca.pem"),
governance: f("governance.p7s"),
permissions: f(&format!("permissions_{who}.p7s")),
password: None,
crl: None,
ocsp: None,
logging: None,
}
}
fn participant(domain: u32, who: Option<&str>) -> rustorb_dds::Result<DomainParticipant> {
let mut c = ParticipantConfig::localhost(domain);
c.announce_period = Duration::from_millis(200);
c.shared_memory = false;
c.security = who.map(security);
DomainParticipant::with_config(c)
}
fn keep_all() -> DataReaderQos {
DataReaderQos {
history: History::KeepAll,
..DataReaderQos::default()
}
}
fn wait_until(mut f: impl FnMut() -> bool) -> bool {
let end = Instant::now() + WAIT;
while Instant::now() < end {
if f() {
return true;
}
std::thread::sleep(Duration::from_millis(20));
}
false
}
#[test]
fn protected_topic() {
let p1 = participant(81, Some("p1")).unwrap();
let p2 = participant(81, Some("p2")).unwrap();
let topic1 = p1.create_topic::<Greeting>("Square").unwrap();
let topic2 = p2.create_topic::<Greeting>("Square").unwrap();
let writer = p1
.create_publisher()
.unwrap()
.create_datawriter(&topic1)
.unwrap();
let reader = p2
.create_subscriber()
.unwrap()
.create_datareader_with_qos(&topic2, keep_all())
.unwrap();
assert!(
wait_until(|| !writer.matched_subscriptions().is_empty()),
"not matched"
);
let mut got = Vec::new();
let mut i = 0;
let ok = wait_until(|| {
i += 1;
writer
.write(&Greeting {
index: i,
message: format!("secret {i}"),
})
.unwrap();
got.extend(reader.take().into_iter().filter_map(|s| s.data));
got.len() >= 3
});
assert!(ok, "no samples");
assert!(got[0].message.starts_with("secret "));
}
#[test]
fn permissions_are_enforced() {
let p1 = participant(82, Some("p1")).unwrap();
let circle = p1.create_topic::<Greeting>("Circle").unwrap();
assert!(
p1.create_publisher()
.unwrap()
.create_datawriter(&circle)
.is_ok()
);
match participant(231, Some("p1")) {
Err(Error::Security(_)) => {}
other => panic!("joined: {:?}", other.map(|_| ())),
}
}
#[test]
fn unauthenticated_participants_are_ignored() {
let p1 = participant(83, Some("p1")).unwrap();
let p0 = participant(83, None).unwrap();
let t1 = p1.create_topic::<Greeting>("Circle").unwrap();
let t0 = p0.create_topic::<Greeting>("Circle").unwrap();
let writer = p1
.create_publisher()
.unwrap()
.create_datawriter(&t1)
.unwrap();
let _reader = p0
.create_subscriber()
.unwrap()
.create_datareader(&t0)
.unwrap();
std::thread::sleep(Duration::from_secs(2));
assert!(writer.matched_subscriptions().is_empty());
}
#[test]
fn deletion_goes_on_the_secure_participant_topic() {
let p1 = participant(84, Some("p1")).unwrap();
let p2 = participant(84, Some("p2")).unwrap();
let t1 = p1.create_topic::<Greeting>("Circle").unwrap();
let t2 = p2.create_topic::<Greeting>("Circle").unwrap();
let writer = p1
.create_publisher()
.unwrap()
.create_datawriter(&t1)
.unwrap();
let _reader = p2
.create_subscriber()
.unwrap()
.create_datareader(&t2)
.unwrap();
assert!(
wait_until(|| !writer.matched_subscriptions().is_empty()),
"not matched"
);
std::thread::sleep(Duration::from_millis(500));
assert_eq!(p2.discovered_participants().len(), 1);
let start = Instant::now();
drop(p1);
assert!(
wait_until(|| p2.discovered_participants().is_empty()),
"p1 still known"
);
assert!(start.elapsed() < Duration::from_secs(3));
}
fn pair(p1: &DomainParticipant, p2: &DomainParticipant) -> bool {
let t1 = p1.create_topic::<Greeting>("Circle").unwrap();
let t2 = p2.create_topic::<Greeting>("Circle").unwrap();
let writer = p1
.create_publisher()
.unwrap()
.create_datawriter(&t1)
.unwrap();
let _reader = p2
.create_subscriber()
.unwrap()
.create_datareader(&t2)
.unwrap();
wait_until(|| !writer.matched_subscriptions().is_empty())
}
fn participant_with(
domain: u32,
security: SecurityConfig,
) -> rustorb_dds::Result<DomainParticipant> {
let mut c = ParticipantConfig::localhost(domain);
c.announce_period = Duration::from_millis(200);
c.shared_memory = false;
c.security = Some(security);
DomainParticipant::with_config(c)
}
#[test]
fn encrypted_private_keys() {
let mut s1 = security("p1");
s1.private_key = format!("file:{CERTS}p1_key_pkcs8_enc.pem");
s1.password = Some("OpenSesame".into());
let mut s2 = security("p2");
s2.private_key = format!("file:{CERTS}p2_key_dek.pem?password=OpenSesame");
let p1 = participant_with(36, s1.clone()).unwrap();
let p2 = participant_with(36, s2).unwrap();
assert!(pair(&p1, &p2), "not matched");
s1.password = Some("wrong".into());
match participant_with(36, s1) {
Err(Error::Security(e)) => assert!(e.contains("does not decrypt"), "{e}"),
other => panic!("created: {:?}", other.map(|_| ())),
}
}
#[test]
fn revoked_certificates_fail_authentication() {
let crl = format!("file:{CERTS}crl_p2.pem");
let mut s1 = security("p1");
s1.crl = Some(crl.clone());
let p1 = participant_with(37, s1).unwrap();
let p2 = participant(37, Some("p2")).unwrap();
assert!(!pair(&p1, &p2), "a revoked participant matched");
let mut s2 = security("p2");
s2.crl = Some(crl);
match participant_with(37, s2) {
Err(Error::Security(e)) => assert!(e.contains("revoked"), "{e}"),
other => panic!("created: {:?}", other.map(|_| ())),
}
}
#[test]
fn password_and_crl_properties() {
let mut c = ParticipantConfig::new(0);
let s = security("p1");
let props = [
("dds.sec.auth.identity_ca", s.identity_ca.as_str()),
(
"dds.sec.auth.identity_certificate",
s.identity_certificate.as_str(),
),
("dds.sec.auth.private_key", s.private_key.as_str()),
("dds.sec.auth.password", "OpenSesame"),
("rustorb.dds.sec.auth.crl", "file:crl.pem"),
("dds.sec.access.permissions_ca", s.permissions_ca.as_str()),
("dds.sec.access.governance", s.governance.as_str()),
("dds.sec.access.permissions", s.permissions.as_str()),
];
c.set_properties(props).unwrap();
let got = c.security.unwrap();
assert_eq!(got.password.as_deref(), Some("OpenSesame"));
assert_eq!(got.crl.as_deref(), Some("file:crl.pem"));
assert_eq!(got.ocsp, None);
let with = |extra: &[(&'static str, &'static str)]| {
let mut p: Vec<(&str, &str)> = props.to_vec();
p.extend_from_slice(extra);
rustorb_dds::SecurityConfig::try_from_properties(p).map(|s| s.ocsp)
};
let o = with(&[
("rustorb.dds.sec.auth.ocsp", "http://ocsp.example:8080/"),
("rustorb.dds.sec.auth.ocsp_timeout", "7"),
("rustorb.dds.sec.auth.ocsp_refresh", "0"),
])
.unwrap()
.unwrap();
assert_eq!(o.responder.as_deref(), Some("http://ocsp.example:8080/"));
assert_eq!(o.timeout, Duration::from_secs(7));
assert_eq!(o.refresh, Duration::ZERO);
let o = with(&[("rustorb.dds.sec.auth.ocsp", "aia")])
.unwrap()
.unwrap();
assert_eq!(o.responder, None);
assert_eq!(o.refresh, Duration::from_secs(300));
assert!(with(&[("rustorb.dds.sec.auth.ocsp", "https://x/")]).is_err());
assert!(
with(&[
("rustorb.dds.sec.auth.ocsp", "aia"),
("rustorb.dds.sec.auth.ocsp_refresh", "soon"),
])
.is_err()
);
}
#[test]
fn security_events_are_logged() {
use rustorb_dds::security_log::{BuiltinLoggingTypeV2, LOG_TOPIC, LogOptions, LoggingLevel};
let file = std::env::temp_dir().join(format!("rustorb-dds-seclog-{}.log", std::process::id()));
let _ = std::fs::remove_file(&file);
let mut s1 = security("p1");
s1.logging = Some(LogOptions {
log_level: LoggingLevel::InformationalLevel,
log_file: Some(file.clone()),
distribute: true,
});
let p1 = participant_with(38, s1).unwrap();
let p2 = participant(38, Some("p2")).unwrap();
let reader = p2
.create_subscriber()
.unwrap()
.create_datareader_with_qos(
&p2.create_topic::<BuiltinLoggingTypeV2>(LOG_TOPIC).unwrap(),
DataReaderQos {
reliability: rustorb_dds::Reliability::reliable(),
..keep_all()
},
)
.unwrap();
let topic = p1.create_topic::<BuiltinLoggingTypeV2>(LOG_TOPIC).unwrap();
let sub = p1.create_subscriber().unwrap();
let mut got = None;
assert!(
wait_until(|| {
match sub.create_datareader(&topic) {
Err(Error::Security(_)) => {}
other => panic!("created: {:?}", other.map(|_| ())),
}
got = reader
.take()
.into_iter()
.filter_map(|s| s.data)
.find(|m| m.msgid == "AccessControl.check_create_datareader");
got.is_some()
}),
"no log message came"
);
let m = got.unwrap();
assert_eq!(m.facility, 10);
assert_eq!(m.severity, LoggingLevel::ErrorLevel);
assert!(
m.message.contains("subscribe to DDS:Security:LogTopicV2"),
"{}",
m.message
);
let dds = &m.structured_data[0];
assert_eq!(dds.key, "DDS");
let g = p1.guid().to_bytes();
let hex: String = g.iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(dds.value[0].value.replace('.', ""), hex);
assert_eq!(dds.value[1].value, "38");
let text = std::fs::read_to_string(&file).unwrap();
assert!(
text.contains("INFORMATIONAL_LEVEL Authentication.validate_local_identity"),
"{text}"
);
assert!(text.contains("authenticated as"), "{text}");
assert!(
text.contains("ERROR_LEVEL AccessControl.check_create_datareader"),
"{text}"
);
drop(p1);
let _ = std::fs::remove_file(&file);
}
#[test]
fn logging_properties() {
use rustorb_dds::security_log::{LogOptions, LoggingLevel};
let s = security("p1");
let mut props = vec![
("dds.sec.auth.identity_ca", s.identity_ca.clone()),
(
"dds.sec.auth.identity_certificate",
s.identity_certificate.clone(),
),
("dds.sec.auth.private_key", s.private_key.clone()),
("dds.sec.access.permissions_ca", s.permissions_ca.clone()),
("dds.sec.access.governance", s.governance.clone()),
("dds.sec.access.permissions", s.permissions.clone()),
(LogOptions::LOGGING_LEVEL, "NOTICE_LEVEL".into()),
(LogOptions::DISTRIBUTE, "true".into()),
];
let mut c = ParticipantConfig::new(0);
c.set_properties(props.iter().map(|(n, v)| (*n, v.as_str())))
.unwrap();
let l = c.security.clone().unwrap().logging.unwrap();
assert_eq!(l.log_level, LoggingLevel::NoticeLevel);
assert!(l.distribute);
assert_eq!(l.log_file, None);
props.push((LogOptions::DISTRIBUTE, "sometimes".into()));
let e = c
.set_properties(props.iter().map(|(n, v)| (*n, v.as_str())))
.unwrap_err();
assert!(e.to_string().contains("distribute"), "{e}");
}
#[test]
fn data_tags_are_checked_against_the_permissions() {
use rustorb_dds::DataWriterQos;
let secret = vec![("level".to_string(), "secret".to_string())];
let p1 = participant(39, Some("p1")).unwrap();
let p2 = participant(39, Some("p2")).unwrap();
let t1 = p1.create_topic::<Greeting>("SquareTagged").unwrap();
let t2 = p2.create_topic::<Greeting>("SquareTagged").unwrap();
let publisher = p1.create_publisher().unwrap();
match publisher.create_datawriter_with_qos(
&t1,
DataWriterQos {
data_tags: vec![("level".into(), "top".into())],
..DataWriterQos::default()
},
) {
Err(Error::Security(e)) => assert!(e.contains("not allowed to publish"), "{e}"),
other => panic!("created: {:?}", other.map(|_| ())),
}
let square = p1.create_topic::<Greeting>("Square").unwrap();
assert!(
publisher
.create_datawriter_with_qos(
&square,
DataWriterQos {
data_tags: secret.clone(),
..DataWriterQos::default()
},
)
.is_err()
);
let writer = publisher
.create_datawriter_with_qos(
&t1,
DataWriterQos {
data_tags: secret.clone(),
..DataWriterQos::default()
},
)
.unwrap();
let reader = p2
.create_subscriber()
.unwrap()
.create_datareader_with_qos(
&t2,
DataReaderQos {
reliability: rustorb_dds::Reliability::reliable(),
data_tags: secret,
..keep_all()
},
)
.unwrap();
assert!(
wait_until(|| !writer.matched_subscriptions().is_empty()),
"not matched"
);
writer
.write(&Greeting {
index: 1,
message: "tagged".into(),
})
.unwrap();
assert!(wait_until(|| reader
.take()
.iter()
.any(|s| s.data.is_some())));
}
fn take_messages(reader: &rustorb_dds::DataReader<Greeting>, got: &mut Vec<String>) {
got.extend(
reader
.take()
.into_iter()
.filter_map(|s| s.data)
.map(|g| g.message),
);
}
#[test]
fn revoked_identities_and_key_revisions() {
use rustorb_dds::{DataWriterQos, DurabilityKind, Reliability};
let p1 = participant(40, Some("p1")).unwrap();
let p2 = participant(40, Some("p2")).unwrap();
let p3 = participant(40, Some("p3")).unwrap();
let t1 = p1.create_topic::<Greeting>("Square").unwrap();
let writer = p1
.create_publisher()
.unwrap()
.create_datawriter_with_qos(
&t1,
DataWriterQos {
reliability: Reliability::reliable(),
durability: DurabilityKind::TransientLocal,
history: History::KeepAll,
..DataWriterQos::default()
},
)
.unwrap();
let reader_qos = DataReaderQos {
reliability: Reliability::reliable(),
durability: DurabilityKind::TransientLocal,
..keep_all()
};
let t2 = p2.create_topic::<Greeting>("Square").unwrap();
let r2 = p2
.create_subscriber()
.unwrap()
.create_datareader_with_qos(&t2, reader_qos.clone())
.unwrap();
let t3 = p3.create_topic::<Greeting>("Square").unwrap();
let r3 = p3
.create_subscriber()
.unwrap()
.create_datareader_with_qos(&t3, reader_qos.clone())
.unwrap();
assert!(
wait_until(|| writer.matched_subscriptions().len() == 2),
"not matched"
);
let write = |m: &str| {
writer
.write(&Greeting {
index: 0,
message: m.into(),
})
.unwrap()
};
write("before");
let (mut got2, mut got3) = (Vec::new(), Vec::new());
assert!(wait_until(|| {
take_messages(&r2, &mut got2);
take_messages(&r3, &mut got3);
got2.len() == 1 && got3.len() == 1
}));
assert!(!p1.revoke_participant(p1.guid().prefix).unwrap());
assert!(p1.revoke_participant(p3.guid().prefix).unwrap());
assert!(
wait_until(|| writer.matched_subscriptions().len() == 1),
"the revoked reader is still matched"
);
write("after revocation");
assert!(wait_until(|| {
take_messages(&r2, &mut got2);
got2.len() == 2
}));
assert_eq!(p1.revise_keys().unwrap(), 2);
std::thread::sleep(Duration::from_millis(300));
write("after two revisions");
assert!(wait_until(|| {
take_messages(&r2, &mut got2);
got2.len() == 3
}));
assert_eq!(got2, ["before", "after revocation", "after two revisions"]);
let p4 = participant(40, Some("p2")).unwrap();
let t4 = p4.create_topic::<Greeting>("Square").unwrap();
let late = p4
.create_subscriber()
.unwrap()
.create_datareader_with_qos(&t4, reader_qos)
.unwrap();
let mut got_late = Vec::new();
assert!(
wait_until(|| {
take_messages(&late, &mut got_late);
got_late.len() == 3
}),
"late joiner got {got_late:?}"
);
std::thread::sleep(Duration::from_secs(1));
take_messages(&r3, &mut got3);
assert_eq!(got3, ["before"]);
assert_eq!(writer.matched_subscriptions().len(), 2);
}
type Answers = std::sync::Arc<std::sync::Mutex<Vec<(Vec<u8>, Vec<u8>)>>>;
struct Responder {
url: String,
answers: Answers,
}
impl Responder {
fn new() -> Self {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let r = Responder {
url: format!("http://{}/", listener.local_addr().unwrap()),
answers: Default::default(),
};
let answers = r.answers.clone();
std::thread::spawn(move || {
for s in listener.incoming() {
let Ok(mut s) = s else { continue };
let mut req = Vec::new();
let mut buf = [0u8; 4096];
while let Ok(n) = s.read(&mut buf) {
req.extend_from_slice(&buf[..n]);
if n == 0
|| req
.windows(4)
.position(|w| w == b"\r\n\r\n")
.is_some_and(|e| {
let head = String::from_utf8_lossy(&req[..e]).to_lowercase();
let len: usize = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
req.len() >= e + 4 + len
})
{
break;
}
}
let found = answers
.lock()
.unwrap()
.iter()
.find(|(serial, _): &&(Vec<u8>, Vec<u8>)| {
req.windows(serial.len()).any(|w| w == serial.as_slice())
})
.map(|(_, a)| a.clone());
let _ = match found {
Some(a) => s
.write_all(
format!("HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n", a.len())
.as_bytes(),
)
.and_then(|_| s.write_all(&a)),
None => s.write_all(b"HTTP/1.0 404 Not Found\r\n\r\n"),
};
}
});
r
}
fn answer(&self, who: &str, f: &str) {
let c = std::fs::read(format!("{CERTS}{who}_cert.pem")).unwrap();
let serial = rustorb_dds_security::pki::Cert::parse(&c)
.unwrap()
.issuer_and_serial()
.1;
let a = std::fs::read(format!("{CERTS}{f}")).unwrap();
let mut all = self.answers.lock().unwrap();
all.retain(|(s, _)| *s != serial);
all.push((serial, a));
}
}
#[test]
fn ocsp_statuses_are_checked_and_refreshed() {
use rustorb_dds::OcspOptions;
let r = Responder::new();
r.answer("p1", "ocsp_p1_good.der");
r.answer("p2", "ocsp_p2_good_delegated.der");
r.answer("p3", "ocsp_p3_good.der");
let with_ocsp = |who: &str| {
let mut s = security(who);
s.ocsp = Some(OcspOptions {
responder: Some(r.url.clone()),
timeout: Duration::from_secs(5),
refresh: Duration::from_millis(500),
});
participant_with(41, s)
};
let p1 = with_ocsp("p1").unwrap();
let p2 = with_ocsp("p2").unwrap();
let p3 = with_ocsp("p3").unwrap();
let t1 = p1.create_topic::<Greeting>("Square").unwrap();
let writer = p1
.create_publisher()
.unwrap()
.create_datawriter(&t1)
.unwrap();
let _readers: Vec<_> = [&p2, &p3]
.iter()
.map(|p| {
let t = p.create_topic::<Greeting>("Square").unwrap();
p.create_subscriber()
.unwrap()
.create_datareader_with_qos(&t, keep_all())
.unwrap()
})
.collect();
assert!(
wait_until(|| writer.matched_subscriptions().len() == 2),
"not matched"
);
r.answer("p3", "ocsp_p3_revoked.der");
match with_ocsp("p3") {
Err(Error::Security(e)) => assert!(e.contains("revoked"), "{e}"),
other => panic!("started: {:?}", other.map(|_| ())),
}
assert!(
wait_until(|| writer.matched_subscriptions().len() == 1
&& writer.matched_subscriptions()[0].prefix == p2.guid().prefix),
"the revoked participant is still matched: {:?}",
writer.matched_subscriptions()
);
let mut s = security("p1");
s.ocsp = Some(OcspOptions {
responder: Some("http://127.0.0.1:9/".into()),
timeout: Duration::from_millis(500),
refresh: Duration::ZERO,
});
assert!(participant_with(41, s).is_err());
}