#![cfg(all(feature = "conformance", feature = "internal-auth", feature = "client"))]
use std::time::Duration;
use openadr::conformance::{Credential, Outcome, Runner, Severity, Target};
use testcontainers::{
ContainerAsync, GenericImage, ImageExt,
core::{ExecCommand, IntoContainerPort},
runners::AsyncRunner,
};
use testcontainers_modules::postgres::Postgres;
const PEER_IMAGE_VAR: &str = "OPENADR_PEER_IMAGE";
const JSON_VAR: &str = "OPENADR_INTEROP_JSON";
const POSTGRES_TAG: &str = "17-alpine";
const NETWORK: &str = "oadr-interop";
const PG_HOST: &str = "oadr-interop-pg";
const DB: &str = "openadr";
const SECRET: &str = "interop-secret";
const BL: &str = "interop-bl";
const VEN: &str = "interop-ven";
struct Peer {
image: String,
tag: String,
}
impl Peer {
fn from_env() -> Self {
let image = std::env::var(PEER_IMAGE_VAR)
.unwrap_or_else(|_| "ghcr.io/openleadr/openleadr-rs:latest".to_string());
match image.rsplit_once(':') {
Some((name, tag)) if !tag.contains('/') => Self {
image: name.to_string(),
tag: tag.to_string(),
},
_ => Self {
image,
tag: "latest".to_string(),
},
}
}
fn bootstrap(hash: &str) -> String {
format!(
r#"
INSERT INTO "user" (id, reference, description, created, modified, scopes) VALUES
('{BL}','{BL}','conformance', now(), now(),
ARRAY['read_all','write_programs','write_events','write_subscriptions_bl','write_vens_bl','write_reports']::scope[]),
('{VEN}','{VEN}','conformance', now(), now(),
ARRAY['read_targets','read_ven_objects','write_reports','write_subscriptions_ven','write_vens_ven']::scope[])
ON CONFLICT (id) DO NOTHING;
INSERT INTO user_credentials (user_id, client_id, client_secret) VALUES
('{BL}','{BL}','{hash}'), ('{VEN}','{VEN}','{hash}')
ON CONFLICT (client_id) DO UPDATE SET client_secret = EXCLUDED.client_secret;
"#
)
}
}
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0")
.and_then(|l| l.local_addr())
.map(|a| a.port())
.expect("a free port")
}
async fn wait_until_serving(base: &str) -> bool {
openadr::install_crypto_provider();
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(5))
.build()
.expect("an HTTP client");
for _ in 0..120 {
if client
.get(format!("{base}/auth/server"))
.send()
.await
.is_ok_and(|r| r.status().is_success())
{
return true;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
false
}
async fn start(
peer: &Peer,
) -> Option<(
ContainerAsync<Postgres>,
ContainerAsync<GenericImage>,
String,
)> {
let postgres = Postgres::default()
.with_user(DB)
.with_password(DB)
.with_db_name(DB)
.with_tag(POSTGRES_TAG)
.with_network(NETWORK)
.with_container_name(PG_HOST)
.start()
.await
.inspect_err(|e| eprintln!("skipping interop: no Docker ({e})"))
.ok()?;
let port = free_port();
let vtn = GenericImage::new(&peer.image, &peer.tag)
.with_mapped_port(port, 3000.tcp())
.with_network(NETWORK)
.with_platform("linux/amd64")
.with_env_var(
"DATABASE_URL",
format!("postgres://{DB}:{DB}@{PG_HOST}:5432/{DB}"),
)
.with_env_var(
"OAUTH_TOKEN_URL",
format!("http://localhost:{port}/auth/token"),
)
.with_startup_timeout(Duration::from_secs(300))
.start()
.await
.inspect_err(|e| eprintln!("skipping interop: the peer image would not start ({e})"))
.ok()?;
let base = format!("http://127.0.0.1:{port}");
if !wait_until_serving(&base).await {
eprintln!("the peer never answered GET /auth/server at {base}. Its output:");
for (stream, bytes) in [
("stdout", vtn.stdout_to_vec().await),
("stderr", vtn.stderr_to_vec().await),
] {
let text = String::from_utf8_lossy(&bytes.unwrap_or_default()).to_string();
for line in text.lines().rev().take(20).collect::<Vec<_>>().iter().rev() {
eprintln!(" {stream}: {line}");
}
}
return None;
}
Some((postgres, vtn, base))
}
#[tokio::test]
#[ignore = "a measurement against somebody else's VTN: run with --ignored --nocapture"]
async fn the_suite_runs_against_a_peer() {
let peer = Peer::from_env();
let Some((postgres, _vtn, base)) = start(&peer).await else {
return;
};
let hash = openadr::vtn::auth::InternalAuth::hash_secret(SECRET).expect("a PHC string");
let result = postgres
.exec(ExecCommand::new([
"psql",
"-qtU",
DB,
"-d",
DB,
"-c",
&Peer::bootstrap(&hash),
]))
.await;
assert!(
result.is_ok(),
"the peer's bootstrap failed — its schema has probably changed: {result:?}"
);
let credential = |id: &str| Credential::ClientCredentials {
id: id.to_string(),
secret: SECRET.to_string(),
};
let target = Target::new(&base)
.with_business_logic(credential(BL))
.with_ven(credential(VEN), VEN);
let report = Runner::new(target)
.expect("the base URL parses")
.run()
.await;
println!("\n{report}");
if let Ok(path) = std::env::var(JSON_VAR) {
std::fs::write(&path, serde_json::to_vec_pretty(&report.to_json()).unwrap())
.unwrap_or_else(|e| panic!("could not write {path}: {e}"));
println!("wrote {path}");
}
let (passed, failed, skipped) = report.tally(Severity::Required);
println!("required: {passed} passed, {failed} failed, {skipped} skipped");
let unreachable: Vec<&str> = report
.findings
.iter()
.filter(|f| match &f.outcome {
Outcome::Skipped(why) => why.contains("could not be reached"),
_ => false,
})
.map(|f| f.check.id)
.collect();
assert!(
unreachable.is_empty(),
"{} check(s) never reached {}:{} — that is this harness's fault, not the peer's: {unreachable:?}",
unreachable.len(),
peer.image,
peer.tag
);
assert!(
passed + failed >= 20,
"only {} required checks were attempted — the suite did not run",
passed + failed
);
}