Skip to main content

xtask_kit/apple/
mod.rs

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/// A resolved Xcode developer directory.
20#[derive(Clone, Debug)]
21pub struct Xcode {
22    developer_dir: PathBuf,
23}
24
25impl Xcode {
26    /// Resolve Xcode from `env_key`, falling back to the standard Xcode.app path.
27    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    /// Construct an [`Xcode`] from an explicit developer directory.
35    pub fn new(developer_dir: impl Into<PathBuf>) -> Self {
36        Self {
37            developer_dir: developer_dir.into(),
38        }
39    }
40
41    /// Return the developer directory.
42    pub fn developer_dir(&self) -> &Path {
43        &self.developer_dir
44    }
45
46    /// Return true when this Xcode installation contains an iOS platform SDK.
47    pub fn has_ios_sdk(&self) -> bool {
48        self.developer_dir
49            .join("Platforms/iPhoneOS.platform")
50            .exists()
51    }
52
53    /// Run `/usr/bin/xcrun --sdk <sdk> ...` with this `DEVELOPER_DIR` and return trimmed stdout.
54    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    /// Return the SDK path for `sdk`, for example `macosx` or `iphoneos`.
66    pub fn sdk_path(&self, sh: &Shell, sdk: &str) -> Result<String> {
67        self.xcrun(sh, sdk, &["--show-sdk-path"])
68    }
69
70    /// Build a command in a minimal host-Xcode environment.
71    ///
72    /// This is useful in nix/devenv shells where `SDKROOT`, `DEVELOPER_DIR`, and
73    /// compiler wrapper variables may point SwiftPM or Xcode at an incompatible SDK.
74    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/// Options for hardened-runtime codesigning.
90#[derive(Clone, Debug)]
91pub struct CodesignOptions<'a> {
92    /// Signing identity. Use `-` for ad-hoc signing.
93    pub identity: &'a str,
94    /// File or bundle to sign.
95    pub target: &'a Path,
96    /// Optional entitlements plist.
97    pub entitlements: Option<&'a Path>,
98    /// Optional explicit signing identifier.
99    pub identifier: Option<&'a str>,
100    /// Include `--options runtime`.
101    pub hardened_runtime: bool,
102    /// Include `--timestamp`. Ignored for ad-hoc signatures.
103    pub timestamp: bool,
104}
105
106impl<'a> CodesignOptions<'a> {
107    /// Create standard Developer ID-style options for `target` and `identity`.
108    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
120/// Sign a binary or bundle using `/usr/bin/codesign`.
121pub 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
152/// Verify a code signature with `codesign --verify --strict`.
153pub 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
170/// Read signed entitlements as XML.
171pub 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
189/// Overwrite a top-level string key in a plist file.
190pub 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/// A decoded provisioning profile matching an application identifier.
203#[derive(Clone, Debug)]
204pub struct ProvisioningProfile {
205    /// Profile file path.
206    pub path: PathBuf,
207    /// Human-readable profile name.
208    pub name: String,
209    /// `com.apple.application-identifier` entitlement.
210    pub application_identifier: String,
211    /// Whether the profile provisions all devices, typical for Developer ID profiles.
212    pub provisions_all_devices: bool,
213}
214
215/// Find installed provisioning profiles whose application identifier equals `app_id`.
216pub 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
225/// Resolve a provisioning profile from an environment override or installed profiles.
226///
227/// When multiple installed profiles match, a Developer ID profile
228/// (`ProvisionsAllDevices = true`) is preferred if it is unique.
229pub 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
270/// Decode one `.provisionprofile` or `.mobileprovision` file.
271pub 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
338/// Submit an artifact to Apple notarization and staple it after acceptance.
339pub 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}