Skip to main content

aft_base/
launch_nonce.rs

1//! The launch nonce: the secret the subc daemon gives AFT when it spawns it
2//! as a supervised module (`aft --subc`), which AFT presents on its HELLO and
3//! on the routes it opens as a consumer, so the daemon admits it as itself.
4//!
5//! The daemon hands the nonce over once through an inherited pipe, and while
6//! modules move to the pipe it also keeps an environment copy. Any process of
7//! the same user can read another process's initial environment, and every
8//! child inherits the live one, so AFT reads the nonce exactly once, at the
9//! top of `main` and before it spawns anything, through
10//! [`subc_os::launch_nonce()`] (the one reader that takes the pipe and falls
11//! back to the environment copy only when no pipe is named). It then keeps the
12//! value here for the life of the process and removes both variables from its
13//! own environment, so no child (bash, PTY, language server, formatter, git,
14//! the `gh` shim, a login-shell PATH probe) can inherit either of them.
15//!
16//! A standalone AFT (no `--subc`) never reads the accessor: it has no nonce
17//! and must not consume a descriptor it was not given.
18
19use std::fmt;
20use std::sync::{Mutex, OnceLock};
21
22use subc_protocol::manifest::{build_provenance, LaunchNonceSource, ManifestProvenance};
23
24/// The nonce AFT was launched with and where it was read from. `Debug` never
25/// prints the value.
26#[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    /// `capture_at_startup` has not run: standalone mode, or an in-process
56    /// test that has not installed a nonce.
57    NotCaptured,
58    Captured(Option<ModuleLaunchNonce>),
59    /// The daemon named a descriptor that could not be read. The accessor
60    /// never falls back to the environment copy in that case, and neither
61    /// does AFT: the module runs without identity and the daemon refuses it.
62    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
73/// Read the launch nonce once and remove it from this process's environment.
74///
75/// Call only in `--subc` mode, first thing in `main`: before any thread
76/// starts (removing environment variables is unsound once other threads may
77/// read the environment) and before anything spawns a child (until the read,
78/// the pipe's descriptor is inheritable, and until the removal, so are both
79/// variables). Logging is not up yet, so the outcome is reported later by
80/// [`log_capture_outcome`].
81pub 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
94// Both modes scrub these before starting threads or children. Only startup
95// without an adopted registration channel reads the nonce.
96pub 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
101/// Log where the nonce came from, once logging is initialized.
102pub 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
117/// The nonce captured at startup, if any.
118pub 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
147/// Install the binary's compiled revision before any provenance is requested.
148/// The library deliberately has no compiled Git revision: embedding it would
149/// invalidate its compiler cache for every commit, even with identical source.
150/// Returns false if facts were already declared, including an unknown revision;
151/// startup cannot replace an identity that has already been reported.
152pub 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
159/// The revision the binary was built from, as installed by
160/// [`initialize_binary_build_revision`]; `None` for unstamped builds and for
161/// library code (tests) that never ran the binary's startup.
162pub fn binary_build_revision() -> Option<&'static str> {
163    BUILD_REVISION
164        .get()
165        .and_then(|revision| revision.as_deref())
166}
167
168/// Build facts are declared on every HELLO, even when no launch nonce was
169/// supplied. The protocol helper reports the version of the wire crate actually
170/// linked into AFT; the nonce source remains a separate runtime fact.
171pub 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            // A malformed build revision must not prevent module registration.
185            // The caller caches these build facts, so this warning occurs once.
186            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/// Restores the previously captured nonce when dropped.
195#[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/// Stand in for `capture_at_startup` in tests that drive the subc loop inside
209/// the test process, where `main` never runs. An empty or blank value counts
210/// as no nonce. The installed nonce reports the environment as its source,
211/// because that is where such a test supplies it.
212#[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    /// The captured nonce is process-wide; tests that replace it run one at a time.
232    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    /// Language servers, formatters, git and the ONNX Runtime probe are
315    /// spawned with a plain `Command` that inherits AFT's own environment,
316    /// without the bash child-environment funnel. What keeps the nonce out of
317    /// them is that the startup capture removes both variables from AFT's
318    /// environment, which this checks with such a child.
319    #[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}