lean_ctx_cloud/consent/
helper_mac.rs1use std::io::{BufRead as _, BufReader, Write as _};
11use std::path::{Path, PathBuf};
12use std::time::Duration;
13
14use serde_json::{Value, json};
15
16use super::broker::Approval;
17use super::{Channel, ConsentError, PresenceSignature, Record};
18
19pub const APP_DIR: &str = "Applications/LeanCTX Consent.app";
21const EXECUTABLE: &str = "Contents/MacOS/LeanCTX Consent";
22pub const TEAM_ID: Option<&str> = option_env!("LEANCTX_RELEASE_TEAM_ID");
25const START_WAIT: Duration = Duration::from_secs(5);
27
28pub fn app_path() -> Option<PathBuf> {
29 dirs::home_dir().map(|home| home.join(APP_DIR))
30}
31
32pub fn team_of(codesign_display: &str) -> Option<&str> {
34 codesign_display
35 .lines()
36 .find_map(|l| l.strip_prefix("TeamIdentifier="))
37 .map(str::trim)
38 .filter(|t| !t.is_empty() && *t != "not set")
39}
40
41pub fn verify_signature(app: &Path) -> Result<(), ConsentError> {
43 if !app.join(EXECUTABLE).is_file() {
44 return Err(ConsentError::HelperMissing);
45 }
46 let Some(pinned) = TEAM_ID else {
47 return Err(ConsentError::HelperSignature);
48 };
49 let run = |args: &[&str]| {
50 std::process::Command::new("/usr/bin/codesign")
51 .args(args)
52 .arg(app)
53 .stdin(std::process::Stdio::null())
54 .output()
55 };
56 let verified = run(&["--verify", "--strict", "--deep"]).is_ok_and(|o| o.status.success());
57 let shown = run(&["-dv", "--verbose=2"]).ok();
58 let team = shown
59 .as_ref()
60 .map(|o| String::from_utf8_lossy(&o.stderr).into_owned())
61 .and_then(|text| team_of(&text).map(str::to_string));
62 if verified && team.as_deref() == Some(pinned) {
63 Ok(())
64 } else {
65 Err(ConsentError::HelperSignature)
66 }
67}
68
69pub struct Helper {
71 child: std::process::Child,
72 reader: BufReader<std::os::unix::net::UnixStream>,
73 writer: std::os::unix::net::UnixStream,
74 next_id: u64,
75}
76
77impl Helper {
78 pub fn start(app: &Path, socket_dir: &Path) -> Result<Helper, ConsentError> {
80 verify_signature(app)?;
81 let local = |e: std::io::Error| ConsentError::Local(format!("consent helper: {e}"));
82 crate::state::write_private(socket_dir, ".keep", b"")
83 .map_err(|e| ConsentError::Local(e.to_string()))?;
84 let socket = socket_dir.join("ctl.sock");
85 let _ = std::fs::remove_file(&socket);
86 let mut secret = [0u8; 32];
87 getrandom::fill(&mut secret).map_err(|e| ConsentError::Local(e.to_string()))?;
88 let secret = hex::encode(secret);
89 let mut child = std::process::Command::new(app.join(EXECUTABLE))
90 .arg("--socket")
91 .arg(&socket)
92 .stdin(std::process::Stdio::piped())
93 .stdout(std::process::Stdio::null())
94 .stderr(std::process::Stdio::null())
95 .spawn()
96 .map_err(local)?;
97 if let Some(mut stdin) = child.stdin.take() {
98 writeln!(stdin, "{secret}").map_err(local)?;
99 }
100 let started = std::time::Instant::now();
101 let stream = loop {
102 match std::os::unix::net::UnixStream::connect(&socket) {
103 Ok(stream) => break stream,
104 Err(_) if started.elapsed() < START_WAIT => {
105 std::thread::sleep(Duration::from_millis(50));
106 }
107 Err(e) => {
108 let _ = child.kill();
109 return Err(local(e));
110 }
111 }
112 };
113 let writer = stream.try_clone().map_err(local)?;
114 let mut helper = Helper {
115 child,
116 reader: BufReader::new(stream),
117 writer,
118 next_id: 0,
119 };
120 helper.call("hello", &json!({"secret": secret}))?;
121 Ok(helper)
122 }
123
124 fn call(&mut self, method: &str, params: &Value) -> Result<Value, ConsentError> {
125 self.next_id += 1;
126 let request =
127 json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
128 let local = |e: std::io::Error| ConsentError::Local(format!("consent helper: {e}"));
129 writeln!(self.writer, "{request}").map_err(local)?;
130 let mut line = String::new();
131 self.reader.read_line(&mut line).map_err(local)?;
132 let answer: Value = serde_json::from_str(&line)
133 .map_err(|_| ConsentError::Local("consent helper: malformed answer".into()))?;
134 answer_result(&answer)
135 }
136
137 pub fn presence(&mut self, record: &Record) -> Result<Approval, ConsentError> {
139 let result = self.call(
140 "presence",
141 &json!({"consent_id": record.consent_id, "kind": record.kind, "subject": record.subject}),
142 )?;
143 approval_of(&result)
144 }
145
146 pub fn bind_key(&mut self, instance_id: &str) -> Result<Value, ConsentError> {
149 self.call("bind_key", &json!({"instance_id": instance_id}))
150 }
151
152 pub fn public_key(&mut self) -> Result<Value, ConsentError> {
153 self.call("public_key", &json!({}))
154 }
155}
156
157impl Drop for Helper {
158 fn drop(&mut self) {
159 let _ = self.writer.shutdown(std::net::Shutdown::Both);
160 let _ = self.child.wait();
161 }
162}
163
164pub fn answer_result(answer: &Value) -> Result<Value, ConsentError> {
167 if let Some(result) = answer.get("result") {
168 return Ok(result.clone());
169 }
170 match answer["error"]["code"].as_i64() {
171 Some(1) => Err(ConsentError::PresenceCancelled),
172 _ => Err(ConsentError::Local(format!(
173 "consent helper: {}",
174 answer["error"]["message"].as_str().unwrap_or("refused")
175 ))),
176 }
177}
178
179pub fn approval_of(result: &Value) -> Result<Approval, ConsentError> {
181 let (Some(approved_at), Some(key_id), Some(signature)) = (
182 result["approved_at"].as_u64(),
183 result["key_id"].as_str(),
184 result["signature"].as_str(),
185 ) else {
186 return Err(ConsentError::Local(
187 "consent helper: incomplete proof".into(),
188 ));
189 };
190 Ok(Approval::Presence {
191 signature: PresenceSignature {
192 key_id: key_id.into(),
193 alg: "p256_ecdsa_sha256".into(),
194 signature: signature.into(),
195 },
196 approved_at,
197 channel: Channel::OsPresence,
198 })
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[test]
206 fn the_team_id_is_read_from_codesign_output() {
207 let shown =
208 "Executable=/x\nIdentifier=ch.thinkery.leanctx.consent\nTeamIdentifier=ABCDE12345\n";
209 assert_eq!(team_of(shown), Some("ABCDE12345"));
210 assert_eq!(team_of("TeamIdentifier=not set\n"), None);
211 assert_eq!(team_of("Identifier=x\n"), None);
212 }
213
214 #[test]
215 fn a_missing_helper_is_named() {
216 let dir = tempfile::tempdir().unwrap();
217 assert_eq!(
218 verify_signature(&dir.path().join("LeanCTX Consent.app")),
219 Err(ConsentError::HelperMissing)
220 );
221 }
222
223 #[test]
224 fn answers_map_to_proofs_and_refusals() {
225 let ok = json!({"jsonrpc": "2.0", "id": 1, "result": {
226 "approved_at": 1_792_800_090_000u64, "key_id": "70daf6041ffc7219", "signature": "MEQC"}});
227 let Approval::Presence {
228 signature,
229 approved_at,
230 channel,
231 } = approval_of(&answer_result(&ok).unwrap()).unwrap()
232 else {
233 panic!("a presence approval");
234 };
235 assert_eq!(
236 (approved_at, channel),
237 (1_792_800_090_000, Channel::OsPresence)
238 );
239 assert_eq!(signature.alg, "p256_ecdsa_sha256");
240 let cancelled =
241 json!({"jsonrpc": "2.0", "id": 2, "error": {"code": 1, "message": "cancelled"}});
242 assert_eq!(
243 answer_result(&cancelled),
244 Err(ConsentError::PresenceCancelled)
245 );
246 let invalid = json!({"jsonrpc": "2.0", "id": 3, "error": {"code": -32602, "message": "invalid_params"}});
247 assert!(matches!(
248 answer_result(&invalid),
249 Err(ConsentError::Local(_))
250 ));
251 }
252}