use std::fmt;
use std::sync::{Mutex, OnceLock};
use subc_protocol::manifest::{build_provenance, LaunchNonceSource, ManifestProvenance};
#[derive(Clone, PartialEq, Eq)]
pub struct ModuleLaunchNonce {
value: String,
source: LaunchNonceSource,
}
impl ModuleLaunchNonce {
pub fn value(&self) -> &str {
&self.value
}
pub fn source(&self) -> &LaunchNonceSource {
&self.source
}
}
impl fmt::Debug for ModuleLaunchNonce {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ModuleLaunchNonce")
.field(
"value",
&format_args!("<{} bytes redacted>", self.value.len()),
)
.field("source", &self.source)
.finish()
}
}
enum Capture {
NotCaptured,
Captured(Option<ModuleLaunchNonce>),
Failed(String),
}
static CAPTURED: Mutex<Capture> = Mutex::new(Capture::NotCaptured);
fn slot() -> std::sync::MutexGuard<'static, Capture> {
CAPTURED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn capture_at_startup() {
let outcome = match subc_os::launch_nonce() {
Ok(Some(nonce)) => Capture::Captured(Some(ModuleLaunchNonce {
value: nonce.value().to_string(),
source: LaunchNonceSource::from_wire_name(nonce.source().as_str()),
})),
Ok(None) => Capture::Captured(None),
Err(error) => Capture::Failed(error.to_string()),
};
*slot() = outcome;
strip_environment();
}
pub fn strip_environment() {
std::env::remove_var(subc_os::launch_nonce::LAUNCH_NONCE_ENV);
std::env::remove_var(subc_os::launch_nonce::LAUNCH_NONCE_FD_ENV);
}
pub fn log_capture_outcome() {
match &*slot() {
Capture::NotCaptured => {}
Capture::Captured(Some(nonce)) => {
log::info!("subc launch nonce read from {}", nonce.source().wire_name())
}
Capture::Captured(None) => {
log::info!("subc launch nonce absent: this module was not spawned by the daemon")
}
Capture::Failed(error) => {
log::warn!("subc launch nonce unavailable, connecting without module identity: {error}")
}
}
}
pub fn current() -> Option<ModuleLaunchNonce> {
match &*slot() {
Capture::Captured(nonce) => nonce.clone(),
Capture::NotCaptured | Capture::Failed(_) => None,
}
}
pub(crate) fn was_captured() -> bool {
matches!(&*slot(), Capture::Captured(Some(_)))
}
#[derive(Default)]
struct BuildDeclaration(OnceLock<ManifestProvenance>);
impl BuildDeclaration {
fn initialize(&self, revision: Option<&str>) -> bool {
if self.0.get().is_some() {
return false;
}
self.0.set(build_facts(revision)).is_ok()
}
fn declared(&self) -> &ManifestProvenance {
self.0.get_or_init(|| build_facts(None))
}
}
static BUILD: BuildDeclaration = BuildDeclaration(OnceLock::new());
pub fn initialize_binary_build_revision(revision: Option<&str>) -> bool {
let _ = BUILD_REVISION.set(revision.map(str::to_owned));
BUILD.initialize(revision)
}
static BUILD_REVISION: OnceLock<Option<String>> = OnceLock::new();
pub fn binary_build_revision() -> Option<&'static str> {
BUILD_REVISION
.get()
.and_then(|revision| revision.as_deref())
}
pub fn provenance() -> Option<ManifestProvenance> {
let declared = BUILD.declared();
Some(
declared
.clone()
.with_launch_nonce_source(current().map(|nonce| nonce.source)),
)
}
fn build_facts(revision: Option<&str>) -> ManifestProvenance {
match build_provenance(revision, None, None) {
Ok(declared) => declared,
Err(error) => {
log::warn!("subc build revision refused; declaring provenance without a SHA: {error}");
ManifestProvenance::new().with_wire_crate_version(Some(
subc_protocol::SUBC_PROTOCOL_CRATE_VERSION.to_string(),
))
}
}
}
#[doc(hidden)]
pub struct InstalledForTests {
previous: Option<Capture>,
}
impl Drop for InstalledForTests {
fn drop(&mut self) {
if let Some(previous) = self.previous.take() {
*slot() = previous;
}
}
}
#[doc(hidden)]
pub fn install_for_tests(nonce: Option<&str>) -> InstalledForTests {
let installed =
Capture::Captured(nonce.filter(|value| !value.trim().is_empty()).map(|value| {
ModuleLaunchNonce {
value: value.to_string(),
source: LaunchNonceSource::Env,
}
}));
let previous = std::mem::replace(&mut *slot(), installed);
InstalledForTests {
previous: Some(previous),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn serial() -> std::sync::MutexGuard<'static, ()> {
static SERIAL: Mutex<()> = Mutex::new(());
SERIAL
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[test]
fn debug_never_prints_the_nonce() {
let nonce = ModuleLaunchNonce {
value: "secret-launch-nonce".to_string(),
source: LaunchNonceSource::Fd,
};
let printed = format!("{nonce:?}");
assert!(!printed.contains("secret-launch-nonce"), "{printed}");
assert!(printed.contains("19 bytes redacted"), "{printed}");
}
#[test]
fn refused_build_revision_preserves_wire_version_without_panicking() {
let declared = build_facts(Some("not-a-git-sha"))
.with_launch_nonce_source(Some(LaunchNonceSource::Fd));
assert_eq!(declared.build_git_sha, None);
assert_eq!(declared.wire_crate_version.as_deref(), Some("0.37.4"));
assert_eq!(declared.launch_nonce_source, Some(LaunchNonceSource::Fd));
}
#[test]
fn provenance_reports_build_facts_with_and_without_a_nonce() {
let _serial = serial();
let _none = install_for_tests(None);
let assert_build_facts = |declared: &ManifestProvenance| {
assert_eq!(declared.wire_crate_version.as_deref(), Some("0.37.4"));
assert_eq!(
declared.build_git_sha, None,
"the library has no binary startup revision"
);
};
let declared = provenance().expect("provenance without a nonce");
assert_build_facts(&declared);
assert_eq!(declared.launch_nonce_source, None);
{
let _env = install_for_tests(Some("n"));
let declared = provenance().expect("provenance with a nonce");
assert_build_facts(&declared);
assert_eq!(declared.launch_nonce_source, Some(LaunchNonceSource::Env));
}
assert_eq!(current(), None, "the guard restores the previous capture");
}
#[test]
fn binary_build_revision_is_declared_once_without_changing_wire_facts() {
let declaration = BuildDeclaration::default();
let revision = "a".repeat(40);
assert!(declaration.initialize(Some(&revision)));
assert_eq!(
declaration.declared().build_git_sha.as_deref(),
Some(revision.as_str())
);
assert_eq!(
declaration.declared().wire_crate_version.as_deref(),
Some("0.37.4")
);
assert!(!declaration.initialize(Some(&"b".repeat(40))));
assert_eq!(
declaration.declared().build_git_sha.as_deref(),
Some(revision.as_str())
);
}
#[test]
fn unknown_build_revision_cannot_be_upgraded_after_provenance_is_reported() {
let declaration = BuildDeclaration::default();
assert_eq!(declaration.declared().build_git_sha, None);
assert!(!declaration.initialize(Some(&"a".repeat(40))));
assert_eq!(declaration.declared().build_git_sha, None);
assert_eq!(
declaration.declared().wire_crate_version.as_deref(),
Some("0.37.4")
);
}
#[test]
fn startup_capture_leaves_nothing_for_a_plainly_spawned_child_to_inherit() {
let _serial = serial();
let _restore = install_for_tests(None);
std::env::remove_var(subc_os::launch_nonce::LAUNCH_NONCE_FD_ENV);
std::env::set_var(subc_os::launch_nonce::LAUNCH_NONCE_ENV, "unit-test-nonce");
capture_at_startup();
assert_eq!(
current().as_ref().map(ModuleLaunchNonce::value),
Some("unit-test-nonce"),
"the nonce is kept in memory"
);
#[cfg(unix)]
let output = std::process::Command::new("sh")
.args(["-c", "env"])
.output()
.expect("spawn sh");
#[cfg(windows)]
let output = std::process::Command::new("cmd")
.args(["/C", "set"])
.output()
.expect("spawn cmd");
let environment = String::from_utf8_lossy(&output.stdout);
assert!(output.status.success(), "{environment}");
assert!(
!environment.contains("SUBC_LAUNCH_NONCE"),
"a child inherited a launch nonce variable: {environment}"
);
}
}