1use crate::TokioProcessRunner;
2use merry_runtime::{
3 ProcessActionIntent, ProcessEnvPolicy, ProcessRunner, ProcessRunnerContext, ProcessRunnerError,
4};
5use std::{
6 ffi::OsString,
7 path::{Component, Path, PathBuf},
8 time::Duration,
9};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct GpgAgentSockets {
17 home: PathBuf,
18 agent: PathBuf,
19 auxiliary: Vec<PathBuf>,
20}
21
22impl GpgAgentSockets {
23 pub fn new(
25 home: impl Into<PathBuf>,
26 agent: impl Into<PathBuf>,
27 ) -> Result<Self, ProcessRunnerError> {
28 let home = home.into();
29 let agent = agent.into();
30 validate(&home)?;
31 validate(&agent)?;
32 Ok(Self {
33 home,
34 agent,
35 auxiliary: Vec::new(),
36 })
37 }
38
39 pub fn with_auxiliary_sockets(
41 mut self,
42 sockets: impl IntoIterator<Item = PathBuf>,
43 ) -> Result<Self, ProcessRunnerError> {
44 for socket in sockets {
45 validate(&socket)?;
46 self.auxiliary.push(socket);
47 }
48 self.auxiliary.sort();
49 self.auxiliary.dedup();
50 Ok(self)
51 }
52
53 #[must_use]
55 pub fn home(&self) -> &Path {
56 &self.home
57 }
58
59 #[must_use]
61 pub fn agent(&self) -> &Path {
62 &self.agent
63 }
64
65 pub fn public_keyrings(&self) -> impl Iterator<Item = PathBuf> + '_ {
69 ["pubring.kbx", "pubring.gpg"]
70 .into_iter()
71 .map(|name| self.home.join(name))
72 }
73
74 pub fn validate_public_key_access(&self) -> Result<(), ProcessRunnerError> {
77 match std::fs::metadata(self.home.join("public-keys.d/pubring.db")) {
78 Ok(_) => Err(ProcessRunnerError::infrastructure(
79 "gpg_agent public-key integration currently supports pubring.kbx and pubring.gpg; a keyboxd database was detected and its host write interface is not automatically authorized",
80 )),
81 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
82 Err(error) => Err(ProcessRunnerError::infrastructure(format!(
83 "cannot inspect GPG public-key storage: {error}"
84 ))),
85 }
86 }
87
88 pub fn paths(&self) -> impl Iterator<Item = &Path> {
90 std::iter::once(self.agent.as_path()).chain(self.auxiliary.iter().map(PathBuf::as_path))
91 }
92
93 pub async fn discover(
99 home: &Path,
100 overrides: &[(OsString, OsString)],
101 ) -> Result<Option<Self>, ProcessRunnerError> {
102 let search_path = overrides
103 .iter()
104 .rev()
105 .find(|(name, _)| name == "PATH")
106 .map(|(_, value)| value.clone())
107 .or_else(|| std::env::var_os("PATH"))
108 .unwrap_or_default();
109 let mut program = None;
110 for directory in std::env::split_paths(&search_path).filter(|path| path.is_absolute()) {
111 let candidate = directory.join("gpgconf");
112 if tokio::fs::metadata(&candidate)
113 .await
114 .is_ok_and(|metadata| metadata.is_file())
115 {
116 program = Some(candidate);
117 break;
118 }
119 }
120 let Some(program) = program else {
121 return Ok(None);
122 };
123 let mut environment = overrides.to_vec();
124 if !environment.iter().any(|(name, _)| name == "HOME") {
125 environment.push((OsString::from("HOME"), home.as_os_str().to_owned()));
126 }
127 let runner = TokioProcessRunner::new().with_environment_overrides(environment)?;
128 let program = program.to_str().ok_or_else(|| {
129 ProcessRunnerError::infrastructure("gpgconf executable path is not UTF-8")
130 })?;
131 let intent = ProcessActionIntent::new(
132 vec![program.to_owned(), "--list-dirs".to_owned()],
133 None,
134 ProcessEnvPolicy::empty(),
135 None,
136 16 * 1024,
137 1024,
138 )
139 .map_err(|error| {
140 ProcessRunnerError::infrastructure(format!("invalid GPG discovery command: {error}"))
141 })?;
142 let context = ProcessRunnerContext::new(Default::default());
143 let cancellation = context.cancellation_token().clone();
144 let output = runner.run(intent, context);
145 tokio::pin!(output);
146 let output = tokio::select! {
147 result = &mut output => result?,
148 () = tokio::time::sleep(Duration::from_secs(2)) => {
149 cancellation.cancel();
150 let _ = output.await;
151 return Err(ProcessRunnerError::infrastructure("gpgconf socket discovery timed out after two seconds"));
152 }
153 };
154 if !output.ok() || output.stdout_truncated() || !output.stdout_is_utf8() {
155 return Err(ProcessRunnerError::infrastructure(
156 "gpgconf socket discovery failed or returned invalid/oversized output",
157 ));
158 }
159 Self::parse(output.stdout_text()).map(Some)
160 }
161
162 fn parse(output: &str) -> Result<Self, ProcessRunnerError> {
163 let mut home = None;
164 let mut agent = None;
165 let mut auxiliary = Vec::new();
166 for line in output.lines() {
167 let Some((name, value)) = line.split_once(':') else {
168 continue;
169 };
170 match name {
171 "homedir" => home = Some(decode(value)?),
172 "agent-socket" => agent = Some(decode(value)?),
173 "agent-ssh-socket"
174 | "agent-extra-socket"
175 | "agent-browser-socket"
176 | "keyboxd-socket" => auxiliary.push(decode(value)?),
177 _ => {}
178 }
179 }
180 let missing = || {
181 ProcessRunnerError::infrastructure("gpgconf did not report homedir and agent-socket")
182 };
183 Self::new(home.ok_or_else(missing)?, agent.ok_or_else(missing)?)?
184 .with_auxiliary_sockets(auxiliary)
185 }
186}
187
188fn validate(path: &Path) -> Result<(), ProcessRunnerError> {
189 if !path.is_absolute()
190 || path == Path::new("/")
191 || path
192 .components()
193 .any(|component| matches!(component, Component::ParentDir | Component::CurDir))
194 || path
195 .to_str()
196 .is_none_or(|value| value.chars().any(char::is_control))
197 {
198 return Err(ProcessRunnerError::infrastructure(
199 "GPG socket and home paths must be clean absolute UTF-8 paths",
200 ));
201 }
202 Ok(())
203}
204
205fn decode(value: &str) -> Result<PathBuf, ProcessRunnerError> {
206 let mut bytes = value.bytes();
207 let mut decoded = Vec::new();
208 while let Some(byte) = bytes.next() {
209 if byte == b'%' {
210 let digits = [bytes.next(), bytes.next()];
211 let [Some(high), Some(low)] = digits else {
212 return Err(ProcessRunnerError::infrastructure(
213 "invalid gpgconf path escape",
214 ));
215 };
216 let high = char::from(high).to_digit(16);
217 let low = char::from(low).to_digit(16);
218 let (Some(high), Some(low)) = (high, low) else {
219 return Err(ProcessRunnerError::infrastructure(
220 "invalid gpgconf path escape",
221 ));
222 };
223 decoded
224 .push(u8::try_from(high * 16 + low).map_err(|_| {
225 ProcessRunnerError::infrastructure("invalid gpgconf path byte")
226 })?);
227 } else {
228 decoded.push(byte);
229 }
230 }
231 let path = PathBuf::from(
232 String::from_utf8(decoded)
233 .map_err(|_| ProcessRunnerError::infrastructure("gpgconf path is not UTF-8"))?,
234 );
235 validate(&path)?;
236 Ok(path)
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 #[test]
244 fn parses_native_and_auxiliary_endpoints_without_conflating_protocols() {
245 let root = if cfg!(windows) { "C:" } else { "" };
246 let output = format!(
247 "homedir:{root}/home/user/custom%3ahome\nagent-socket:{root}/run/agent/native\nagent-ssh-socket:{root}/run/agent/ssh\nagent-extra-socket:{root}/run/agent/extra\nagent-browser-socket:{root}/run/agent/browser\nkeyboxd-socket:{root}/run/agent/keyboxd\n"
248 );
249 let sockets = GpgAgentSockets::parse(&output).unwrap();
250 assert_eq!(
251 sockets.home(),
252 Path::new(&format!("{root}/home/user/custom:home"))
253 );
254 assert_eq!(
255 sockets.agent(),
256 Path::new(&format!("{root}/run/agent/native"))
257 );
258 assert_eq!(sockets.paths().count(), 5);
259 assert!(
260 sockets
261 .paths()
262 .any(|path| path == Path::new(&format!("{root}/run/agent/keyboxd")))
263 );
264 }
265
266 #[test]
267 fn rejects_incomplete_or_unsafe_socket_discovery() {
268 for output in [
269 "homedir:/home/user",
270 "homedir:/home/user\nagent-socket:relative",
271 "homedir:/home/user\nagent-socket:/run/%00socket",
272 "homedir:/home/user\nagent-socket:/run/%GGsocket",
273 "homedir:/home/user\nagent-socket:/run/../socket",
274 ] {
275 assert!(GpgAgentSockets::parse(output).is_err());
276 }
277 }
278
279 #[cfg(unix)]
280 fn discovery_fixture(script: &str) -> (tempfile::TempDir, Vec<(OsString, OsString)>) {
281 use std::os::unix::fs::PermissionsExt;
282 let fixture = tempfile::tempdir().unwrap();
283 let program = fixture.path().join("gpgconf");
284 std::fs::write(&program, format!("#!/bin/sh\n{script}\n")).unwrap();
285 std::fs::set_permissions(program, std::fs::Permissions::from_mode(0o700)).unwrap();
286 let environment = vec![
287 (
288 OsString::from("PATH"),
289 fixture.path().as_os_str().to_owned(),
290 ),
291 (
292 OsString::from("GNUPGHOME"),
293 OsString::from("/custom/keyring"),
294 ),
295 ];
296 (fixture, environment)
297 }
298
299 #[cfg(unix)]
300 #[tokio::test]
301 async fn discovery_uses_the_configured_home_and_never_launches_an_agent() {
302 let (fixture, environment) = discovery_fixture(
303 "test \"$#\" = 1 && test \"$1\" = --list-dirs && test \"$HOME\" = /fixture/home || exit 1\nprintf 'homedir:%s\\nagent-socket:/custom/runtime/native\\n' \"$GNUPGHOME\"",
304 );
305 let sockets = GpgAgentSockets::discover(Path::new("/fixture/home"), &environment)
306 .await
307 .unwrap()
308 .unwrap();
309 assert_eq!(sockets.home(), Path::new("/custom/keyring"));
310 assert_eq!(sockets.agent(), Path::new("/custom/runtime/native"));
311 assert_eq!(std::fs::read_dir(fixture.path()).unwrap().count(), 1);
312 std::fs::remove_file(fixture.path().join("gpgconf")).unwrap();
313 assert!(
314 GpgAgentSockets::discover(Path::new("/fixture/home"), &environment)
315 .await
316 .unwrap()
317 .is_none()
318 );
319 }
320
321 #[cfg(unix)]
322 #[tokio::test]
323 async fn discovery_rejects_failure_and_oversized_output_without_reporting_output() {
324 for script in [
325 "printf 'private diagnostic' >&2; exit 1",
326 "printf '%17000s' oversized",
327 ] {
328 let (_fixture, environment) = discovery_fixture(script);
329 let error = GpgAgentSockets::discover(Path::new("/fixture/home"), &environment)
330 .await
331 .unwrap_err();
332 assert!(!error.to_string().contains("private diagnostic"));
333 }
334 }
335
336 #[cfg(unix)]
337 #[tokio::test]
338 async fn discovery_times_out_and_cancels_the_process() {
339 let (_fixture, environment) = discovery_fixture("exec /bin/sleep 30");
340 let error = GpgAgentSockets::discover(Path::new("/fixture/home"), &environment)
341 .await
342 .unwrap_err();
343 assert!(error.to_string().contains("timed out"));
344 }
345}