aboutsummaryrefslogtreecommitdiff
path: root/tools/releasetools/test_sign_target_files_apks.py
blob: 7ac1cff0bb715e4d53f943edd5c0306b1e053957 (plain)
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
#
# Copyright (C) 2017 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import base64
import io
import os.path
import zipfile

import common
import test_utils
from sign_target_files_apks import (
    CheckApkAndApexKeysAvailable, EditTags, GetApkFileInfo, ParseAvbInfo,
    ReadApexKeysInfo, ReplaceCerts, RewriteAvbProps, RewriteProps,
    WriteOtacerts)


class SignTargetFilesApksTest(test_utils.ReleaseToolsTestCase):

  MAC_PERMISSIONS_XML = """<?xml version="1.0" encoding="iso-8859-1"?>
<policy>
  <signer signature="{}"><seinfo value="platform"/></signer>
  <signer signature="{}"><seinfo value="media"/></signer>
</policy>"""

  # Note that we test one apex with the partition tag, and another without to
  # make sure that new OTA tools can process an older target files package that
  # does not include the partition tag.

  # pylint: disable=line-too-long
  APEX_KEYS_TXT = """name="apex.apexd_test.apex" public_key="system/apex/apexd/apexd_testdata/com.android.apex.test_package.avbpubkey" private_key="system/apex/apexd/apexd_testdata/com.android.apex.test_package.pem" container_certificate="build/make/target/product/security/testkey.x509.pem" container_private_key="build/make/target/product/security/testkey.pk8" partition="system"
name="apex.apexd_test_different_app.apex" public_key="system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.avbpubkey" private_key="system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem" container_certificate="build/make/target/product/security/testkey.x509.pem" container_private_key="build/make/target/product/security/testkey.pk8"
"""

  def setUp(self):
    self.testdata_dir = test_utils.get_testdata_dir()

  def test_EditTags(self):
    self.assertEqual(EditTags('dev-keys'), ('release-keys'))
    self.assertEqual(EditTags('test-keys'), ('release-keys'))

    # Multiple tags.
    self.assertEqual(EditTags('abc,dev-keys,xyz'), ('abc,release-keys,xyz'))

    # Tags are sorted.
    self.assertEqual(EditTags('xyz,abc,dev-keys,xyz'), ('abc,release-keys,xyz'))

  def test_RewriteAvbProps(self):
    misc_info = {
      'avb_boot_add_hash_footer_args':
          ('--prop com.android.build.boot.os_version:R '
           '--prop com.android.build.boot.security_patch:2019-09-05'),
      'avb_init_boot_add_hash_footer_args':
          ('--prop com.android.build.boot.os_version:R '
           '--prop com.android.build.boot.security_patch:2019-09-05'),
      'avb_system_add_hashtree_footer_args':
          ('--prop com.android.build.system.os_version:R '
           '--prop com.android.build.system.security_patch:2019-09-05 '
           '--prop com.android.build.system.fingerprint:'
           'Android/aosp_taimen/taimen:R/QT/foo:userdebug/test-keys'),
      'avb_vendor_add_hashtree_footer_args':
          ('--prop com.android.build.vendor.os_version:R '
           '--prop com.android.build.vendor.security_patch:2019-09-05 '
           '--prop com.android.build.vendor.fingerprint:'
           'Android/aosp_taimen/taimen:R/QT/foo:userdebug/dev-keys'),
    }
    expected_dict = {
      'avb_boot_add_hash_footer_args':
          ('--prop com.android.build.boot.os_version:R '
           '--prop com.android.build.boot.security_patch:2019-09-05'),
      'avb_init_boot_add_hash_footer_args':
          ('--prop com.android.build.boot.os_version:R '
           '--prop com.android.build.boot.security_patch:2019-09-05'),
      'avb_system_add_hashtree_footer_args':
          ('--prop com.android.build.system.os_version:R '
           '--prop com.android.build.system.security_patch:2019-09-05 '
           '--prop com.android.build.system.fingerprint:'
           'Android/aosp_taimen/taimen:R/QT/foo:userdebug/release-keys'),
      'avb_vendor_add_hashtree_footer_args':
          ('--prop com.android.build.vendor.os_version:R '
           '--prop com.android.build.vendor.security_patch:2019-09-05 '
           '--prop com.android.build.vendor.fingerprint:'
           'Android/aosp_taimen/taimen:R/QT/foo:userdebug/release-keys'),
    }
    RewriteAvbProps(misc_info)
    self.assertDictEqual(expected_dict, misc_info)

  def test_RewriteProps(self):
    props = (
        ('', ''),
        ('ro.build.fingerprint=foo/bar/dev-keys',
         'ro.build.fingerprint=foo/bar/release-keys'),
        ('ro.build.thumbprint=foo/bar/dev-keys',
         'ro.build.thumbprint=foo/bar/release-keys'),
        ('ro.vendor.build.fingerprint=foo/bar/dev-keys',
         'ro.vendor.build.fingerprint=foo/bar/release-keys'),
        ('ro.vendor.build.thumbprint=foo/bar/dev-keys',
         'ro.vendor.build.thumbprint=foo/bar/release-keys'),
        ('ro.odm.build.fingerprint=foo/bar/test-keys',
         'ro.odm.build.fingerprint=foo/bar/release-keys'),
        ('ro.odm.build.thumbprint=foo/bar/test-keys',
         'ro.odm.build.thumbprint=foo/bar/release-keys'),
        ('ro.product.build.fingerprint=foo/bar/dev-keys',
         'ro.product.build.fingerprint=foo/bar/release-keys'),
        ('ro.product.build.thumbprint=foo/bar/dev-keys',
         'ro.product.build.thumbprint=foo/bar/release-keys'),
        ('ro.system_ext.build.fingerprint=foo/bar/test-keys',
         'ro.system_ext.build.fingerprint=foo/bar/release-keys'),
        ('ro.system_ext.build.thumbprint=foo/bar/test-keys',
         'ro.system_ext.build.thumbprint=foo/bar/release-keys'),
        ('# comment line 1', '# comment line 1'),
        ('ro.bootimage.build.fingerprint=foo/bar/dev-keys',
         'ro.bootimage.build.fingerprint=foo/bar/release-keys'),
        ('ro.build.description='
         'sailfish-user 8.0.0 OPR6.170623.012 4283428 dev-keys',
         'ro.build.description='
         'sailfish-user 8.0.0 OPR6.170623.012 4283428 release-keys'),
        ('ro.build.tags=dev-keys', 'ro.build.tags=release-keys'),
        ('ro.build.tags=test-keys', 'ro.build.tags=release-keys'),
        ('ro.system.build.tags=dev-keys',
         'ro.system.build.tags=release-keys'),
        ('ro.vendor.build.tags=dev-keys',
         'ro.vendor.build.tags=release-keys'),
        ('ro.odm.build.tags=dev-keys',
         'ro.odm.build.tags=release-keys'),
        ('ro.product.build.tags=dev-keys',
         'ro.product.build.tags=release-keys'),
        ('ro.system_ext.build.tags=dev-keys',
         'ro.system_ext.build.tags=release-keys'),
        ('# comment line 2', '# comment line 2'),
        ('ro.build.display.id=OPR6.170623.012 dev-keys',
         'ro.build.display.id=OPR6.170623.012'),
        ('# comment line 3', '# comment line 3'),
    )

    # Assert the case for each individual line.
    for prop, expected in props:
      self.assertEqual(expected + '\n', RewriteProps(prop))

    # Concatenate all the input lines.
    self.assertEqual(
        '\n'.join([prop[1] for prop in props]) + '\n',
        RewriteProps('\n'.join([prop[0] for prop in props])))

  def test_ReplaceCerts(self):
    cert1_path = os.path.join(self.testdata_dir, 'platform.x509.pem')
    with open(cert1_path) as cert1_fp:
      cert1 = cert1_fp.read()
    cert2_path = os.path.join(self.testdata_dir, 'media.x509.pem')
    with open(cert2_path) as cert2_fp:
      cert2 = cert2_fp.read()
    cert3_path = os.path.join(self.testdata_dir, 'testkey.x509.pem')
    with open(cert3_path) as cert3_fp:
      cert3 = cert3_fp.read()

    # Replace cert1 with cert3.
    input_xml = self.MAC_PERMISSIONS_XML.format(
        base64.b16encode(common.ParseCertificate(cert1)).lower(),
        base64.b16encode(common.ParseCertificate(cert2)).lower())

    output_xml = self.MAC_PERMISSIONS_XML.format(
        base64.b16encode(common.ParseCertificate(cert3)).lower(),
        base64.b16encode(common.ParseCertificate(cert2)).lower())

    common.OPTIONS.key_map = {
        cert1_path[:-9] : cert3_path[:-9],
    }

    self.assertEqual(output_xml, ReplaceCerts(input_xml))

  def test_ReplaceCerts_duplicateEntries(self):
    cert1_path = os.path.join(self.testdata_dir, 'platform.x509.pem')
    with open(cert1_path) as cert1_fp:
      cert1 = cert1_fp.read()
    cert2_path = os.path.join(self.testdata_dir, 'media.x509.pem')
    with open(cert2_path) as cert2_fp:
      cert2 = cert2_fp.read()

    # Replace cert1 with cert2, which leads to duplicate entries.
    input_xml = self.MAC_PERMISSIONS_XML.format(
        base64.b16encode(common.ParseCertificate(cert1)).lower(),
        base64.b16encode(common.ParseCertificate(cert2)).lower())

    common.OPTIONS.key_map = {
        cert1_path[:-9] : cert2_path[:-9],
    }
    self.assertRaises(AssertionError, ReplaceCerts, input_xml)

  def test_ReplaceCerts_skipNonExistentCerts(self):
    cert1_path = os.path.join(self.testdata_dir, 'platform.x509.pem')
    with open(cert1_path) as cert1_fp:
      cert1 = cert1_fp.read()
    cert2_path = os.path.join(self.testdata_dir, 'media.x509.pem')
    with open(cert2_path) as cert2_fp:
      cert2 = cert2_fp.read()
    cert3_path = os.path.join(self.testdata_dir, 'testkey.x509.pem')
    with open(cert3_path) as cert3_fp:
      cert3 = cert3_fp.read()

    input_xml = self.MAC_PERMISSIONS_XML.format(
        base64.b16encode(common.ParseCertificate(cert1)).lower(),
        base64.b16encode(common.ParseCertificate(cert2)).lower())

    output_xml = self.MAC_PERMISSIONS_XML.format(
        base64.b16encode(common.ParseCertificate(cert3)).lower(),
        base64.b16encode(common.ParseCertificate(cert2)).lower())

    common.OPTIONS.key_map = {
        cert1_path[:-9] : cert3_path[:-9],
        'non-existent' : cert3_path[:-9],
        cert2_path[:-9] : 'non-existent',
    }
    self.assertEqual(output_xml, ReplaceCerts(input_xml))

  def test_WriteOtacerts(self):
    certs = [
        os.path.join(self.testdata_dir, 'platform.x509.pem'),
        os.path.join(self.testdata_dir, 'media.x509.pem'),
        os.path.join(self.testdata_dir, 'testkey.x509.pem'),
    ]
    entry_name = 'SYSTEM/etc/security/otacerts.zip'
    output_file = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(output_file, 'w', allowZip64=True) as output_zip:
      WriteOtacerts(output_zip, entry_name, certs)
    with zipfile.ZipFile(output_file) as input_zip:
      self.assertIn(entry_name, input_zip.namelist())
      otacerts_file = io.BytesIO(input_zip.read(entry_name))
      with zipfile.ZipFile(otacerts_file) as otacerts_zip:
        self.assertEqual(3, len(otacerts_zip.namelist()))

  def test_CheckApkAndApexKeysAvailable(self):
    input_file = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(input_file, 'w', allowZip64=True) as input_zip:
      input_zip.writestr('SYSTEM/app/App1.apk', "App1-content")
      input_zip.writestr('SYSTEM/app/App2.apk.gz', "App2-content")

    apk_key_map = {
        'App1.apk' : 'key1',
        'App2.apk' : 'key2',
        'App3.apk' : 'key3',
    }
    with zipfile.ZipFile(input_file) as input_zip:
      CheckApkAndApexKeysAvailable(input_zip, apk_key_map, None, {})
      CheckApkAndApexKeysAvailable(input_zip, apk_key_map, '.gz', {})

      # 'App2.apk.gz' won't be considered as an APK.
      CheckApkAndApexKeysAvailable(input_zip, apk_key_map, None, {})
      CheckApkAndApexKeysAvailable(input_zip, apk_key_map, '.xz', {})

      del apk_key_map['App2.apk']
      self.assertRaises(
          AssertionError, CheckApkAndApexKeysAvailable, input_zip, apk_key_map,
          '.gz', {})

  def test_CheckApkAndApexKeysAvailable_invalidApexKeys(self):
    input_file = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(input_file, 'w', allowZip64=True) as input_zip:
      input_zip.writestr('SYSTEM/apex/Apex1.apex', "Apex1-content")
      input_zip.writestr('SYSTEM/apex/Apex2.apex', "Apex2-content")

    apk_key_map = {
        'Apex1.apex' : 'key1',
        'Apex2.apex' : 'key2',
        'Apex3.apex' : 'key3',
    }
    apex_keys = {
        'Apex1.apex' : ('payload-key1', 'container-key1', None),
        'Apex2.apex' : ('payload-key2', 'container-key2', None),
    }
    with zipfile.ZipFile(input_file) as input_zip:
      CheckApkAndApexKeysAvailable(input_zip, apk_key_map, None, apex_keys)

      # Fine to have both keys as PRESIGNED.
      apex_keys['Apex2.apex'] = ('PRESIGNED', 'PRESIGNED', None)
      CheckApkAndApexKeysAvailable(input_zip, apk_key_map, None, apex_keys)

      # Having only one of them as PRESIGNED is not allowed.
      apex_keys['Apex2.apex'] = ('payload-key2', 'PRESIGNED', None)
      self.assertRaises(
          AssertionError, CheckApkAndApexKeysAvailable, input_zip, apk_key_map,
          None, apex_keys)

      apex_keys['Apex2.apex'] = ('PRESIGNED', 'container-key1', None)
      self.assertRaises(
          AssertionError, CheckApkAndApexKeysAvailable, input_zip, apk_key_map,
          None, apex_keys)

  def test_GetApkFileInfo(self):
    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "PRODUCT/apps/Chats.apk", None, [])
    self.assertTrue(is_apk)
    self.assertFalse(is_compressed)
    self.assertFalse(should_be_skipped)

    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "PRODUCT/apps/Chats.apk", None, [])
    self.assertTrue(is_apk)
    self.assertFalse(is_compressed)
    self.assertFalse(should_be_skipped)

    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "PRODUCT/apps/Chats.dat", None, [])
    self.assertFalse(is_apk)
    self.assertFalse(is_compressed)
    self.assertFalse(should_be_skipped)

  def test_GetApkFileInfo_withCompressedApks(self):
    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "PRODUCT/apps/Chats.apk.gz", ".gz", [])
    self.assertTrue(is_apk)
    self.assertTrue(is_compressed)
    self.assertFalse(should_be_skipped)

    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "PRODUCT/apps/Chats.apk.gz", ".xz", [])
    self.assertFalse(is_apk)
    self.assertFalse(is_compressed)
    self.assertFalse(should_be_skipped)

    self.assertRaises(
        AssertionError, GetApkFileInfo, "PRODUCT/apps/Chats.apk", "", [])

    self.assertRaises(
        AssertionError, GetApkFileInfo, "PRODUCT/apps/Chats.apk", "apk", [])

  def test_GetApkFileInfo_withSkippedPrefixes(self):
    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "PRODUCT/preloads/apps/Chats.apk", None, set())
    self.assertTrue(is_apk)
    self.assertFalse(is_compressed)
    self.assertFalse(should_be_skipped)

    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "PRODUCT/preloads/apps/Chats.apk",
        None,
        set(["PRODUCT/preloads/"]))
    self.assertTrue(is_apk)
    self.assertFalse(is_compressed)
    self.assertTrue(should_be_skipped)

    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "SYSTEM_OTHER/preloads/apps/Chats.apk",
        None,
        set(["SYSTEM/preloads/", "SYSTEM_OTHER/preloads/"]))
    self.assertTrue(is_apk)
    self.assertFalse(is_compressed)
    self.assertTrue(should_be_skipped)

    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "SYSTEM_OTHER/preloads/apps/Chats.apk.gz",
        ".gz",
        set(["PRODUCT/prebuilts/", "SYSTEM_OTHER/preloads/"]))
    self.assertTrue(is_apk)
    self.assertTrue(is_compressed)
    self.assertTrue(should_be_skipped)

    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "SYSTEM_OTHER/preloads/apps/Chats.dat",
        None,
        set(["SYSTEM_OTHER/preloads/"]))
    self.assertFalse(is_apk)
    self.assertFalse(is_compressed)
    self.assertFalse(should_be_skipped)

  def test_GetApkFileInfo_checkSkippedPrefixesInput(self):
    # set
    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "SYSTEM_OTHER/preloads/apps/Chats.apk",
        None,
        set(["SYSTEM_OTHER/preloads/"]))
    self.assertTrue(is_apk)
    self.assertFalse(is_compressed)
    self.assertTrue(should_be_skipped)

    # tuple
    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "SYSTEM_OTHER/preloads/apps/Chats.apk",
        None,
        ("SYSTEM_OTHER/preloads/",))
    self.assertTrue(is_apk)
    self.assertFalse(is_compressed)
    self.assertTrue(should_be_skipped)

    # list
    (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
        "SYSTEM_OTHER/preloads/apps/Chats.apk",
        None,
        ["SYSTEM_OTHER/preloads/"])
    self.assertTrue(is_apk)
    self.assertFalse(is_compressed)
    self.assertTrue(should_be_skipped)

    # str is invalid.
    self.assertRaises(
        AssertionError, GetApkFileInfo, "SYSTEM_OTHER/preloads/apps/Chats.apk",
        None, "SYSTEM_OTHER/preloads/")

    # None is invalid.
    self.assertRaises(
        AssertionError, GetApkFileInfo, "SYSTEM_OTHER/preloads/apps/Chats.apk",
        None, None)

  def test_ReadApexKeysInfo(self):
    target_files = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(target_files, 'w', allowZip64=True) as target_files_zip:
      target_files_zip.writestr('META/apexkeys.txt', self.APEX_KEYS_TXT)

    with zipfile.ZipFile(target_files, allowZip64=True) as target_files_zip:
      keys_info = ReadApexKeysInfo(target_files_zip)

    self.assertEqual({
        'apex.apexd_test.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package.pem',
            'build/make/target/product/security/testkey', None),
        'apex.apexd_test_different_app.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem',
            'build/make/target/product/security/testkey', None),
        }, keys_info)

  def test_ReadApexKeysInfo_mismatchingContainerKeys(self):
    # Mismatching payload public / private keys.
    apex_keys = self.APEX_KEYS_TXT + (
        'name="apex.apexd_test_different_app2.apex" '
        'public_key="system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.avbpubkey" '
        'private_key="system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem" '
        'container_certificate="build/make/target/product/security/testkey.x509.pem" '
        'container_private_key="build/make/target/product/security/testkey2.pk8" '
        'partition="system"')
    target_files = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(target_files, 'w', allowZip64=True) as target_files_zip:
      target_files_zip.writestr('META/apexkeys.txt', apex_keys)

    with zipfile.ZipFile(target_files, allowZip64=True) as target_files_zip:
      self.assertRaises(ValueError, ReadApexKeysInfo, target_files_zip)

  def test_ReadApexKeysInfo_missingPayloadPrivateKey(self):
    # Invalid lines will be skipped.
    apex_keys = self.APEX_KEYS_TXT + (
        'name="apex.apexd_test_different_app2.apex" '
        'public_key="system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.avbpubkey" '
        'container_certificate="build/make/target/product/security/testkey.x509.pem" '
        'container_private_key="build/make/target/product/security/testkey.pk8"')
    target_files = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(target_files, 'w', allowZip64=True) as target_files_zip:
      target_files_zip.writestr('META/apexkeys.txt', apex_keys)

    with zipfile.ZipFile(target_files, allowZip64=True) as target_files_zip:
      keys_info = ReadApexKeysInfo(target_files_zip)

    self.assertEqual({
        'apex.apexd_test.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package.pem',
            'build/make/target/product/security/testkey', None),
        'apex.apexd_test_different_app.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem',
            'build/make/target/product/security/testkey', None),
        }, keys_info)

  def test_ReadApexKeysInfo_missingPayloadPublicKey(self):
    # Invalid lines will be skipped.
    apex_keys = self.APEX_KEYS_TXT + (
        'name="apex.apexd_test_different_app2.apex" '
        'private_key="system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem" '
        'container_certificate="build/make/target/product/security/testkey.x509.pem" '
        'container_private_key="build/make/target/product/security/testkey.pk8"')
    target_files = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(target_files, 'w', allowZip64=True) as target_files_zip:
      target_files_zip.writestr('META/apexkeys.txt', apex_keys)

    with zipfile.ZipFile(target_files, allowZip64=True) as target_files_zip:
      keys_info = ReadApexKeysInfo(target_files_zip)

    self.assertEqual({
        'apex.apexd_test.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package.pem',
            'build/make/target/product/security/testkey', None),
        'apex.apexd_test_different_app.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem',
            'build/make/target/product/security/testkey', None),
        }, keys_info)

  def test_ReadApexKeysInfo_presignedKeys(self):
    apex_keys = self.APEX_KEYS_TXT + (
        'name="apex.apexd_test_different_app2.apex" '
        'private_key="PRESIGNED" '
        'public_key="PRESIGNED" '
        'container_certificate="PRESIGNED" '
        'container_private_key="PRESIGNED"')
    target_files = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(target_files, 'w', allowZip64=True) as target_files_zip:
      target_files_zip.writestr('META/apexkeys.txt', apex_keys)

    with zipfile.ZipFile(target_files, allowZip64=True) as target_files_zip:
      keys_info = ReadApexKeysInfo(target_files_zip)

    self.assertEqual({
        'apex.apexd_test.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package.pem',
            'build/make/target/product/security/testkey', None),
        'apex.apexd_test_different_app.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem',
            'build/make/target/product/security/testkey', None),
        }, keys_info)

  def test_ReadApexKeysInfo_presignedKeys(self):
    apex_keys = self.APEX_KEYS_TXT + (
        'name="apex.apexd_test_different_app2.apex" '
        'private_key="PRESIGNED" '
        'public_key="PRESIGNED" '
        'container_certificate="PRESIGNED" '
        'container_private_key="PRESIGNED"')
    target_files = common.MakeTempFile(suffix='.zip')
    with zipfile.ZipFile(target_files, 'w', allowZip64=True) as target_files_zip:
      target_files_zip.writestr('META/apexkeys.txt', apex_keys)

    with zipfile.ZipFile(target_files, allowZip64=True) as target_files_zip:
      keys_info = ReadApexKeysInfo(target_files_zip)

    self.assertEqual({
        'apex.apexd_test.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package.pem',
            'build/make/target/product/security/testkey', None),
        'apex.apexd_test_different_app.apex': (
            'system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem',
            'build/make/target/product/security/testkey', None),
        }, keys_info)

  def test_ParseAvbInfo(self):
    avb_info_string = """
    Footer version:           1.0
    Image size:               9999999 bytes
    Original image size:      8888888 bytes
    VBMeta offset:            7777777
    VBMeta size:              1111 bytes
    --
    Minimum libavb version:   1.0
    Header Block:             222 bytes
    Authentication Block:     333 bytes
    Auxiliary Block:          888 bytes
    Public key (sha1):        abababababababababababababababababababab
    Algorithm:                SHA256_RSA2048
    Rollback Index:           0
    Flags:                    0
    Rollback Index Location:  0
    Release String:           'avbtool 1.3.0'
    Descriptors:
        Hashtree descriptor:
          Version of dm-verity:  1
          Image Size:            8888888 bytes
          Tree Offset:           8888888
          Tree Size:             44444 bytes
          Data Block Size:       4444 bytes
          Hash Block Size:       4444 bytes
          FEC num roots:         0
          FEC offset:            0
          FEC size:              0 bytes
          Hash Algorithm:        sha1
          Partition Name:        partition-name
          Salt:                  cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd
          Root Digest:           efefefefefefefefefefefefefefefefefef
          Flags:                 0
        Prop: prop.key -> 'prop.value'
    """

    self.assertEqual(
        {
            'Footer version': '1.0',
            'Image size': '9999999 bytes',
            'Original image size': '8888888 bytes',
            'VBMeta offset': '7777777',
            'VBMeta size': '1111 bytes',
            'Minimum libavb version': '1.0',
            'Header Block': '222 bytes',
            'Authentication Block': '333 bytes',
            'Auxiliary Block': '888 bytes',
            'Public key (sha1)': 'abababababababababababababababababababab',
            'Algorithm': 'SHA256_RSA2048',
            'Rollback Index': '0',
            'Flags': '0',
            'Rollback Index Location': '0',
            'Release String': "'avbtool 1.3.0'",
            'Descriptors': [
                {
                    'Hashtree descriptor': {
                        'Version of dm-verity': '1',
                        'Image Size': '8888888 bytes',
                        'Tree Offset': '8888888',
                        'Tree Size': '44444 bytes',
                        'Data Block Size': '4444 bytes',
                        'Hash Block Size': '4444 bytes',
                        'FEC num roots': '0',
                        'FEC offset': '0',
                        'FEC size': '0 bytes',
                        'Hash Algorithm': 'sha1',
                        'Partition Name': 'partition-name',
                        'Salt': 'cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd',
                        'Root Digest': 'efefefefefefefefefefefefefefefefefef',
                        'Flags': '0',
                    }
                },
                {
                    'Prop': {
                        'prop.key': 'prop.value',
                    }
                },
            ],
        },
        ParseAvbInfo(avb_info_string),
    )