1use std::fmt;
20use std::sync::{Mutex, OnceLock};
21
22use subc_protocol::manifest::{build_provenance, LaunchNonceSource, ManifestProvenance};
23
24#[derive(Clone, PartialEq, Eq)]
27pub struct ModuleLaunchNonce {
28 value: String,
29 source: LaunchNonceSource,
30}
31
32impl ModuleLaunchNonce {
33 pub fn value(&self) -> &str {
34 &self.value
35 }
36
37 pub fn source(&self) -> &LaunchNonceSource {
38 &self.source
39 }
40}
41
42impl fmt::Debug for ModuleLaunchNonce {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.debug_struct("ModuleLaunchNonce")
45 .field(
46 "value",
47 &format_args!("<{} bytes redacted>", self.value.len()),
48 )
49 .field("source", &self.source)
50 .finish()
51 }
52}
53
54enum Capture {
55 NotCaptured,
58 Captured(Option<ModuleLaunchNonce>),
59 Failed(String),
63}
64
65static CAPTURED: Mutex<Capture> = Mutex::new(Capture::NotCaptured);
66
67fn slot() -> std::sync::MutexGuard<'static, Capture> {
68 CAPTURED
69 .lock()
70 .unwrap_or_else(std::sync::PoisonError::into_inner)
71}
72
73pub fn capture_at_startup() {
82 let outcome = match subc_os::launch_nonce() {
83 Ok(Some(nonce)) => Capture::Captured(Some(ModuleLaunchNonce {
84 value: nonce.value().to_string(),
85 source: LaunchNonceSource::from_wire_name(nonce.source().as_str()),
86 })),
87 Ok(None) => Capture::Captured(None),
88 Err(error) => Capture::Failed(error.to_string()),
89 };
90 *slot() = outcome;
91 strip_environment();
92}
93
94pub fn strip_environment() {
97 std::env::remove_var(subc_os::launch_nonce::LAUNCH_NONCE_ENV);
98 std::env::remove_var(subc_os::launch_nonce::LAUNCH_NONCE_FD_ENV);
99}
100
101pub fn log_capture_outcome() {
103 match &*slot() {
104 Capture::NotCaptured => {}
105 Capture::Captured(Some(nonce)) => {
106 log::info!("subc launch nonce read from {}", nonce.source().wire_name())
107 }
108 Capture::Captured(None) => {
109 log::info!("subc launch nonce absent: this module was not spawned by the daemon")
110 }
111 Capture::Failed(error) => {
112 log::warn!("subc launch nonce unavailable, connecting without module identity: {error}")
113 }
114 }
115}
116
117pub fn current() -> Option<ModuleLaunchNonce> {
119 match &*slot() {
120 Capture::Captured(nonce) => nonce.clone(),
121 Capture::NotCaptured | Capture::Failed(_) => None,
122 }
123}
124
125pub(crate) fn was_captured() -> bool {
126 matches!(&*slot(), Capture::Captured(Some(_)))
127}
128
129#[derive(Default)]
130struct BuildDeclaration(OnceLock<ManifestProvenance>);
131
132impl BuildDeclaration {
133 fn initialize(&self, revision: Option<&str>) -> bool {
134 if self.0.get().is_some() {
135 return false;
136 }
137 self.0.set(build_facts(revision)).is_ok()
138 }
139
140 fn declared(&self) -> &ManifestProvenance {
141 self.0.get_or_init(|| build_facts(None))
142 }
143}
144
145static BUILD: BuildDeclaration = BuildDeclaration(OnceLock::new());
146
147pub fn initialize_binary_build_revision(revision: Option<&str>) -> bool {
153 let _ = BUILD_REVISION.set(revision.map(str::to_owned));
154 BUILD.initialize(revision)
155}
156
157static BUILD_REVISION: OnceLock<Option<String>> = OnceLock::new();
158
159pub fn binary_build_revision() -> Option<&'static str> {
163 BUILD_REVISION
164 .get()
165 .and_then(|revision| revision.as_deref())
166}
167
168pub fn provenance() -> Option<ManifestProvenance> {
172 let declared = BUILD.declared();
173 Some(
174 declared
175 .clone()
176 .with_launch_nonce_source(current().map(|nonce| nonce.source)),
177 )
178}
179
180fn build_facts(revision: Option<&str>) -> ManifestProvenance {
181 match build_provenance(revision, None, None) {
182 Ok(declared) => declared,
183 Err(error) => {
184 log::warn!("subc build revision refused; declaring provenance without a SHA: {error}");
187 ManifestProvenance::new().with_wire_crate_version(Some(
188 subc_protocol::SUBC_PROTOCOL_CRATE_VERSION.to_string(),
189 ))
190 }
191 }
192}
193
194#[doc(hidden)]
196pub struct InstalledForTests {
197 previous: Option<Capture>,
198}
199
200impl Drop for InstalledForTests {
201 fn drop(&mut self) {
202 if let Some(previous) = self.previous.take() {
203 *slot() = previous;
204 }
205 }
206}
207
208#[doc(hidden)]
213pub fn install_for_tests(nonce: Option<&str>) -> InstalledForTests {
214 let installed =
215 Capture::Captured(nonce.filter(|value| !value.trim().is_empty()).map(|value| {
216 ModuleLaunchNonce {
217 value: value.to_string(),
218 source: LaunchNonceSource::Env,
219 }
220 }));
221 let previous = std::mem::replace(&mut *slot(), installed);
222 InstalledForTests {
223 previous: Some(previous),
224 }
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230
231 fn serial() -> std::sync::MutexGuard<'static, ()> {
233 static SERIAL: Mutex<()> = Mutex::new(());
234 SERIAL
235 .lock()
236 .unwrap_or_else(std::sync::PoisonError::into_inner)
237 }
238
239 #[test]
240 fn debug_never_prints_the_nonce() {
241 let nonce = ModuleLaunchNonce {
242 value: "secret-launch-nonce".to_string(),
243 source: LaunchNonceSource::Fd,
244 };
245 let printed = format!("{nonce:?}");
246 assert!(!printed.contains("secret-launch-nonce"), "{printed}");
247 assert!(printed.contains("19 bytes redacted"), "{printed}");
248 }
249
250 #[test]
251 fn refused_build_revision_preserves_wire_version_without_panicking() {
252 let declared = build_facts(Some("not-a-git-sha"))
253 .with_launch_nonce_source(Some(LaunchNonceSource::Fd));
254 assert_eq!(declared.build_git_sha, None);
255 assert_eq!(declared.wire_crate_version.as_deref(), Some("0.37.4"));
256 assert_eq!(declared.launch_nonce_source, Some(LaunchNonceSource::Fd));
257 }
258
259 #[test]
260 fn provenance_reports_build_facts_with_and_without_a_nonce() {
261 let _serial = serial();
262 let _none = install_for_tests(None);
263 let assert_build_facts = |declared: &ManifestProvenance| {
264 assert_eq!(declared.wire_crate_version.as_deref(), Some("0.37.4"));
265 assert_eq!(
266 declared.build_git_sha, None,
267 "the library has no binary startup revision"
268 );
269 };
270 let declared = provenance().expect("provenance without a nonce");
271 assert_build_facts(&declared);
272 assert_eq!(declared.launch_nonce_source, None);
273 {
274 let _env = install_for_tests(Some("n"));
275 let declared = provenance().expect("provenance with a nonce");
276 assert_build_facts(&declared);
277 assert_eq!(declared.launch_nonce_source, Some(LaunchNonceSource::Env));
278 }
279 assert_eq!(current(), None, "the guard restores the previous capture");
280 }
281
282 #[test]
283 fn binary_build_revision_is_declared_once_without_changing_wire_facts() {
284 let declaration = BuildDeclaration::default();
285 let revision = "a".repeat(40);
286 assert!(declaration.initialize(Some(&revision)));
287 assert_eq!(
288 declaration.declared().build_git_sha.as_deref(),
289 Some(revision.as_str())
290 );
291 assert_eq!(
292 declaration.declared().wire_crate_version.as_deref(),
293 Some("0.37.4")
294 );
295 assert!(!declaration.initialize(Some(&"b".repeat(40))));
296 assert_eq!(
297 declaration.declared().build_git_sha.as_deref(),
298 Some(revision.as_str())
299 );
300 }
301
302 #[test]
303 fn unknown_build_revision_cannot_be_upgraded_after_provenance_is_reported() {
304 let declaration = BuildDeclaration::default();
305 assert_eq!(declaration.declared().build_git_sha, None);
306 assert!(!declaration.initialize(Some(&"a".repeat(40))));
307 assert_eq!(declaration.declared().build_git_sha, None);
308 assert_eq!(
309 declaration.declared().wire_crate_version.as_deref(),
310 Some("0.37.4")
311 );
312 }
313
314 #[test]
320 fn startup_capture_leaves_nothing_for_a_plainly_spawned_child_to_inherit() {
321 let _serial = serial();
322 let _restore = install_for_tests(None);
323 std::env::remove_var(subc_os::launch_nonce::LAUNCH_NONCE_FD_ENV);
324 std::env::set_var(subc_os::launch_nonce::LAUNCH_NONCE_ENV, "unit-test-nonce");
325
326 capture_at_startup();
327
328 assert_eq!(
329 current().as_ref().map(ModuleLaunchNonce::value),
330 Some("unit-test-nonce"),
331 "the nonce is kept in memory"
332 );
333 #[cfg(unix)]
334 let output = std::process::Command::new("sh")
335 .args(["-c", "env"])
336 .output()
337 .expect("spawn sh");
338 #[cfg(windows)]
339 let output = std::process::Command::new("cmd")
340 .args(["/C", "set"])
341 .output()
342 .expect("spawn cmd");
343 let environment = String::from_utf8_lossy(&output.stdout);
344 assert!(output.status.success(), "{environment}");
345 assert!(
346 !environment.contains("SUBC_LAUNCH_NONCE"),
347 "a child inherited a launch nonce variable: {environment}"
348 );
349 }
350}