nsh-cli 0.8.0

The nsh command line tool: build, package and run apps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Provisioning profiles of iOS device packages and macOS packages (`nsh
//! package --target ios|macos --profile`): on iOS one for the app and one
//! for each of its app extensions, each found by the bundle identifier it
//! covers, and the entitlements a bundle is signed with under its profile.

use std::{
    cell::Cell,
    path::{Path, PathBuf},
    process::Command,
};

use anyhow::{Context, bail};

use crate::ui;

/// A provisioning profile (iOS `.mobileprovision`, macOS
/// `.provisionprofile`), read.
#[derive(Debug)]
pub(crate) struct Profile {
    /// The file, which a bundle carries as `embedded.mobileprovision` (iOS)
    /// or `Contents/embedded.provisionprofile` (macOS).
    pub(crate) path: PathBuf,
    /// Its `application-identifier` (`TEAMID.com.example.app`, or a
    /// wildcard such as `TEAMID.*`).
    app_id: String,
    /// The entitlements it grants.
    entitlements: plist::Dictionary,
    /// Whether it lists no devices and does not provision them all: an App
    /// Store profile, the only kind the App Store and the Mac App Store take.
    pub(crate) store: bool,
    /// The platforms it is for (`iOS`, `OSX`), as its `Platform` lists them.
    platforms: Vec<String>,
    /// Whether [`Profile::choose`] chose it for a bundle.
    used: Cell<bool>,
}

impl Profile {
    /// Reads the profile at `path`.
    pub(crate) fn read(path: &Path) -> anyhow::Result<Self> {
        let output = Command::new("security")
            .args(["cms", "-D", "-i"])
            .arg(path)
            .output()
            .context("run security cms")?;
        if !output.status.success() {
            bail!("cannot read provisioning profile {}", path.display());
        }
        let profile = plist::Value::from_reader_xml(output.stdout.as_slice())?;
        let dictionary = profile.as_dictionary();
        let key = |key: &str| dictionary.and_then(|d| d.get(key));
        let devices = key("ProvisionedDevices").is_some()
            || key("ProvisionsAllDevices").and_then(|v| v.as_boolean()) == Some(true);
        let platforms = key("Platform")
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|v| v.as_string().map(str::to_owned))
                    .collect()
            })
            .unwrap_or_default();
        let entitlements = key("Entitlements")
            .and_then(|v| v.as_dictionary())
            .cloned()
            .with_context(|| {
                format!(
                    "the provisioning profile {} has no entitlements",
                    path.display()
                )
            })?;
        let mut profile = Self::new(path.to_owned(), entitlements);
        profile.store = !devices;
        profile.platforms = platforms;
        Ok(profile)
    }

    fn new(path: PathBuf, entitlements: plist::Dictionary) -> Self {
        // iOS profiles name the app `application-identifier`, macOS ones
        // `com.apple.application-identifier`.
        let app_id = ["application-identifier", MACOS_APP_ID]
            .iter()
            .find_map(|key| entitlements.get(key).and_then(|v| v.as_string()))
            .unwrap_or_default()
            .to_owned();
        Profile {
            path,
            app_id,
            entitlements,
            store: false,
            platforms: Vec::new(),
            used: Cell::new(false),
        }
    }

    /// Whether it is for macOS (`Platform` lists `OSX`).
    pub(crate) fn is_macos(&self) -> bool {
        self.platforms.iter().any(|p| p == "OSX")
    }

    /// Whether it is for iOS (`Platform` lists `iOS`).
    pub(crate) fn is_ios(&self) -> bool {
        self.platforms.iter().any(|p| p == "iOS")
    }

    /// The profile of `profiles` for bundle id `id`: the one whose
    /// application identifier names it, else the narrowest wildcard that
    /// covers it (`TEAMID.com.example.*` before `TEAMID.*`). Two equally
    /// close profiles are an error, as is none; when `id` is an app
    /// extension's (`extension`), whose profile a command line with only the
    /// app's leaves out, the error says to pass it.
    pub(crate) fn choose<'p>(
        profiles: &'p [Profile],
        id: &str,
        extension: bool,
    ) -> anyhow::Result<&'p Profile> {
        // Exact before wildcard, then the longer pattern.
        let closeness = |profile: &Profile| {
            let pattern = profile.app_id.split_once('.').map_or("", |(_, p)| p);
            (!pattern.ends_with('*'), pattern.len())
        };
        let covering: Vec<&Profile> = profiles
            .iter()
            .filter(|p| profile_allows(&p.app_id, id))
            .collect();
        let Some(best) = covering.iter().map(|p| closeness(p)).max() else {
            return Err(match profiles {
                [profile] if extension => anyhow::anyhow!(
                    "the provisioning profile is for {}, not {id}: pass its profile with another --profile",
                    profile.app_id
                ),
                [profile] => anyhow::anyhow!(
                    "the provisioning profile is for {}, not {id}",
                    profile.app_id
                ),
                _ => anyhow::anyhow!(
                    "none of the provisioning profiles is for {id} (they are for {}): pass its profile with another --profile",
                    profiles
                        .iter()
                        .map(|p| p.app_id.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            });
        };
        let mut closest = covering.into_iter().filter(|p| closeness(p) == best);
        let profile = closest.next().expect("the closest profile is one of them");
        if let Some(other) = closest.next() {
            bail!(
                "{} and {} are both provisioning profiles for {id}: pass one of them",
                profile.path.display(),
                other.path.display()
            );
        }
        profile.used.set(true);
        Ok(profile)
    }

    /// The entitlements bundle id `id` is signed with under this profile:
    /// those it grants, with the bundle's own (`requested`, `nsh.json`
    /// `section`) in place of its values, each checked against what it
    /// grants.
    pub(crate) fn entitlements(
        &self,
        id: &str,
        requested: plist::Dictionary,
        section: &str,
    ) -> anyhow::Result<plist::Value> {
        if !profile_allows(&self.app_id, id) {
            bail!("the provisioning profile is for {}, not {id}", self.app_id);
        }
        let mut entitlements = self.entitlements.clone();
        crate::apple::grant(&mut entitlements, requested, section)?;
        // A wildcard profile (`TEAMID.*`) signs the bundle as `TEAMID.<id>`,
        // as Xcode does: devices refuse a bundle signed with the wildcard
        // itself.
        entitlements.insert(
            "application-identifier".to_owned(),
            plist::Value::String(signed_app_id(&self.app_id, id)),
        );
        Ok(plist::Value::Dictionary(entitlements))
    }
}

