1use std::ffi::OsStr;
2use std::io::Cursor;
3use std::path::{Path, PathBuf};
4use std::process::Command;
5
6use anyhow::{Context, Result, bail};
7use plist::Value;
8use xshell::{Cmd, Shell, cmd};
9
10const HOST_XCODE_ENV: &[&str] = &[
11 "HOME",
12 "TMPDIR",
13 "USER",
14 "LOGNAME",
15 "SHELL",
16 "SSH_AUTH_SOCK",
17];
18
19#[derive(Clone, Debug)]
21pub struct Xcode {
22 developer_dir: PathBuf,
23}
24
25impl Xcode {
26 pub fn resolve(env_key: &str) -> Self {
28 let developer_dir = std::env::var_os(env_key)
29 .map(PathBuf::from)
30 .unwrap_or_else(|| PathBuf::from("/Applications/Xcode.app/Contents/Developer"));
31 Self { developer_dir }
32 }
33
34 pub fn new(developer_dir: impl Into<PathBuf>) -> Self {
36 Self {
37 developer_dir: developer_dir.into(),
38 }
39 }
40
41 pub fn developer_dir(&self) -> &Path {
43 &self.developer_dir
44 }
45
46 pub fn has_ios_sdk(&self) -> bool {
48 self.developer_dir
49 .join("Platforms/iPhoneOS.platform")
50 .exists()
51 }
52
53 pub fn xcrun(&self, sh: &Shell, sdk: &str, args: &[&str]) -> Result<String> {
55 let mut full = vec!["--sdk", sdk];
56 full.extend_from_slice(args);
57 Ok(cmd!(sh, "/usr/bin/xcrun {full...}")
58 .env("DEVELOPER_DIR", self.developer_dir.as_os_str())
59 .read()
60 .with_context(|| format!("run xcrun for SDK {sdk}"))?
61 .trim()
62 .to_string())
63 }
64
65 pub fn sdk_path(&self, sh: &Shell, sdk: &str) -> Result<String> {
67 self.xcrun(sh, sdk, &["--show-sdk-path"])
68 }
69
70 pub fn clean_cmd<'a>(&self, sh: &'a Shell, program: &str, args: &[&str]) -> Cmd<'a> {
75 keep_host_env(sh.cmd(program).args(args).env_clear())
76 .env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
77 .env("MACOSX_DEPLOYMENT_TARGET", "14.0")
78 .env("DEVELOPER_DIR", self.developer_dir.as_os_str())
79 }
80}
81
82fn keep_host_env(cmd: Cmd<'_>) -> Cmd<'_> {
83 HOST_XCODE_ENV
84 .iter()
85 .filter_map(|key| std::env::var_os(key).map(|value| (*key, value)))
86 .fold(cmd, |cmd, (key, value)| cmd.env(key, value))
87}
88
89#[derive(Clone, Debug)]
91pub struct CodesignOptions<'a> {
92 pub identity: &'a str,
94 pub target: &'a Path,
96 pub entitlements: Option<&'a Path>,
98 pub identifier: Option<&'a str>,
100 pub hardened_runtime: bool,
102 pub timestamp: bool,
104}
105
106impl<'a> CodesignOptions<'a> {
107 pub fn runtime(identity: &'a str, target: &'a Path) -> Self {
109 Self {
110 identity,
111 target,
112 entitlements: None,
113 identifier: None,
114 hardened_runtime: true,
115 timestamp: true,
116 }
117 }
118}
119
120pub fn codesign(options: &CodesignOptions<'_>) -> Result<()> {
122 let mut command = Command::new("/usr/bin/codesign");
123 command.arg("--force");
124 if options.hardened_runtime {
125 command.args(["--options", "runtime"]);
126 }
127 if let Some(identifier) = options.identifier {
128 command.args(["--identifier", identifier]);
129 }
130 if let Some(entitlements) = options.entitlements {
131 command.arg("--entitlements").arg(entitlements);
132 }
133 command.args(["--sign", options.identity]);
134 if options.timestamp && options.identity != "-" {
135 command.arg("--timestamp");
136 }
137 command.arg(options.target);
138
139 let status = command
140 .status()
141 .with_context(|| format!("run codesign for {}", options.target.display()))?;
142 if status.success() {
143 Ok(())
144 } else {
145 bail!(
146 "codesign failed for {} with {status}",
147 options.target.display()
148 )
149 }
150}
151
152pub fn verify_signature(target: impl AsRef<Path>) -> Result<()> {
154 let target = target.as_ref();
155 let status = Command::new("/usr/bin/codesign")
156 .args([OsStr::new("--verify"), OsStr::new("--strict")])
157 .arg(target)
158 .status()
159 .with_context(|| format!("verify signature for {}", target.display()))?;
160 if status.success() {
161 Ok(())
162 } else {
163 bail!(
164 "codesign verification failed for {} with {status}",
165 target.display()
166 )
167 }
168}
169
170pub fn entitlements_xml(target: impl AsRef<Path>) -> Result<String> {
172 let target = target.as_ref();
173 let output = Command::new("/usr/bin/codesign")
174 .args(["-d", "--entitlements", "-", "--xml"])
175 .arg(target)
176 .output()
177 .with_context(|| format!("read entitlements for {}", target.display()))?;
178 if !output.status.success() {
179 bail!(
180 "codesign could not read entitlements for {}",
181 target.display()
182 );
183 }
184 let mut xml = String::from_utf8_lossy(&output.stdout).into_owned();
185 xml.push_str(&String::from_utf8_lossy(&output.stderr));
186 Ok(xml)
187}
188
189pub fn set_plist_string(plist: impl AsRef<Path>, key: &str, value: &str) -> Result<()> {
191 let plist = plist.as_ref();
192 let mut root =
193 Value::from_file(plist).with_context(|| format!("read plist {}", plist.display()))?;
194 let dict = root
195 .as_dictionary_mut()
196 .with_context(|| format!("plist root is not a dictionary: {}", plist.display()))?;
197 dict.insert(key.into(), Value::String(value.to_string()));
198 root.to_file_xml(plist)
199 .with_context(|| format!("write plist {}", plist.display()))
200}
201
202#[derive(Clone, Debug)]
204pub struct ProvisioningProfile {
205 pub path: PathBuf,
207 pub name: String,
209 pub application_identifier: String,
211 pub provisions_all_devices: bool,
213}
214
215pub fn find_provisioning_profiles(app_id: &str) -> Vec<ProvisioningProfile> {
217 profile_search_roots()
218 .into_iter()
219 .flat_map(|root| profile_files(&root))
220 .filter_map(|path| read_provisioning_profile(&path).ok())
221 .filter(|profile| profile.application_identifier == app_id)
222 .collect()
223}
224
225pub fn resolve_provisioning_profile(
230 env_key: &str,
231 app_id: &str,
232) -> Result<Option<ProvisioningProfile>> {
233 if let Ok(path) = std::env::var(env_key) {
234 let path = PathBuf::from(path);
235 if !path.exists() {
236 bail!("{env_key} does not exist: {}", path.display());
237 }
238 return read_provisioning_profile(&path).map(Some);
239 }
240
241 let profiles = find_provisioning_profiles(app_id);
242 match profiles.as_slice() {
243 [] => Ok(None),
244 [profile] => Ok(Some(profile.clone())),
245 many => {
246 let developer_id = many
247 .iter()
248 .filter(|profile| profile.provisions_all_devices)
249 .collect::<Vec<_>>();
250 if let [profile] = developer_id.as_slice() {
251 return Ok(Some((*profile).clone()));
252 }
253
254 let mut message = format!(
255 "multiple installed provisioning profiles matched {app_id}; set {env_key} to choose one:"
256 );
257 for profile in many {
258 message.push_str(&format!(
259 "\n - {} ({}, ProvisionsAllDevices={})",
260 profile.path.display(),
261 profile.name,
262 profile.provisions_all_devices
263 ));
264 }
265 bail!(message)
266 }
267 }
268}
269
270pub fn read_provisioning_profile(path: impl AsRef<Path>) -> Result<ProvisioningProfile> {
272 let path = path.as_ref();
273 let output = Command::new("/usr/bin/security")
274 .args(["cms", "-D", "-i"])
275 .arg(path)
276 .output()
277 .with_context(|| format!("decode provisioning profile {}", path.display()))?;
278 if !output.status.success() {
279 bail!("security cms failed for {}", path.display());
280 }
281
282 let plist = Value::from_reader_xml(Cursor::new(output.stdout))?;
283 let root = plist
284 .as_dictionary()
285 .with_context(|| format!("profile root is not a dictionary: {}", path.display()))?;
286 let entitlements = root
287 .get("Entitlements")
288 .and_then(Value::as_dictionary)
289 .context("profile has no Entitlements dictionary")?;
290 let application_identifier = entitlements
291 .get("com.apple.application-identifier")
292 .and_then(Value::as_string)
293 .context("profile has no com.apple.application-identifier entitlement")?
294 .to_string();
295
296 Ok(ProvisioningProfile {
297 path: path.to_path_buf(),
298 name: root
299 .get("Name")
300 .and_then(Value::as_string)
301 .unwrap_or("<unnamed>")
302 .to_string(),
303 application_identifier,
304 provisions_all_devices: root
305 .get("ProvisionsAllDevices")
306 .and_then(Value::as_boolean)
307 .unwrap_or(false),
308 })
309}
310
311fn profile_search_roots() -> Vec<PathBuf> {
312 let mut roots = Vec::new();
313 if let Ok(home) = std::env::var("HOME") {
314 let standard = PathBuf::from(&home).join("Library/MobileDevice/Provisioning Profiles");
315 if standard.exists() {
316 roots.push(standard);
317 } else {
318 roots.push(PathBuf::from(home).join("Developer"));
319 }
320 }
321 roots
322}
323
324fn profile_files(root: &Path) -> Vec<PathBuf> {
325 let mut files = Vec::new();
326 if let Ok(entries) = std::fs::read_dir(root) {
327 for entry in entries.flatten() {
328 let path = entry.path();
329 let ext = path.extension().and_then(|ext| ext.to_str());
330 if matches!(ext, Some("provisionprofile" | "mobileprovision")) {
331 files.push(path);
332 }
333 }
334 }
335 files
336}
337
338pub fn notarize_and_staple(artifact: impl AsRef<Path>, keychain_profile: &str) -> Result<()> {
340 let artifact = artifact.as_ref();
341 let output = Command::new("/usr/bin/xcrun")
342 .args([
343 "notarytool",
344 "submit",
345 &artifact.to_string_lossy(),
346 "--keychain-profile",
347 keychain_profile,
348 "--wait",
349 "--timeout",
350 "90m",
351 ])
352 .output()
353 .with_context(|| format!("submit {} for notarization", artifact.display()))?;
354 let mut log = String::from_utf8_lossy(&output.stdout).into_owned();
355 log.push_str(&String::from_utf8_lossy(&output.stderr));
356 print!("{log}");
357
358 if !output.status.success() || !log.contains("status: Accepted") {
359 bail!(
360 "notarization did not reach Accepted for {}",
361 artifact.display()
362 );
363 }
364
365 let status = Command::new("/usr/bin/xcrun")
366 .args(["stapler", "staple", &artifact.to_string_lossy()])
367 .status()
368 .with_context(|| format!("staple notarization ticket to {}", artifact.display()))?;
369 if status.success() {
370 Ok(())
371 } else {
372 bail!("stapler failed for {} with {status}", artifact.display())
373 }
374}