ios-core 0.1.7

High-level device API, pairing transport, and discovery for iOS devices
Documentation
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Wire protocol for `com.apple.mobile.mobile_image_mounter`.
//!
//! Commands: LookupImage, ReceiveBytes, MountImage, QueryPersonalizationIdentifiers,
//!           QueryPersonalizationManifest (QueryNonce), Hangup
//!
//! Reference: go-ios/ios/imagemounter/imagemounter.go

use std::collections::HashMap;

use plist::Value;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};

pub const SERVICE_NAME: &str = "com.apple.mobile.mobile_image_mounter";

service_error!(
    ImageMounterError,
    #[error("device error: {0}")]
    DeviceError(String),
    #[error("TSS error: {0}")]
    Tss(String),
    #[error("download error: {0}")]
    Download(String),
);

/// High-level image mounter client.
pub struct ImageMounterClient<S> {
    stream: S,
}

impl<S: AsyncRead + AsyncWrite + Unpin + Send> ImageMounterClient<S> {
    pub fn new(stream: S) -> Self {
        Self { stream }
    }

    /// Return raw mounted image entries reported by mobile_image_mounter.
    pub async fn copy_devices(&mut self) -> Result<Vec<plist::Dictionary>, ImageMounterError> {
        let req = plist::Dictionary::from_iter([(
            "Command".to_string(),
            Value::String("CopyDevices".into()),
        )]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;

        match resp.get("EntryList") {
            Some(Value::Array(items)) => items
                .iter()
                .map(|value| {
                    value.as_dictionary().cloned().ok_or_else(|| {
                        ImageMounterError::Protocol("CopyDevices entry was not a dictionary".into())
                    })
                })
                .collect(),
            None => Ok(Vec::new()),
            Some(_) => Err(ImageMounterError::Protocol(
                "CopyDevices EntryList had unexpected type".into(),
            )),
        }
    }

    /// Check if a developer image is already mounted.
    pub async fn is_image_mounted(&mut self) -> Result<bool, ImageMounterError> {
        Ok(!self.lookup_image_signatures("Developer").await?.is_empty()
            || !self
                .lookup_image_signatures("Personalized")
                .await?
                .is_empty())
    }

    /// Return mounted image signatures for an image type.
    pub async fn lookup_image_signatures(
        &mut self,
        image_type: &str,
    ) -> Result<Vec<Vec<u8>>, ImageMounterError> {
        let req = plist::Dictionary::from_iter([
            ("Command".to_string(), Value::String("LookupImage".into())),
            ("ImageType".to_string(), Value::String(image_type.into())),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;

        match resp.get("ImageSignature") {
            Some(Value::Array(items)) => items
                .iter()
                .map(|value| {
                    value.as_data().map(|bytes| bytes.to_vec()).ok_or_else(|| {
                        ImageMounterError::Protocol(
                            "LookupImage ImageSignature entry was not data".into(),
                        )
                    })
                })
                .collect(),
            Some(Value::Data(bytes)) => Ok(vec![bytes.clone()]),
            None => Ok(Vec::new()),
            Some(_) => Err(ImageMounterError::Protocol(
                "LookupImage ImageSignature had unexpected type".into(),
            )),
        }
    }

    /// Mount a standard (pre-iOS 17) developer disk image.
    ///
    /// `image_bytes`: the DeveloperDiskImage.dmg contents
    /// `signature`: the DeveloperDiskImage.dmg.signature contents
    pub async fn mount_standard(
        &mut self,
        image_bytes: &[u8],
        signature: &[u8],
    ) -> Result<(), ImageMounterError> {
        // 1. Upload image via ReceiveBytes
        self.upload_image(image_bytes, signature).await?;

        // 2. Mount
        let mount_req = plist::Dictionary::from_iter([
            ("Command".to_string(), Value::String("MountImage".into())),
            ("ImageType".to_string(), Value::String("Developer".into())),
            (
                "ImagePath".to_string(),
                Value::String("/private/var/mobile/Media/PublicStaging/staging.dimage".into()),
            ),
            (
                "ImageSignature".to_string(),
                Value::Data(signature.to_vec()),
            ),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(mount_req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;
        Ok(())
    }

    /// Mount a personalized (iOS 17+) developer disk image.
    ///
    /// `trustcache`: the trust cache data
    /// `build_manifest`: the BuildManifest.plist bytes
    /// `image_bytes`: the personalized disk image
    /// `ticket`: the TSS ticket (ApImg4Ticket)
    pub async fn mount_personalized(
        &mut self,
        trustcache: &[u8],
        build_manifest: &[u8],
        image_bytes: &[u8],
        ticket: &[u8],
    ) -> Result<(), ImageMounterError> {
        // 1. Query personalization identifiers
        let ids = self.query_personalization_identifiers().await?;
        tracing::debug!(
            "personalization identifiers: {:?}",
            ids.keys().collect::<Vec<_>>()
        );

        // 2. Query nonce
        let nonce = self.query_nonce().await?;
        tracing::debug!("personalization nonce: {} bytes", nonce.len());

        // 3. Upload image
        self.upload_personalized_image(image_bytes, trustcache, build_manifest)
            .await?;

        // 4. Mount with ticket
        let mount_req = plist::Dictionary::from_iter([
            ("Command".to_string(), Value::String("MountImage".into())),
            (
                "ImageType".to_string(),
                Value::String("Personalized".into()),
            ),
            (
                "ImagePath".to_string(),
                Value::String("/private/var/mobile/Media/PublicStaging/staging.dimage".into()),
            ),
            ("ImageSignature".to_string(), Value::Data(ticket.to_vec())),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(mount_req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;
        Ok(())
    }

    /// Query personalization identifiers (board ID, chip ID, etc.)
    pub async fn query_personalization_identifiers(
        &mut self,
    ) -> Result<HashMap<String, Value>, ImageMounterError> {
        self.query_personalization_identifiers_with_type("DeveloperDiskImage")
            .await
    }

    /// Query personalization identifiers for a specific personalized image type.
    pub async fn query_personalization_identifiers_with_type(
        &mut self,
        personalized_image_type: &str,
    ) -> Result<HashMap<String, Value>, ImageMounterError> {
        let req = plist::Dictionary::from_iter([
            (
                "Command".to_string(),
                Value::String("QueryPersonalizationIdentifiers".into()),
            ),
            (
                "PersonalizedImageType".to_string(),
                Value::String(personalized_image_type.into()),
            ),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;

        let ids = resp
            .get("PersonalizationIdentifiers")
            .and_then(|v| v.as_dictionary())
            .ok_or_else(|| {
                ImageMounterError::Protocol("missing PersonalizationIdentifiers".into())
            })?;

        Ok(ids.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
    }

    /// Query the personalization manifest associated with a mounted personalized image.
    pub async fn query_personalization_manifest(
        &mut self,
        personalized_image_type: &str,
        image_signature: &[u8],
    ) -> Result<Vec<u8>, ImageMounterError> {
        let req = plist::Dictionary::from_iter([
            (
                "Command".to_string(),
                Value::String("QueryPersonalizationManifest".into()),
            ),
            (
                "PersonalizedImageType".to_string(),
                Value::String(personalized_image_type.into()),
            ),
            (
                "ImageType".to_string(),
                Value::String(personalized_image_type.into()),
            ),
            (
                "ImageSignature".to_string(),
                Value::Data(image_signature.to_vec()),
            ),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;

        let manifest = resp
            .get("ImageSignature")
            .and_then(|v| v.as_data())
            .ok_or_else(|| ImageMounterError::Protocol("missing ImageSignature".into()))?;

        Ok(manifest.to_vec())
    }

    /// Query the personalization nonce.
    pub async fn query_nonce(&mut self) -> Result<Vec<u8>, ImageMounterError> {
        self.query_nonce_with_type("DeveloperDiskImage").await
    }

    /// Query the personalization nonce for a specific personalized image type.
    pub async fn query_nonce_with_type(
        &mut self,
        personalized_image_type: &str,
    ) -> Result<Vec<u8>, ImageMounterError> {
        let req = plist::Dictionary::from_iter([
            ("Command".to_string(), Value::String("QueryNonce".into())),
            (
                "PersonalizedImageType".to_string(),
                Value::String(personalized_image_type.into()),
            ),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;

        let nonce = resp
            .get("PersonalizationNonce")
            .and_then(|v| v.as_data())
            .ok_or_else(|| ImageMounterError::Protocol("missing PersonalizationNonce".into()))?;

        Ok(nonce.to_vec())
    }

    /// Query whether developer mode is enabled on the device.
    pub async fn query_developer_mode_status(&mut self) -> Result<bool, ImageMounterError> {
        let req = plist::Dictionary::from_iter([(
            "Command".to_string(),
            Value::String("QueryDeveloperModeStatus".into()),
        )]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;

        Ok(resp
            .get("DeveloperModeStatus")
            .and_then(|v| v.as_boolean())
            .unwrap_or(false))
    }

    /// Unmount a mounted image at a mount path such as `/Developer` or `/System/Developer`.
    pub async fn unmount_image(&mut self, mount_path: &str) -> Result<(), ImageMounterError> {
        let req = plist::Dictionary::from_iter([
            ("Command".to_string(), Value::String("UnmountImage".into())),
            ("MountPath".to_string(), Value::String(mount_path.into())),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;
        check_error(&resp)?;
        Ok(())
    }

    async fn upload_image(
        &mut self,
        image_bytes: &[u8],
        signature: &[u8],
    ) -> Result<(), ImageMounterError> {
        let req = plist::Dictionary::from_iter([
            ("Command".to_string(), Value::String("ReceiveBytes".into())),
            ("ImageType".to_string(), Value::String("Developer".into())),
            (
                "ImageSize".to_string(),
                Value::Integer((image_bytes.len() as i64).into()),
            ),
            (
                "ImageSignature".to_string(),
                Value::Data(signature.to_vec()),
            ),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;

        let status = resp.get("Status").and_then(|v| v.as_string()).unwrap_or("");

        if status == "ReceiveBytesAck" {
            // Device wants the image bytes
            self.stream.write_all(image_bytes).await?;
            self.stream.flush().await?;
            let resp2 = recv_plist(&mut self.stream).await?;
            check_error(&resp2)?;
        } else {
            check_error(&resp)?;
        }
        Ok(())
    }

    async fn upload_personalized_image(
        &mut self,
        image_bytes: &[u8],
        trustcache: &[u8],
        build_manifest: &[u8],
    ) -> Result<(), ImageMounterError> {
        let req = plist::Dictionary::from_iter([
            ("Command".to_string(), Value::String("ReceiveBytes".into())),
            (
                "ImageType".to_string(),
                Value::String("Personalized".into()),
            ),
            (
                "ImageSize".to_string(),
                Value::Integer((image_bytes.len() as i64).into()),
            ),
            (
                "ImageTrustCache".to_string(),
                Value::Data(trustcache.to_vec()),
            ),
            (
                "BuildManifest".to_string(),
                Value::Data(build_manifest.to_vec()),
            ),
        ]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        let resp = recv_plist(&mut self.stream).await?;

        let status = resp.get("Status").and_then(|v| v.as_string()).unwrap_or("");

        if status == "ReceiveBytesAck" {
            self.stream.write_all(image_bytes).await?;
            self.stream.flush().await?;
            let resp2 = recv_plist(&mut self.stream).await?;
            check_error(&resp2)?;
        } else {
            check_error(&resp)?;
        }
        Ok(())
    }

    /// Send Hangup to close the session.
    pub async fn hangup(&mut self) -> Result<(), ImageMounterError> {
        let req =
            plist::Dictionary::from_iter([("Command".to_string(), Value::String("Hangup".into()))]);
        send_plist(&mut self.stream, &Value::Dictionary(req)).await?;
        Ok(())
    }
}

fn check_error(resp: &plist::Dictionary) -> Result<(), ImageMounterError> {
    if let Some(err) = resp.get("Error") {
        let msg = err.as_string().unwrap_or("unknown error");
        return Err(ImageMounterError::DeviceError(msg.to_string()));
    }
    Ok(())
}

// ── plist framing (4-byte BE length prefix) ──────────────────────────────────

async fn send_plist<S: AsyncWrite + Unpin>(
    stream: &mut S,
    value: &Value,
) -> Result<(), ImageMounterError> {
    let mut buf = Vec::new();
    plist::to_writer_xml(&mut buf, value)?;
    stream.write_all(&(buf.len() as u32).to_be_bytes()).await?;
    stream.write_all(&buf).await?;
    stream.flush().await?;
    Ok(())
}

async fn recv_plist<S: AsyncRead + Unpin>(
    stream: &mut S,
) -> Result<plist::Dictionary, ImageMounterError> {
    let mut len_buf = [0u8; 4];
    stream.read_exact(&mut len_buf).await?;
    let len = u32::from_be_bytes(len_buf) as usize;
    const MAX_PLIST_SIZE: usize = 4 * 1024 * 1024;
    if len > MAX_PLIST_SIZE {
        return Err(ImageMounterError::Protocol(format!(
            "plist length {len} exceeds maximum of {MAX_PLIST_SIZE}"
        )));
    }
    let mut buf = vec![0u8; len];
    stream.read_exact(&mut buf).await?;
    let val: plist::Value = plist::from_bytes(&buf)?;
    val.into_dictionary()
        .ok_or_else(|| ImageMounterError::Protocol("expected plist dictionary".into()))
}

#[cfg(test)]
mod tests {
    use crate::test_util::MockStream;

    use super::*;

    #[tokio::test]
    async fn query_developer_mode_status_roundtrips_boolean() {
        let response = Value::Dictionary(plist::Dictionary::from_iter([(
            "DeveloperModeStatus".to_string(),
            Value::Boolean(true),
        )]));
        let mut stream = MockStream::with_response(response);
        let mut client = ImageMounterClient::new(&mut stream);

        let enabled = client.query_developer_mode_status().await.unwrap();
        assert!(enabled);

        let len = u32::from_be_bytes(stream.written[..4].try_into().unwrap()) as usize;
        let payload = &stream.written[4..4 + len];
        let dict: plist::Dictionary = plist::from_bytes(payload).unwrap();
        assert_eq!(
            dict.get("Command").and_then(|v| v.as_string()),
            Some("QueryDeveloperModeStatus")
        );
    }

    #[tokio::test]
    async fn lookup_image_signatures_roundtrips_data_array() {
        let response = Value::Dictionary(plist::Dictionary::from_iter([(
            "ImageSignature".to_string(),
            Value::Array(vec![Value::Data(vec![0xde, 0xad, 0xbe, 0xef])]),
        )]));
        let mut stream = MockStream::with_response(response);
        let mut client = ImageMounterClient::new(&mut stream);

        let signatures = client.lookup_image_signatures("Developer").await.unwrap();
        assert_eq!(signatures, vec![vec![0xde, 0xad, 0xbe, 0xef]]);

        let len = u32::from_be_bytes(stream.written[..4].try_into().unwrap()) as usize;
        let payload = &stream.written[4..4 + len];
        let dict: plist::Dictionary = plist::from_bytes(payload).unwrap();
        assert_eq!(
            dict.get("Command").and_then(|v| v.as_string()),
            Some("LookupImage")
        );
        assert_eq!(
            dict.get("ImageType").and_then(|v| v.as_string()),
            Some("Developer")
        );
    }

    #[tokio::test]
    async fn is_image_mounted_checks_both_image_types() {
        let mut stream = MockStream::with_responses(vec![
            Value::Dictionary(plist::Dictionary::new()),
            Value::Dictionary(plist::Dictionary::from_iter([(
                "ImageSignature".to_string(),
                Value::Array(vec![Value::Data(vec![1, 2, 3])]),
            )])),
        ]);
        let mut client = ImageMounterClient::new(&mut stream);

        let mounted = client.is_image_mounted().await.unwrap();
        assert!(mounted);
    }

    #[tokio::test]
    async fn unmount_image_sends_mount_path() {
        let response = Value::Dictionary(plist::Dictionary::new());
        let mut stream = MockStream::with_response(response);
        let mut client = ImageMounterClient::new(&mut stream);

        client.unmount_image("/System/Developer").await.unwrap();

        let len = u32::from_be_bytes(stream.written[..4].try_into().unwrap()) as usize;
        let payload = &stream.written[4..4 + len];
        let dict: plist::Dictionary = plist::from_bytes(payload).unwrap();
        assert_eq!(
            dict.get("Command").and_then(|v| v.as_string()),
            Some("UnmountImage")
        );
        assert_eq!(
            dict.get("MountPath").and_then(|v| v.as_string()),
            Some("/System/Developer")
        );
    }

    #[tokio::test]
    async fn query_nonce_uses_query_nonce_command_and_personalization_nonce() {
        let response = Value::Dictionary(plist::Dictionary::from_iter([(
            "PersonalizationNonce".to_string(),
            Value::Data(vec![0xde, 0xad, 0xbe, 0xef]),
        )]));
        let mut stream = MockStream::with_response(response);
        let mut client = ImageMounterClient::new(&mut stream);

        let nonce = client.query_nonce().await.unwrap();
        assert_eq!(nonce, vec![0xde, 0xad, 0xbe, 0xef]);

        let len = u32::from_be_bytes(stream.written[..4].try_into().unwrap()) as usize;
        let payload = &stream.written[4..4 + len];
        let dict: plist::Dictionary = plist::from_bytes(payload).unwrap();
        assert_eq!(
            dict.get("Command").and_then(|v| v.as_string()),
            Some("QueryNonce")
        );
        assert_eq!(
            dict.get("PersonalizedImageType")
                .and_then(|v| v.as_string()),
            Some("DeveloperDiskImage")
        );
    }

    #[tokio::test]
    async fn copy_devices_roundtrips_entry_list() {
        let response = Value::Dictionary(plist::Dictionary::from_iter([(
            "EntryList".to_string(),
            Value::Array(vec![Value::Dictionary(plist::Dictionary::from_iter([
                (
                    "ImageType".to_string(),
                    Value::String("Personalized".into()),
                ),
                ("ImageSignature".to_string(), Value::Data(vec![0xaa, 0xbb])),
            ]))]),
        )]));
        let mut stream = MockStream::with_response(response);
        let mut client = ImageMounterClient::new(&mut stream);

        let entries = client.copy_devices().await.unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0].get("ImageType").and_then(|v| v.as_string()),
            Some("Personalized")
        );
        assert_eq!(
            entries[0].get("ImageSignature").and_then(|v| v.as_data()),
            Some([0xaa, 0xbb].as_slice())
        );

        let len = u32::from_be_bytes(stream.written[..4].try_into().unwrap()) as usize;
        let payload = &stream.written[4..4 + len];
        let dict: plist::Dictionary = plist::from_bytes(payload).unwrap();
        assert_eq!(
            dict.get("Command").and_then(|v| v.as_string()),
            Some("CopyDevices")
        );
    }

    #[tokio::test]
    async fn query_personalization_manifest_roundtrips_request_and_manifest_bytes() {
        let response = Value::Dictionary(plist::Dictionary::from_iter([(
            "ImageSignature".to_string(),
            Value::Data(vec![0xfa, 0xce]),
        )]));
        let mut stream = MockStream::with_response(response);
        let mut client = ImageMounterClient::new(&mut stream);

        let manifest = client
            .query_personalization_manifest("DeveloperDiskImage", &[0xaa, 0xbb])
            .await
            .unwrap();
        assert_eq!(manifest, vec![0xfa, 0xce]);

        let len = u32::from_be_bytes(stream.written[..4].try_into().unwrap()) as usize;
        let payload = &stream.written[4..4 + len];
        let dict: plist::Dictionary = plist::from_bytes(payload).unwrap();
        assert_eq!(
            dict.get("Command").and_then(|v| v.as_string()),
            Some("QueryPersonalizationManifest")
        );
        assert_eq!(
            dict.get("PersonalizedImageType")
                .and_then(|v| v.as_string()),
            Some("DeveloperDiskImage")
        );
        assert_eq!(
            dict.get("ImageType").and_then(|v| v.as_string()),
            Some("DeveloperDiskImage")
        );
        assert_eq!(
            dict.get("ImageSignature").and_then(|v| v.as_data()),
            Some([0xaa, 0xbb].as_slice())
        );
    }

    #[tokio::test]
    async fn query_nonce_with_custom_image_type_uses_provided_personalized_image_type() {
        let response = Value::Dictionary(plist::Dictionary::from_iter([(
            "PersonalizationNonce".to_string(),
            Value::Data(vec![0xde, 0xad]),
        )]));
        let mut stream = MockStream::with_response(response);
        let mut client = ImageMounterClient::new(&mut stream);

        let nonce = client.query_nonce_with_type("Cryptex").await.unwrap();
        assert_eq!(nonce, vec![0xde, 0xad]);

        let len = u32::from_be_bytes(stream.written[..4].try_into().unwrap()) as usize;
        let payload = &stream.written[4..4 + len];
        let dict: plist::Dictionary = plist::from_bytes(payload).unwrap();
        assert_eq!(
            dict.get("Command").and_then(|v| v.as_string()),
            Some("QueryNonce")
        );
        assert_eq!(
            dict.get("PersonalizedImageType")
                .and_then(|v| v.as_string()),
            Some("Cryptex")
        );
    }

    #[tokio::test]
    async fn query_personalization_identifiers_with_custom_type_uses_provided_image_type() {
        let response = Value::Dictionary(plist::Dictionary::from_iter([(
            "PersonalizationIdentifiers".to_string(),
            Value::Dictionary(plist::Dictionary::from_iter([(
                "BoardId".to_string(),
                Value::Integer(12.into()),
            )])),
        )]));
        let mut stream = MockStream::with_response(response);
        let mut client = ImageMounterClient::new(&mut stream);

        let identifiers = client
            .query_personalization_identifiers_with_type("Cryptex")
            .await
            .unwrap();
        assert_eq!(
            identifiers
                .get("BoardId")
                .and_then(|v| v.as_unsigned_integer()),
            Some(12)
        );

        let len = u32::from_be_bytes(stream.written[..4].try_into().unwrap()) as usize;
        let payload = &stream.written[4..4 + len];
        let dict: plist::Dictionary = plist::from_bytes(payload).unwrap();
        assert_eq!(
            dict.get("Command").and_then(|v| v.as_string()),
            Some("QueryPersonalizationIdentifiers")
        );
        assert_eq!(
            dict.get("PersonalizedImageType")
                .and_then(|v| v.as_string()),
            Some("Cryptex")
        );
    }
}