impl Profile {
    /// The entitlements macOS app `id` is signed with under this profile:
    /// the app's own (`requested`, `nsh.json` `macos.entitlements`), the
    /// ones only a profile grants ([`crate::apple::needs_profile`]) checked
    /// against it, and the app's identity from it. Unlike on iOS, the rest
    /// of what the profile grants (its wildcard keychain groups) is left
    /// out, as Xcode does: the sandbox keys are the app's, not the
    /// profile's.
    pub(crate) fn macos_entitlements(
        &self,
        id: &str,
        requested: plist::Dictionary,
    ) -> anyhow::Result<plist::Dictionary> {
        if !profile_allows(&self.app_id, id) {
            bail!("the provisioning profile is for {}, not {id}", self.app_id);
        }
        let (checked, own): (plist::Dictionary, plist::Dictionary) = requested
            .into_iter()
            .partition(|(key, _)| crate::apple::needs_profile(key));
        let mut granted = self.entitlements.clone();
        crate::apple::grant(&mut granted, checked.clone(), "macos.entitlements")?;
        let mut entitlements = own;
        for key in checked.keys() {
            if let Some(value) = granted.get(key) {
                entitlements.insert(key.clone(), value.clone());
            }
        }
        entitlements.insert(
            MACOS_APP_ID.to_owned(),
            plist::Value::String(signed_app_id(&self.app_id, id)),
        );
        if let Some(team) = self.entitlements.get(TEAM_ID) {
            entitlements.insert(TEAM_ID.to_owned(), team.clone());
        }
        Ok(entitlements)
    }
}

/// A macOS profile's key for the app's identifier.
const MACOS_APP_ID: &str = "com.apple.application-identifier";
/// A macOS profile's key for the team's identifier.
const TEAM_ID: &str = "com.apple.developer.team-identifier";

/// The profiles [`Profile::choose`] chose for no bundle.
fn unused(profiles: &[Profile]) -> impl Iterator<Item = &Profile> {
    profiles.iter().filter(|p| !p.used.get())
}

/// Warns of each `--profile` the package signed no bundle with: a profile
/// meant for a bundle whose identifier it does not cover, or one too many.
pub(crate) fn warn_unused(profiles: &[Profile]) {
    for profile in unused(profiles) {
        ui::warn(format!(
            "--profile {} is for {}, which no bundle of the package is, so nothing is signed with it",
            profile.path.display(),
            profile.app_id
        ));
    }
}

/// The `application-identifier` a bundle with id `id` is signed with under
/// a profile's (`TEAMID.com.example.app` or a wildcard such as `TEAMID.*`),
/// which covers it.
fn signed_app_id(app_id: &str, id: &str) -> String {
    match app_id.split_once('.') {
        Some((team, pattern)) if pattern.ends_with('*') => format!("{team}.{id}"),
        _ => app_id.to_owned(),
    }
}

/// Whether a profile's `application-identifier` (`TEAMID.com.example.app`,
/// or a wildcard such as `TEAMID.*`) covers bundle id `id`.
fn profile_allows(app_id: &str, id: &str) -> bool {
    app_id
        .split_once('.')
        .map(|(_, pattern)| match pattern.strip_suffix('*') {
            Some(prefix) => id.starts_with(prefix),
            None => pattern == id,
        })
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn profile(file: &str, app_id: &str) -> Profile {
        let mut entitlements = plist::Dictionary::new();
        entitlements.insert("application-identifier".into(), app_id.into());
        entitlements.insert("aps-environment".into(), "production".into());
        Profile::new(file.into(), entitlements)
    }

    /// A Mac App Store profile as Apple writes one: the app's identity, the
    /// team's keychain groups, and the capabilities enabled for the id.
    fn macos_profile() -> Profile {
        let mut entitlements = plist::Dictionary::new();
        entitlements.insert(MACOS_APP_ID.into(), "TEAMID.ai.example.board".into());
        entitlements.insert(TEAM_ID.into(), "TEAMID".into());
        entitlements.insert(
            "keychain-access-groups".into(),
            plist::Value::Array(vec!["TEAMID.*".into()]),
        );
        entitlements.insert("com.apple.developer.associated-domains".into(), "*".into());
        let mut profile = Profile::new("board.provisionprofile".into(), entitlements);
        profile.store = true;
        profile.platforms = vec!["OSX".into()];
        profile
    }

    #[test]
    fn macos_apps_are_signed_with_their_own_entitlements_and_the_profiles_identity() {
        let profile = macos_profile();
        assert!(profile.is_macos());
        assert!(!profile.is_ios());
        let mut requested = plist::Dictionary::new();
        requested.insert("com.apple.security.app-sandbox".into(), true.into());
        requested.insert(
            "com.apple.developer.associated-domains".into(),
            plist::Value::Array(vec!["applinks:example.com".into()]),
        );
        let signed = profile
            .macos_entitlements("ai.example.board", requested)
            .unwrap();
        assert_eq!(
            signed.get(MACOS_APP_ID).and_then(|v| v.as_string()),
            Some("TEAMID.ai.example.board")
        );
        assert_eq!(
            signed.get(TEAM_ID).and_then(|v| v.as_string()),
            Some("TEAMID")
        );
        assert_eq!(
            signed.get("com.apple.security.app-sandbox"),
            Some(&plist::Value::Boolean(true))
        );
        assert_eq!(
            signed.get("com.apple.developer.associated-domains"),
            Some(&plist::Value::Array(vec!["applinks:example.com".into()]))
        );
        assert!(!signed.contains_key("keychain-access-groups"));
    }

    #[test]
    fn macos_profiles_must_grant_what_only_a_profile_can() {
        let profile = macos_profile();
        let mut requested = plist::Dictionary::new();
        requested.insert("com.apple.developer.icloud-services".into(), "*".into());
        let error = profile
            .macos_entitlements("ai.example.board", requested)
            .unwrap_err();
        assert!(error.to_string().contains("does not grant the entitlement"));
        assert!(
            profile
                .macos_entitlements("ai.example.other", plist::Dictionary::new())
                .is_err()
        );
    }

    #[test]
    fn profiles_match_bundle_ids() {
        assert!(profile_allows(
            "ABCDE12345.com.example.app",
            "com.example.app"
        ));
        assert!(!profile_allows(
            "ABCDE12345.com.example.app",
            "com.example.other"
        ));
        assert!(profile_allows("ABCDE12345.*", "com.example.app"));
        assert!(profile_allows(
            "ABCDE12345.com.example.*",
            "com.example.app"
        ));
        assert!(!profile_allows("ABCDE12345.com.other.*", "com.example.app"));
        assert!(!profile_allows("", "com.example.app"));
    }

    #[test]
    fn wildcard_profiles_sign_the_bundle_id() {
        assert_eq!(
            signed_app_id("ABCDE12345.*", "com.example.app"),
            "ABCDE12345.com.example.app"
        );
        assert_eq!(
            signed_app_id("ABCDE12345.com.example.*", "com.example.app"),
            "ABCDE12345.com.example.app"
        );
        assert_eq!(
            signed_app_id("ABCDE12345.com.example.app", "com.example.app"),
            "ABCDE12345.com.example.app"
        );
    }

    /// The app and each extension take the profile that names them, else
    /// the narrowest wildcard covering them.
    #[test]
    fn each_bundle_takes_the_closest_profile() {
        let profiles = [
            profile("all.mobileprovision", "TEAM.*"),
            profile("app.mobileprovision", "TEAM.com.example.app"),
            profile("widget.mobileprovision", "TEAM.com.example.app.Widget"),
            profile("example.mobileprovision", "TEAM.com.example.*"),
        ];
        let chosen = |id| {
            Profile::choose(&profiles, id, id != "com.example.app")
                .unwrap()
                .path
                .to_string_lossy()
                .into_owned()
        };
        assert_eq!(chosen("com.example.app"), "app.mobileprovision");
        assert_eq!(chosen("com.example.app.Widget"), "widget.mobileprovision");
        assert_eq!(chosen("com.example.app.Service"), "example.mobileprovision");
        assert_eq!(chosen("org.other.app"), "all.mobileprovision");
        assert_eq!(unused(&profiles).count(), 0);
    }

    /// A profile no bundle took is left over, which packaging warns of.
    #[test]
    fn profiles_no_bundle_takes_are_left_over() {
        let profiles = [
            profile("app.mobileprovision", "TEAM.com.example.app"),
            profile("widget.mobileprovision", "TEAM.com.example.app.Widget"),
            profile("old.mobileprovision", "TEAM.com.example.app.Old"),
        ];
        Profile::choose(&profiles, "com.example.app.Widget", true).unwrap();
        Profile::choose(&profiles, "com.example.app", false).unwrap();
        let left: Vec<_> = unused(&profiles).map(|p| p.app_id.as_str()).collect();
        assert_eq!(left, ["TEAM.com.example.app.Old"]);
    }

    #[test]
    fn a_bundle_without_a_profile_or_with_two_is_an_error() {
        let one = [profile("app.mobileprovision", "TEAM.com.example.app")];
        // The app's error stays as it was; an extension's says what to do.
        assert_eq!(
            Profile::choose(&one, "com.other.app", false)
                .unwrap_err()
                .to_string(),
            "the provisioning profile is for TEAM.com.example.app, not com.other.app"
        );
        assert_eq!(
            Profile::choose(&one, "com.example.app.Widget", true)
                .unwrap_err()
                .to_string(),
            "the provisioning profile is for TEAM.com.example.app, not com.example.app.Widget: \
             pass its profile with another --profile"
        );
        let two = [
            profile("app.mobileprovision", "TEAM.com.example.app"),
            profile("other.mobileprovision", "TEAM.com.example.other"),
        ];
        let error = Profile::choose(&two, "com.example.app.Widget", true)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("none of the provisioning profiles is for com.example.app.Widget")
                && error.contains("TEAM.com.example.app, TEAM.com.example.other"),
            "{error}"
        );
        let same = [
            profile("dev.mobileprovision", "TEAM.com.example.app"),
            profile("dist.mobileprovision", "TEAM.com.example.app"),
        ];
        let error = Profile::choose(&same, "com.example.app", false)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("are both provisioning profiles for com.example.app"),
            "{error}"
        );
    }

    #[test]
    fn a_bundle_is_signed_as_its_own_id_with_its_own_entitlements() {
        let all = profile("all.mobileprovision", "TEAM.*");
        let entitlements = all
            .entitlements(
                "com.example.app.Widget",
                plist::Dictionary::new(),
                "ios.extensions[0].entitlements",
            )
            .unwrap();
        let entitlements = entitlements.as_dictionary().unwrap();
        assert_eq!(
            entitlements["application-identifier"],
            plist::Value::String("TEAM.com.example.app.Widget".into())
        );
        assert_eq!(
            entitlements["aps-environment"],
            plist::Value::String("production".into())
        );
        let mut requested = plist::Dictionary::new();
        requested.insert("com.apple.developer.healthkit".into(), true.into());
        let error = all
            .entitlements(
                "com.example.app.Widget",
                requested,
                "ios.extensions[0].entitlements",
            )
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("(nsh.json ios.extensions[0].entitlements)"),
            "{error}"
        );
    }
}