blob: e472363ad95dc18f5197d6ee0504bb86c70a99fc [file] [log] [blame]
Tao Bao481bab82017-12-21 11:23:09 -08001#
2# Copyright (C) 2018 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import copy
Tao Baoc7b403a2018-01-30 18:19:04 -080018import os
Tao Baofabe0832018-01-17 15:52:28 -080019import os.path
Tao Baob6304672018-03-08 16:28:33 -080020import subprocess
Tao Bao481bab82017-12-21 11:23:09 -080021import unittest
Tao Baoc7b403a2018-01-30 18:19:04 -080022import zipfile
Tao Bao481bab82017-12-21 11:23:09 -080023
24import common
Tao Bao04e1f012018-02-04 12:13:35 -080025import test_utils
Tao Bao481bab82017-12-21 11:23:09 -080026from ota_from_target_files import (
Tao Bao3bf8c652018-03-16 12:59:42 -070027 _LoadOemDicts, AbOtaPropertyFiles, BuildInfo, FinalizeMetadata,
28 GetPackageMetadata, GetTargetFilesZipForSecondaryImages,
Tao Baoc0746f42018-02-21 13:17:22 -080029 GetTargetFilesZipWithoutPostinstallConfig, NonAbOtaPropertyFiles,
Tao Bao69203522018-03-08 16:09:01 -080030 Payload, PayloadSigner, POSTINSTALL_CONFIG, PropertyFiles,
31 StreamingPropertyFiles, WriteFingerprintAssertion)
Tao Baofabe0832018-01-17 15:52:28 -080032
33
Tao Baof7140c02018-01-30 17:09:24 -080034def construct_target_files(secondary=False):
35 """Returns a target-files.zip file for generating OTA packages."""
36 target_files = common.MakeTempFile(prefix='target_files-', suffix='.zip')
37 with zipfile.ZipFile(target_files, 'w') as target_files_zip:
38 # META/update_engine_config.txt
39 target_files_zip.writestr(
40 'META/update_engine_config.txt',
41 "PAYLOAD_MAJOR_VERSION=2\nPAYLOAD_MINOR_VERSION=4\n")
42
Tao Bao15a146a2018-02-21 16:06:59 -080043 # META/postinstall_config.txt
44 target_files_zip.writestr(
45 POSTINSTALL_CONFIG,
46 '\n'.join([
47 "RUN_POSTINSTALL_system=true",
48 "POSTINSTALL_PATH_system=system/bin/otapreopt_script",
49 "FILESYSTEM_TYPE_system=ext4",
50 "POSTINSTALL_OPTIONAL_system=true",
51 ]))
52
Tao Bao5277d102018-04-17 23:47:21 -070053 ab_partitions = [
54 ('IMAGES', 'boot'),
55 ('IMAGES', 'system'),
56 ('IMAGES', 'vendor'),
57 ('RADIO', 'bootloader'),
58 ('RADIO', 'modem'),
59 ]
Tao Baof7140c02018-01-30 17:09:24 -080060 # META/ab_partitions.txt
Tao Baof7140c02018-01-30 17:09:24 -080061 target_files_zip.writestr(
62 'META/ab_partitions.txt',
Tao Bao5277d102018-04-17 23:47:21 -070063 '\n'.join([partition[1] for partition in ab_partitions]))
Tao Baof7140c02018-01-30 17:09:24 -080064
65 # Create dummy images for each of them.
Tao Bao5277d102018-04-17 23:47:21 -070066 for path, partition in ab_partitions:
67 target_files_zip.writestr(
68 '{}/{}.img'.format(path, partition),
69 os.urandom(len(partition)))
Tao Baof7140c02018-01-30 17:09:24 -080070
Tao Bao5277d102018-04-17 23:47:21 -070071 # system_other shouldn't appear in META/ab_partitions.txt.
Tao Baof7140c02018-01-30 17:09:24 -080072 if secondary:
73 target_files_zip.writestr('IMAGES/system_other.img',
74 os.urandom(len("system_other")))
75
76 return target_files
77
78
Tao Bao481bab82017-12-21 11:23:09 -080079class MockScriptWriter(object):
80 """A class that mocks edify_generator.EdifyGenerator.
81
82 It simply pushes the incoming arguments onto script stack, which is to assert
83 the calls to EdifyGenerator functions.
84 """
85
86 def __init__(self):
87 self.script = []
88
89 def Mount(self, *args):
90 self.script.append(('Mount',) + args)
91
92 def AssertDevice(self, *args):
93 self.script.append(('AssertDevice',) + args)
94
95 def AssertOemProperty(self, *args):
96 self.script.append(('AssertOemProperty',) + args)
97
98 def AssertFingerprintOrThumbprint(self, *args):
99 self.script.append(('AssertFingerprintOrThumbprint',) + args)
100
101 def AssertSomeFingerprint(self, *args):
102 self.script.append(('AssertSomeFingerprint',) + args)
103
104 def AssertSomeThumbprint(self, *args):
105 self.script.append(('AssertSomeThumbprint',) + args)
106
107
108class BuildInfoTest(unittest.TestCase):
109
110 TEST_INFO_DICT = {
111 'build.prop' : {
112 'ro.product.device' : 'product-device',
113 'ro.product.name' : 'product-name',
114 'ro.build.fingerprint' : 'build-fingerprint',
115 'ro.build.foo' : 'build-foo',
116 },
117 'vendor.build.prop' : {
118 'ro.vendor.build.fingerprint' : 'vendor-build-fingerprint',
119 },
120 'property1' : 'value1',
121 'property2' : 4096,
122 }
123
124 TEST_INFO_DICT_USES_OEM_PROPS = {
125 'build.prop' : {
126 'ro.product.name' : 'product-name',
127 'ro.build.thumbprint' : 'build-thumbprint',
128 'ro.build.bar' : 'build-bar',
129 },
130 'vendor.build.prop' : {
131 'ro.vendor.build.fingerprint' : 'vendor-build-fingerprint',
132 },
133 'property1' : 'value1',
134 'property2' : 4096,
135 'oem_fingerprint_properties' : 'ro.product.device ro.product.brand',
136 }
137
138 TEST_OEM_DICTS = [
139 {
140 'ro.product.brand' : 'brand1',
141 'ro.product.device' : 'device1',
142 },
143 {
144 'ro.product.brand' : 'brand2',
145 'ro.product.device' : 'device2',
146 },
147 {
148 'ro.product.brand' : 'brand3',
149 'ro.product.device' : 'device3',
150 },
151 ]
152
153 def test_init(self):
154 target_info = BuildInfo(self.TEST_INFO_DICT, None)
155 self.assertEqual('product-device', target_info.device)
156 self.assertEqual('build-fingerprint', target_info.fingerprint)
157 self.assertFalse(target_info.is_ab)
158 self.assertIsNone(target_info.oem_props)
159
160 def test_init_with_oem_props(self):
161 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
162 self.TEST_OEM_DICTS)
163 self.assertEqual('device1', target_info.device)
164 self.assertEqual('brand1/product-name/device1:build-thumbprint',
165 target_info.fingerprint)
166
167 # Swap the order in oem_dicts, which would lead to different BuildInfo.
168 oem_dicts = copy.copy(self.TEST_OEM_DICTS)
169 oem_dicts[0], oem_dicts[2] = oem_dicts[2], oem_dicts[0]
170 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS, oem_dicts)
171 self.assertEqual('device3', target_info.device)
172 self.assertEqual('brand3/product-name/device3:build-thumbprint',
173 target_info.fingerprint)
174
175 # Missing oem_dict should be rejected.
176 self.assertRaises(AssertionError, BuildInfo,
177 self.TEST_INFO_DICT_USES_OEM_PROPS, None)
178
179 def test___getitem__(self):
180 target_info = BuildInfo(self.TEST_INFO_DICT, None)
181 self.assertEqual('value1', target_info['property1'])
182 self.assertEqual(4096, target_info['property2'])
183 self.assertEqual('build-foo', target_info['build.prop']['ro.build.foo'])
184
185 def test___getitem__with_oem_props(self):
186 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
187 self.TEST_OEM_DICTS)
188 self.assertEqual('value1', target_info['property1'])
189 self.assertEqual(4096, target_info['property2'])
190 self.assertRaises(KeyError,
191 lambda: target_info['build.prop']['ro.build.foo'])
192
193 def test_get(self):
194 target_info = BuildInfo(self.TEST_INFO_DICT, None)
195 self.assertEqual('value1', target_info.get('property1'))
196 self.assertEqual(4096, target_info.get('property2'))
197 self.assertEqual(4096, target_info.get('property2', 1024))
198 self.assertEqual(1024, target_info.get('property-nonexistent', 1024))
199 self.assertEqual('build-foo', target_info.get('build.prop')['ro.build.foo'])
200
201 def test_get_with_oem_props(self):
202 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
203 self.TEST_OEM_DICTS)
204 self.assertEqual('value1', target_info.get('property1'))
205 self.assertEqual(4096, target_info.get('property2'))
206 self.assertEqual(4096, target_info.get('property2', 1024))
207 self.assertEqual(1024, target_info.get('property-nonexistent', 1024))
208 self.assertIsNone(target_info.get('build.prop').get('ro.build.foo'))
209 self.assertRaises(KeyError,
210 lambda: target_info.get('build.prop')['ro.build.foo'])
211
212 def test_GetBuildProp(self):
213 target_info = BuildInfo(self.TEST_INFO_DICT, None)
214 self.assertEqual('build-foo', target_info.GetBuildProp('ro.build.foo'))
215 self.assertRaises(common.ExternalError, target_info.GetBuildProp,
216 'ro.build.nonexistent')
217
218 def test_GetBuildProp_with_oem_props(self):
219 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
220 self.TEST_OEM_DICTS)
221 self.assertEqual('build-bar', target_info.GetBuildProp('ro.build.bar'))
222 self.assertRaises(common.ExternalError, target_info.GetBuildProp,
223 'ro.build.nonexistent')
224
225 def test_GetVendorBuildProp(self):
226 target_info = BuildInfo(self.TEST_INFO_DICT, None)
227 self.assertEqual('vendor-build-fingerprint',
228 target_info.GetVendorBuildProp(
229 'ro.vendor.build.fingerprint'))
230 self.assertRaises(common.ExternalError, target_info.GetVendorBuildProp,
231 'ro.build.nonexistent')
232
233 def test_GetVendorBuildProp_with_oem_props(self):
234 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
235 self.TEST_OEM_DICTS)
236 self.assertEqual('vendor-build-fingerprint',
237 target_info.GetVendorBuildProp(
238 'ro.vendor.build.fingerprint'))
239 self.assertRaises(common.ExternalError, target_info.GetVendorBuildProp,
240 'ro.build.nonexistent')
241
242 def test_WriteMountOemScript(self):
243 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
244 self.TEST_OEM_DICTS)
245 script_writer = MockScriptWriter()
246 target_info.WriteMountOemScript(script_writer)
247 self.assertEqual([('Mount', '/oem', None)], script_writer.script)
248
249 def test_WriteDeviceAssertions(self):
250 target_info = BuildInfo(self.TEST_INFO_DICT, None)
251 script_writer = MockScriptWriter()
252 target_info.WriteDeviceAssertions(script_writer, False)
253 self.assertEqual([('AssertDevice', 'product-device')], script_writer.script)
254
255 def test_WriteDeviceAssertions_with_oem_props(self):
256 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
257 self.TEST_OEM_DICTS)
258 script_writer = MockScriptWriter()
259 target_info.WriteDeviceAssertions(script_writer, False)
260 self.assertEqual(
261 [
262 ('AssertOemProperty', 'ro.product.device',
263 ['device1', 'device2', 'device3'], False),
264 ('AssertOemProperty', 'ro.product.brand',
265 ['brand1', 'brand2', 'brand3'], False),
266 ],
267 script_writer.script)
268
269 def test_WriteFingerprintAssertion_without_oem_props(self):
270 target_info = BuildInfo(self.TEST_INFO_DICT, None)
271 source_info_dict = copy.deepcopy(self.TEST_INFO_DICT)
272 source_info_dict['build.prop']['ro.build.fingerprint'] = (
273 'source-build-fingerprint')
274 source_info = BuildInfo(source_info_dict, None)
275
276 script_writer = MockScriptWriter()
277 WriteFingerprintAssertion(script_writer, target_info, source_info)
278 self.assertEqual(
279 [('AssertSomeFingerprint', 'source-build-fingerprint',
280 'build-fingerprint')],
281 script_writer.script)
282
283 def test_WriteFingerprintAssertion_with_source_oem_props(self):
284 target_info = BuildInfo(self.TEST_INFO_DICT, None)
285 source_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
286 self.TEST_OEM_DICTS)
287
288 script_writer = MockScriptWriter()
289 WriteFingerprintAssertion(script_writer, target_info, source_info)
290 self.assertEqual(
291 [('AssertFingerprintOrThumbprint', 'build-fingerprint',
292 'build-thumbprint')],
293 script_writer.script)
294
295 def test_WriteFingerprintAssertion_with_target_oem_props(self):
296 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
297 self.TEST_OEM_DICTS)
298 source_info = BuildInfo(self.TEST_INFO_DICT, None)
299
300 script_writer = MockScriptWriter()
301 WriteFingerprintAssertion(script_writer, target_info, source_info)
302 self.assertEqual(
303 [('AssertFingerprintOrThumbprint', 'build-fingerprint',
304 'build-thumbprint')],
305 script_writer.script)
306
307 def test_WriteFingerprintAssertion_with_both_oem_props(self):
308 target_info = BuildInfo(self.TEST_INFO_DICT_USES_OEM_PROPS,
309 self.TEST_OEM_DICTS)
310 source_info_dict = copy.deepcopy(self.TEST_INFO_DICT_USES_OEM_PROPS)
311 source_info_dict['build.prop']['ro.build.thumbprint'] = (
312 'source-build-thumbprint')
313 source_info = BuildInfo(source_info_dict, self.TEST_OEM_DICTS)
314
315 script_writer = MockScriptWriter()
316 WriteFingerprintAssertion(script_writer, target_info, source_info)
317 self.assertEqual(
318 [('AssertSomeThumbprint', 'build-thumbprint',
319 'source-build-thumbprint')],
320 script_writer.script)
321
322
323class LoadOemDictsTest(unittest.TestCase):
324
325 def tearDown(self):
326 common.Cleanup()
327
328 def test_NoneDict(self):
329 self.assertIsNone(_LoadOemDicts(None))
330
331 def test_SingleDict(self):
332 dict_file = common.MakeTempFile()
333 with open(dict_file, 'w') as dict_fp:
334 dict_fp.write('abc=1\ndef=2\nxyz=foo\na.b.c=bar\n')
335
336 oem_dicts = _LoadOemDicts([dict_file])
337 self.assertEqual(1, len(oem_dicts))
338 self.assertEqual('foo', oem_dicts[0]['xyz'])
339 self.assertEqual('bar', oem_dicts[0]['a.b.c'])
340
341 def test_MultipleDicts(self):
342 oem_source = []
343 for i in range(3):
344 dict_file = common.MakeTempFile()
345 with open(dict_file, 'w') as dict_fp:
346 dict_fp.write(
347 'ro.build.index={}\ndef=2\nxyz=foo\na.b.c=bar\n'.format(i))
348 oem_source.append(dict_file)
349
350 oem_dicts = _LoadOemDicts(oem_source)
351 self.assertEqual(3, len(oem_dicts))
352 for i, oem_dict in enumerate(oem_dicts):
353 self.assertEqual('2', oem_dict['def'])
354 self.assertEqual('foo', oem_dict['xyz'])
355 self.assertEqual('bar', oem_dict['a.b.c'])
356 self.assertEqual('{}'.format(i), oem_dict['ro.build.index'])
Tao Baodf3a48b2018-01-10 16:30:43 -0800357
358
359class OtaFromTargetFilesTest(unittest.TestCase):
360
361 TEST_TARGET_INFO_DICT = {
362 'build.prop' : {
363 'ro.product.device' : 'product-device',
364 'ro.build.fingerprint' : 'build-fingerprint-target',
365 'ro.build.version.incremental' : 'build-version-incremental-target',
Tao Bao35dc2552018-02-01 13:18:00 -0800366 'ro.build.version.sdk' : '27',
367 'ro.build.version.security_patch' : '2017-12-01',
Tao Baodf3a48b2018-01-10 16:30:43 -0800368 'ro.build.date.utc' : '1500000000',
369 },
370 }
371
372 TEST_SOURCE_INFO_DICT = {
373 'build.prop' : {
374 'ro.product.device' : 'product-device',
375 'ro.build.fingerprint' : 'build-fingerprint-source',
376 'ro.build.version.incremental' : 'build-version-incremental-source',
Tao Bao35dc2552018-02-01 13:18:00 -0800377 'ro.build.version.sdk' : '25',
378 'ro.build.version.security_patch' : '2016-12-01',
Tao Baodf3a48b2018-01-10 16:30:43 -0800379 'ro.build.date.utc' : '1400000000',
380 },
381 }
382
383 def setUp(self):
Tao Bao3bf8c652018-03-16 12:59:42 -0700384 self.testdata_dir = test_utils.get_testdata_dir()
385 self.assertTrue(os.path.exists(self.testdata_dir))
386
Tao Baodf3a48b2018-01-10 16:30:43 -0800387 # Reset the global options as in ota_from_target_files.py.
388 common.OPTIONS.incremental_source = None
389 common.OPTIONS.downgrade = False
390 common.OPTIONS.timestamp = False
391 common.OPTIONS.wipe_user_data = False
Tao Bao3bf8c652018-03-16 12:59:42 -0700392 common.OPTIONS.no_signing = False
393 common.OPTIONS.package_key = os.path.join(self.testdata_dir, 'testkey')
394 common.OPTIONS.key_passwords = {
395 common.OPTIONS.package_key : None,
396 }
397
398 common.OPTIONS.search_path = test_utils.get_search_path()
399 self.assertIsNotNone(common.OPTIONS.search_path)
Tao Baodf3a48b2018-01-10 16:30:43 -0800400
Tao Baof5110492018-03-02 09:47:43 -0800401 def tearDown(self):
402 common.Cleanup()
403
Tao Baodf3a48b2018-01-10 16:30:43 -0800404 def test_GetPackageMetadata_abOta_full(self):
405 target_info_dict = copy.deepcopy(self.TEST_TARGET_INFO_DICT)
406 target_info_dict['ab_update'] = 'true'
407 target_info = BuildInfo(target_info_dict, None)
408 metadata = GetPackageMetadata(target_info)
409 self.assertDictEqual(
410 {
411 'ota-type' : 'AB',
412 'ota-required-cache' : '0',
413 'post-build' : 'build-fingerprint-target',
414 'post-build-incremental' : 'build-version-incremental-target',
Tao Bao35dc2552018-02-01 13:18:00 -0800415 'post-sdk-level' : '27',
416 'post-security-patch-level' : '2017-12-01',
Tao Baodf3a48b2018-01-10 16:30:43 -0800417 'post-timestamp' : '1500000000',
418 'pre-device' : 'product-device',
419 },
420 metadata)
421
422 def test_GetPackageMetadata_abOta_incremental(self):
423 target_info_dict = copy.deepcopy(self.TEST_TARGET_INFO_DICT)
424 target_info_dict['ab_update'] = 'true'
425 target_info = BuildInfo(target_info_dict, None)
426 source_info = BuildInfo(self.TEST_SOURCE_INFO_DICT, None)
427 common.OPTIONS.incremental_source = ''
428 metadata = GetPackageMetadata(target_info, source_info)
429 self.assertDictEqual(
430 {
431 'ota-type' : 'AB',
432 'ota-required-cache' : '0',
433 'post-build' : 'build-fingerprint-target',
434 'post-build-incremental' : 'build-version-incremental-target',
Tao Bao35dc2552018-02-01 13:18:00 -0800435 'post-sdk-level' : '27',
436 'post-security-patch-level' : '2017-12-01',
Tao Baodf3a48b2018-01-10 16:30:43 -0800437 'post-timestamp' : '1500000000',
438 'pre-device' : 'product-device',
439 'pre-build' : 'build-fingerprint-source',
440 'pre-build-incremental' : 'build-version-incremental-source',
441 },
442 metadata)
443
444 def test_GetPackageMetadata_nonAbOta_full(self):
445 target_info = BuildInfo(self.TEST_TARGET_INFO_DICT, None)
446 metadata = GetPackageMetadata(target_info)
447 self.assertDictEqual(
448 {
449 'ota-type' : 'BLOCK',
450 'post-build' : 'build-fingerprint-target',
451 'post-build-incremental' : 'build-version-incremental-target',
Tao Bao35dc2552018-02-01 13:18:00 -0800452 'post-sdk-level' : '27',
453 'post-security-patch-level' : '2017-12-01',
Tao Baodf3a48b2018-01-10 16:30:43 -0800454 'post-timestamp' : '1500000000',
455 'pre-device' : 'product-device',
456 },
457 metadata)
458
459 def test_GetPackageMetadata_nonAbOta_incremental(self):
460 target_info = BuildInfo(self.TEST_TARGET_INFO_DICT, None)
461 source_info = BuildInfo(self.TEST_SOURCE_INFO_DICT, None)
462 common.OPTIONS.incremental_source = ''
463 metadata = GetPackageMetadata(target_info, source_info)
464 self.assertDictEqual(
465 {
466 'ota-type' : 'BLOCK',
467 'post-build' : 'build-fingerprint-target',
468 'post-build-incremental' : 'build-version-incremental-target',
Tao Bao35dc2552018-02-01 13:18:00 -0800469 'post-sdk-level' : '27',
470 'post-security-patch-level' : '2017-12-01',
Tao Baodf3a48b2018-01-10 16:30:43 -0800471 'post-timestamp' : '1500000000',
472 'pre-device' : 'product-device',
473 'pre-build' : 'build-fingerprint-source',
474 'pre-build-incremental' : 'build-version-incremental-source',
475 },
476 metadata)
477
478 def test_GetPackageMetadata_wipe(self):
479 target_info = BuildInfo(self.TEST_TARGET_INFO_DICT, None)
480 common.OPTIONS.wipe_user_data = True
481 metadata = GetPackageMetadata(target_info)
482 self.assertDictEqual(
483 {
484 'ota-type' : 'BLOCK',
485 'ota-wipe' : 'yes',
486 'post-build' : 'build-fingerprint-target',
487 'post-build-incremental' : 'build-version-incremental-target',
Tao Bao35dc2552018-02-01 13:18:00 -0800488 'post-sdk-level' : '27',
489 'post-security-patch-level' : '2017-12-01',
Tao Baodf3a48b2018-01-10 16:30:43 -0800490 'post-timestamp' : '1500000000',
491 'pre-device' : 'product-device',
492 },
493 metadata)
494
495 @staticmethod
496 def _test_GetPackageMetadata_swapBuildTimestamps(target_info, source_info):
497 (target_info['build.prop']['ro.build.date.utc'],
498 source_info['build.prop']['ro.build.date.utc']) = (
499 source_info['build.prop']['ro.build.date.utc'],
500 target_info['build.prop']['ro.build.date.utc'])
501
502 def test_GetPackageMetadata_unintentionalDowngradeDetected(self):
503 target_info_dict = copy.deepcopy(self.TEST_TARGET_INFO_DICT)
504 source_info_dict = copy.deepcopy(self.TEST_SOURCE_INFO_DICT)
505 self._test_GetPackageMetadata_swapBuildTimestamps(
506 target_info_dict, source_info_dict)
507
508 target_info = BuildInfo(target_info_dict, None)
509 source_info = BuildInfo(source_info_dict, None)
510 common.OPTIONS.incremental_source = ''
511 self.assertRaises(RuntimeError, GetPackageMetadata, target_info,
512 source_info)
513
514 def test_GetPackageMetadata_downgrade(self):
515 target_info_dict = copy.deepcopy(self.TEST_TARGET_INFO_DICT)
516 source_info_dict = copy.deepcopy(self.TEST_SOURCE_INFO_DICT)
517 self._test_GetPackageMetadata_swapBuildTimestamps(
518 target_info_dict, source_info_dict)
519
520 target_info = BuildInfo(target_info_dict, None)
521 source_info = BuildInfo(source_info_dict, None)
522 common.OPTIONS.incremental_source = ''
523 common.OPTIONS.downgrade = True
524 common.OPTIONS.wipe_user_data = True
525 metadata = GetPackageMetadata(target_info, source_info)
526 self.assertDictEqual(
527 {
528 'ota-downgrade' : 'yes',
529 'ota-type' : 'BLOCK',
530 'ota-wipe' : 'yes',
531 'post-build' : 'build-fingerprint-target',
532 'post-build-incremental' : 'build-version-incremental-target',
Tao Bao35dc2552018-02-01 13:18:00 -0800533 'post-sdk-level' : '27',
534 'post-security-patch-level' : '2017-12-01',
Tao Baofaa8e0b2018-04-12 14:31:43 -0700535 'post-timestamp' : '1400000000',
Tao Baodf3a48b2018-01-10 16:30:43 -0800536 'pre-device' : 'product-device',
537 'pre-build' : 'build-fingerprint-source',
538 'pre-build-incremental' : 'build-version-incremental-source',
539 },
540 metadata)
Tao Baofabe0832018-01-17 15:52:28 -0800541
Tao Baof7140c02018-01-30 17:09:24 -0800542 def test_GetTargetFilesZipForSecondaryImages(self):
543 input_file = construct_target_files(secondary=True)
544 target_file = GetTargetFilesZipForSecondaryImages(input_file)
545
546 with zipfile.ZipFile(target_file) as verify_zip:
547 namelist = verify_zip.namelist()
548
549 self.assertIn('META/ab_partitions.txt', namelist)
550 self.assertIn('IMAGES/boot.img', namelist)
551 self.assertIn('IMAGES/system.img', namelist)
552 self.assertIn('IMAGES/vendor.img', namelist)
Tao Bao15a146a2018-02-21 16:06:59 -0800553 self.assertIn(POSTINSTALL_CONFIG, namelist)
Tao Baof7140c02018-01-30 17:09:24 -0800554
555 self.assertNotIn('IMAGES/system_other.img', namelist)
556 self.assertNotIn('IMAGES/system.map', namelist)
557
Tao Bao15a146a2018-02-21 16:06:59 -0800558 def test_GetTargetFilesZipForSecondaryImages_skipPostinstall(self):
559 input_file = construct_target_files(secondary=True)
560 target_file = GetTargetFilesZipForSecondaryImages(
561 input_file, skip_postinstall=True)
562
563 with zipfile.ZipFile(target_file) as verify_zip:
564 namelist = verify_zip.namelist()
565
566 self.assertIn('META/ab_partitions.txt', namelist)
567 self.assertIn('IMAGES/boot.img', namelist)
568 self.assertIn('IMAGES/system.img', namelist)
569 self.assertIn('IMAGES/vendor.img', namelist)
570
571 self.assertNotIn('IMAGES/system_other.img', namelist)
572 self.assertNotIn('IMAGES/system.map', namelist)
573 self.assertNotIn(POSTINSTALL_CONFIG, namelist)
574
575 def test_GetTargetFilesZipWithoutPostinstallConfig(self):
576 input_file = construct_target_files()
577 target_file = GetTargetFilesZipWithoutPostinstallConfig(input_file)
578 with zipfile.ZipFile(target_file) as verify_zip:
579 self.assertNotIn(POSTINSTALL_CONFIG, verify_zip.namelist())
580
581 def test_GetTargetFilesZipWithoutPostinstallConfig_missingEntry(self):
582 input_file = construct_target_files()
583 common.ZipDelete(input_file, POSTINSTALL_CONFIG)
584 target_file = GetTargetFilesZipWithoutPostinstallConfig(input_file)
585 with zipfile.ZipFile(target_file) as verify_zip:
586 self.assertNotIn(POSTINSTALL_CONFIG, verify_zip.namelist())
587
Tao Bao3bf8c652018-03-16 12:59:42 -0700588 def _test_FinalizeMetadata(self, large_entry=False):
589 entries = [
590 'required-entry1',
591 'required-entry2',
592 ]
593 zip_file = PropertyFilesTest.construct_zip_package(entries)
594 # Add a large entry of 1 GiB if requested.
595 if large_entry:
596 with zipfile.ZipFile(zip_file, 'a') as zip_fp:
597 zip_fp.writestr(
598 # Using 'zoo' so that the entry stays behind others after signing.
599 'zoo',
600 'A' * 1024 * 1024 * 1024,
601 zipfile.ZIP_STORED)
602
603 metadata = {}
604 output_file = common.MakeTempFile(suffix='.zip')
605 needed_property_files = (
606 TestPropertyFiles(),
607 )
608 FinalizeMetadata(metadata, zip_file, output_file, needed_property_files)
609 self.assertIn('ota-test-property-files', metadata)
610
611 def test_FinalizeMetadata(self):
612 self._test_FinalizeMetadata()
613
614 def test_FinalizeMetadata_withNoSigning(self):
615 common.OPTIONS.no_signing = True
616 self._test_FinalizeMetadata()
617
618 def test_FinalizeMetadata_largeEntry(self):
619 self._test_FinalizeMetadata(large_entry=True)
620
621 def test_FinalizeMetadata_largeEntry_withNoSigning(self):
622 common.OPTIONS.no_signing = True
623 self._test_FinalizeMetadata(large_entry=True)
624
625 def test_FinalizeMetadata_insufficientSpace(self):
626 entries = [
627 'required-entry1',
628 'required-entry2',
629 'optional-entry1',
630 'optional-entry2',
631 ]
632 zip_file = PropertyFilesTest.construct_zip_package(entries)
633 with zipfile.ZipFile(zip_file, 'a') as zip_fp:
634 zip_fp.writestr(
635 # 'foo-entry1' will appear ahead of all other entries (in alphabetical
636 # order) after the signing, which will in turn trigger the
637 # InsufficientSpaceException and an automatic retry.
638 'foo-entry1',
639 'A' * 1024 * 1024,
640 zipfile.ZIP_STORED)
641
642 metadata = {}
643 needed_property_files = (
644 TestPropertyFiles(),
645 )
646 output_file = common.MakeTempFile(suffix='.zip')
647 FinalizeMetadata(metadata, zip_file, output_file, needed_property_files)
648 self.assertIn('ota-test-property-files', metadata)
649
Tao Baoae5e4c32018-03-01 19:30:00 -0800650
Tao Bao69203522018-03-08 16:09:01 -0800651class TestPropertyFiles(PropertyFiles):
652 """A class that extends PropertyFiles for testing purpose."""
653
654 def __init__(self):
655 super(TestPropertyFiles, self).__init__()
656 self.name = 'ota-test-property-files'
657 self.required = (
658 'required-entry1',
659 'required-entry2',
660 )
661 self.optional = (
662 'optional-entry1',
663 'optional-entry2',
664 )
665
666
667class PropertyFilesTest(unittest.TestCase):
Tao Baoae5e4c32018-03-01 19:30:00 -0800668
Tao Bao3bf8c652018-03-16 12:59:42 -0700669 def setUp(self):
670 common.OPTIONS.no_signing = False
671
Tao Baoae5e4c32018-03-01 19:30:00 -0800672 def tearDown(self):
673 common.Cleanup()
674
Tao Baof5110492018-03-02 09:47:43 -0800675 @staticmethod
Tao Bao3bf8c652018-03-16 12:59:42 -0700676 def construct_zip_package(entries):
Tao Baof5110492018-03-02 09:47:43 -0800677 zip_file = common.MakeTempFile(suffix='.zip')
678 with zipfile.ZipFile(zip_file, 'w') as zip_fp:
679 for entry in entries:
680 zip_fp.writestr(
681 entry,
682 entry.replace('.', '-').upper(),
683 zipfile.ZIP_STORED)
684 return zip_file
685
686 @staticmethod
Tao Bao69203522018-03-08 16:09:01 -0800687 def _parse_property_files_string(data):
Tao Baof5110492018-03-02 09:47:43 -0800688 result = {}
689 for token in data.split(','):
690 name, info = token.split(':', 1)
691 result[name] = info
692 return result
693
694 def _verify_entries(self, input_file, tokens, entries):
695 for entry in entries:
696 offset, size = map(int, tokens[entry].split(':'))
697 with open(input_file, 'rb') as input_fp:
698 input_fp.seek(offset)
699 if entry == 'metadata':
700 expected = b'META-INF/COM/ANDROID/METADATA'
701 else:
702 expected = entry.replace('.', '-').upper().encode()
703 self.assertEqual(expected, input_fp.read(size))
704
Tao Baoae5e4c32018-03-01 19:30:00 -0800705 def test_Compute(self):
Tao Baof5110492018-03-02 09:47:43 -0800706 entries = (
Tao Bao69203522018-03-08 16:09:01 -0800707 'required-entry1',
708 'required-entry2',
Tao Baof5110492018-03-02 09:47:43 -0800709 )
Tao Bao3bf8c652018-03-16 12:59:42 -0700710 zip_file = self.construct_zip_package(entries)
Tao Bao69203522018-03-08 16:09:01 -0800711 property_files = TestPropertyFiles()
Tao Baof5110492018-03-02 09:47:43 -0800712 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
Tao Bao69203522018-03-08 16:09:01 -0800713 property_files_string = property_files.Compute(zip_fp)
Tao Baof5110492018-03-02 09:47:43 -0800714
Tao Bao69203522018-03-08 16:09:01 -0800715 tokens = self._parse_property_files_string(property_files_string)
Tao Baof5110492018-03-02 09:47:43 -0800716 self.assertEqual(3, len(tokens))
717 self._verify_entries(zip_file, tokens, entries)
718
Tao Bao69203522018-03-08 16:09:01 -0800719 def test_Compute_withOptionalEntries(self):
Tao Baof5110492018-03-02 09:47:43 -0800720 entries = (
Tao Bao69203522018-03-08 16:09:01 -0800721 'required-entry1',
722 'required-entry2',
723 'optional-entry1',
724 'optional-entry2',
Tao Baof5110492018-03-02 09:47:43 -0800725 )
Tao Bao3bf8c652018-03-16 12:59:42 -0700726 zip_file = self.construct_zip_package(entries)
Tao Bao69203522018-03-08 16:09:01 -0800727 property_files = TestPropertyFiles()
Tao Baof5110492018-03-02 09:47:43 -0800728 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
Tao Bao69203522018-03-08 16:09:01 -0800729 property_files_string = property_files.Compute(zip_fp)
Tao Baof5110492018-03-02 09:47:43 -0800730
Tao Bao69203522018-03-08 16:09:01 -0800731 tokens = self._parse_property_files_string(property_files_string)
Tao Baof5110492018-03-02 09:47:43 -0800732 self.assertEqual(5, len(tokens))
733 self._verify_entries(zip_file, tokens, entries)
734
Tao Bao69203522018-03-08 16:09:01 -0800735 def test_Compute_missingRequiredEntry(self):
736 entries = (
737 'required-entry2',
738 )
Tao Bao3bf8c652018-03-16 12:59:42 -0700739 zip_file = self.construct_zip_package(entries)
Tao Bao69203522018-03-08 16:09:01 -0800740 property_files = TestPropertyFiles()
741 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
742 self.assertRaises(KeyError, property_files.Compute, zip_fp)
743
Tao Baoae5e4c32018-03-01 19:30:00 -0800744 def test_Finalize(self):
Tao Baof5110492018-03-02 09:47:43 -0800745 entries = [
Tao Bao69203522018-03-08 16:09:01 -0800746 'required-entry1',
747 'required-entry2',
Tao Baof5110492018-03-02 09:47:43 -0800748 'META-INF/com/android/metadata',
749 ]
Tao Bao3bf8c652018-03-16 12:59:42 -0700750 zip_file = self.construct_zip_package(entries)
Tao Bao69203522018-03-08 16:09:01 -0800751 property_files = TestPropertyFiles()
Tao Baof5110492018-03-02 09:47:43 -0800752 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -0700753 raw_metadata = property_files.GetPropertyFilesString(
Tao Baoae5e4c32018-03-01 19:30:00 -0800754 zip_fp, reserve_space=False)
755 streaming_metadata = property_files.Finalize(zip_fp, len(raw_metadata))
Tao Bao69203522018-03-08 16:09:01 -0800756 tokens = self._parse_property_files_string(streaming_metadata)
Tao Baof5110492018-03-02 09:47:43 -0800757
758 self.assertEqual(3, len(tokens))
759 # 'META-INF/com/android/metadata' will be key'd as 'metadata' in the
760 # streaming metadata.
761 entries[2] = 'metadata'
762 self._verify_entries(zip_file, tokens, entries)
763
Tao Baoae5e4c32018-03-01 19:30:00 -0800764 def test_Finalize_assertReservedLength(self):
Tao Baof5110492018-03-02 09:47:43 -0800765 entries = (
Tao Bao69203522018-03-08 16:09:01 -0800766 'required-entry1',
767 'required-entry2',
768 'optional-entry1',
769 'optional-entry2',
Tao Baof5110492018-03-02 09:47:43 -0800770 'META-INF/com/android/metadata',
771 )
Tao Bao3bf8c652018-03-16 12:59:42 -0700772 zip_file = self.construct_zip_package(entries)
Tao Bao69203522018-03-08 16:09:01 -0800773 property_files = TestPropertyFiles()
Tao Baof5110492018-03-02 09:47:43 -0800774 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
775 # First get the raw metadata string (i.e. without padding space).
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -0700776 raw_metadata = property_files.GetPropertyFilesString(
Tao Baoae5e4c32018-03-01 19:30:00 -0800777 zip_fp, reserve_space=False)
Tao Baof5110492018-03-02 09:47:43 -0800778 raw_length = len(raw_metadata)
779
780 # Now pass in the exact expected length.
Tao Baoae5e4c32018-03-01 19:30:00 -0800781 streaming_metadata = property_files.Finalize(zip_fp, raw_length)
Tao Baof5110492018-03-02 09:47:43 -0800782 self.assertEqual(raw_length, len(streaming_metadata))
783
784 # Or pass in insufficient length.
785 self.assertRaises(
Tao Bao3bf8c652018-03-16 12:59:42 -0700786 PropertyFiles.InsufficientSpaceException,
Tao Baoae5e4c32018-03-01 19:30:00 -0800787 property_files.Finalize,
Tao Baof5110492018-03-02 09:47:43 -0800788 zip_fp,
Tao Baoae5e4c32018-03-01 19:30:00 -0800789 raw_length - 1)
Tao Baof5110492018-03-02 09:47:43 -0800790
791 # Or pass in a much larger size.
Tao Baoae5e4c32018-03-01 19:30:00 -0800792 streaming_metadata = property_files.Finalize(
Tao Baof5110492018-03-02 09:47:43 -0800793 zip_fp,
Tao Baoae5e4c32018-03-01 19:30:00 -0800794 raw_length + 20)
Tao Baof5110492018-03-02 09:47:43 -0800795 self.assertEqual(raw_length + 20, len(streaming_metadata))
796 self.assertEqual(' ' * 20, streaming_metadata[raw_length:])
797
Tao Baoae5e4c32018-03-01 19:30:00 -0800798 def test_Verify(self):
799 entries = (
Tao Bao69203522018-03-08 16:09:01 -0800800 'required-entry1',
801 'required-entry2',
802 'optional-entry1',
803 'optional-entry2',
804 'META-INF/com/android/metadata',
805 )
Tao Bao3bf8c652018-03-16 12:59:42 -0700806 zip_file = self.construct_zip_package(entries)
Tao Bao69203522018-03-08 16:09:01 -0800807 property_files = TestPropertyFiles()
808 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
809 # First get the raw metadata string (i.e. without padding space).
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -0700810 raw_metadata = property_files.GetPropertyFilesString(
Tao Bao69203522018-03-08 16:09:01 -0800811 zip_fp, reserve_space=False)
812
813 # Should pass the test if verification passes.
814 property_files.Verify(zip_fp, raw_metadata)
815
816 # Or raise on verification failure.
817 self.assertRaises(
818 AssertionError, property_files.Verify, zip_fp, raw_metadata + 'x')
819
820
821class StreamingPropertyFilesTest(PropertyFilesTest):
822 """Additional sanity checks specialized for StreamingPropertyFiles."""
823
824 def test_init(self):
825 property_files = StreamingPropertyFiles()
826 self.assertEqual('ota-streaming-property-files', property_files.name)
827 self.assertEqual(
828 (
829 'payload.bin',
830 'payload_properties.txt',
831 ),
832 property_files.required)
833 self.assertEqual(
834 (
835 'care_map.txt',
836 'compatibility.zip',
837 ),
838 property_files.optional)
839
840 def test_Compute(self):
841 entries = (
Tao Baoae5e4c32018-03-01 19:30:00 -0800842 'payload.bin',
843 'payload_properties.txt',
844 'care_map.txt',
Tao Bao69203522018-03-08 16:09:01 -0800845 'compatibility.zip',
846 )
Tao Bao3bf8c652018-03-16 12:59:42 -0700847 zip_file = self.construct_zip_package(entries)
Tao Bao69203522018-03-08 16:09:01 -0800848 property_files = StreamingPropertyFiles()
849 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
850 property_files_string = property_files.Compute(zip_fp)
851
852 tokens = self._parse_property_files_string(property_files_string)
853 self.assertEqual(5, len(tokens))
854 self._verify_entries(zip_file, tokens, entries)
855
856 def test_Finalize(self):
857 entries = [
858 'payload.bin',
859 'payload_properties.txt',
860 'care_map.txt',
861 'compatibility.zip',
862 'META-INF/com/android/metadata',
863 ]
Tao Bao3bf8c652018-03-16 12:59:42 -0700864 zip_file = self.construct_zip_package(entries)
Tao Bao69203522018-03-08 16:09:01 -0800865 property_files = StreamingPropertyFiles()
866 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -0700867 raw_metadata = property_files.GetPropertyFilesString(
Tao Bao69203522018-03-08 16:09:01 -0800868 zip_fp, reserve_space=False)
869 streaming_metadata = property_files.Finalize(zip_fp, len(raw_metadata))
870 tokens = self._parse_property_files_string(streaming_metadata)
871
872 self.assertEqual(5, len(tokens))
873 # 'META-INF/com/android/metadata' will be key'd as 'metadata' in the
874 # streaming metadata.
875 entries[4] = 'metadata'
876 self._verify_entries(zip_file, tokens, entries)
877
878 def test_Verify(self):
879 entries = (
880 'payload.bin',
881 'payload_properties.txt',
882 'care_map.txt',
883 'compatibility.zip',
Tao Baoae5e4c32018-03-01 19:30:00 -0800884 'META-INF/com/android/metadata',
885 )
Tao Bao3bf8c652018-03-16 12:59:42 -0700886 zip_file = self.construct_zip_package(entries)
Tao Baoae5e4c32018-03-01 19:30:00 -0800887 property_files = StreamingPropertyFiles()
888 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
889 # First get the raw metadata string (i.e. without padding space).
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -0700890 raw_metadata = property_files.GetPropertyFilesString(
Tao Baoae5e4c32018-03-01 19:30:00 -0800891 zip_fp, reserve_space=False)
892
893 # Should pass the test if verification passes.
894 property_files.Verify(zip_fp, raw_metadata)
895
896 # Or raise on verification failure.
897 self.assertRaises(
898 AssertionError, property_files.Verify, zip_fp, raw_metadata + 'x')
899
Tao Baofabe0832018-01-17 15:52:28 -0800900
Tao Baob6304672018-03-08 16:28:33 -0800901class AbOtaPropertyFilesTest(PropertyFilesTest):
902 """Additional sanity checks specialized for AbOtaPropertyFiles."""
903
904 # The size for payload and metadata signature size.
905 SIGNATURE_SIZE = 256
906
907 def setUp(self):
908 self.testdata_dir = test_utils.get_testdata_dir()
909 self.assertTrue(os.path.exists(self.testdata_dir))
910
911 common.OPTIONS.wipe_user_data = False
912 common.OPTIONS.payload_signer = None
913 common.OPTIONS.payload_signer_args = None
914 common.OPTIONS.package_key = os.path.join(self.testdata_dir, 'testkey')
915 common.OPTIONS.key_passwords = {
916 common.OPTIONS.package_key : None,
917 }
918
919 def test_init(self):
920 property_files = AbOtaPropertyFiles()
921 self.assertEqual('ota-property-files', property_files.name)
922 self.assertEqual(
923 (
924 'payload.bin',
925 'payload_properties.txt',
926 ),
927 property_files.required)
928 self.assertEqual(
929 (
930 'care_map.txt',
931 'compatibility.zip',
932 ),
933 property_files.optional)
934
935 def test_GetPayloadMetadataOffsetAndSize(self):
936 target_file = construct_target_files()
937 payload = Payload()
938 payload.Generate(target_file)
939
940 payload_signer = PayloadSigner()
941 payload.Sign(payload_signer)
942
943 output_file = common.MakeTempFile(suffix='.zip')
944 with zipfile.ZipFile(output_file, 'w') as output_zip:
945 payload.WriteToZip(output_zip)
946
947 # Find out the payload metadata offset and size.
948 property_files = AbOtaPropertyFiles()
949 with zipfile.ZipFile(output_file) as input_zip:
950 # pylint: disable=protected-access
951 payload_offset, metadata_total = (
952 property_files._GetPayloadMetadataOffsetAndSize(input_zip))
953
954 # Read in the metadata signature directly.
955 with open(output_file, 'rb') as verify_fp:
956 verify_fp.seek(payload_offset + metadata_total - self.SIGNATURE_SIZE)
957 metadata_signature = verify_fp.read(self.SIGNATURE_SIZE)
958
959 # Now we extract the metadata hash via brillo_update_payload script, which
960 # will serve as the oracle result.
961 payload_sig_file = common.MakeTempFile(prefix="sig-", suffix=".bin")
962 metadata_sig_file = common.MakeTempFile(prefix="sig-", suffix=".bin")
963 cmd = ['brillo_update_payload', 'hash',
964 '--unsigned_payload', payload.payload_file,
965 '--signature_size', str(self.SIGNATURE_SIZE),
966 '--metadata_hash_file', metadata_sig_file,
967 '--payload_hash_file', payload_sig_file]
968 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
969 stdoutdata, _ = proc.communicate()
970 self.assertEqual(
971 0, proc.returncode,
972 'Failed to run brillo_update_payload: {}'.format(stdoutdata))
973
974 signed_metadata_sig_file = payload_signer.Sign(metadata_sig_file)
975
976 # Finally we can compare the two signatures.
977 with open(signed_metadata_sig_file, 'rb') as verify_fp:
978 self.assertEqual(verify_fp.read(), metadata_signature)
979
980 @staticmethod
Tao Bao3bf8c652018-03-16 12:59:42 -0700981 def construct_zip_package_withValidPayload(with_metadata=False):
982 # Cannot use construct_zip_package() since we need a "valid" payload.bin.
Tao Baob6304672018-03-08 16:28:33 -0800983 target_file = construct_target_files()
984 payload = Payload()
985 payload.Generate(target_file)
986
987 payload_signer = PayloadSigner()
988 payload.Sign(payload_signer)
989
990 zip_file = common.MakeTempFile(suffix='.zip')
991 with zipfile.ZipFile(zip_file, 'w') as zip_fp:
992 # 'payload.bin',
993 payload.WriteToZip(zip_fp)
994
995 # Other entries.
996 entries = ['care_map.txt', 'compatibility.zip']
997
998 # Put META-INF/com/android/metadata if needed.
999 if with_metadata:
1000 entries.append('META-INF/com/android/metadata')
1001
1002 for entry in entries:
1003 zip_fp.writestr(
1004 entry, entry.replace('.', '-').upper(), zipfile.ZIP_STORED)
1005
1006 return zip_file
1007
1008 def test_Compute(self):
Tao Bao3bf8c652018-03-16 12:59:42 -07001009 zip_file = self.construct_zip_package_withValidPayload()
Tao Baob6304672018-03-08 16:28:33 -08001010 property_files = AbOtaPropertyFiles()
1011 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
1012 property_files_string = property_files.Compute(zip_fp)
1013
1014 tokens = self._parse_property_files_string(property_files_string)
1015 # "6" indcludes the four entries above, one metadata entry, and one entry
1016 # for payload-metadata.bin.
1017 self.assertEqual(6, len(tokens))
1018 self._verify_entries(
1019 zip_file, tokens, ('care_map.txt', 'compatibility.zip'))
1020
1021 def test_Finalize(self):
Tao Bao3bf8c652018-03-16 12:59:42 -07001022 zip_file = self.construct_zip_package_withValidPayload(with_metadata=True)
Tao Baob6304672018-03-08 16:28:33 -08001023 property_files = AbOtaPropertyFiles()
1024 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -07001025 raw_metadata = property_files.GetPropertyFilesString(
Tao Baob6304672018-03-08 16:28:33 -08001026 zip_fp, reserve_space=False)
1027 property_files_string = property_files.Finalize(zip_fp, len(raw_metadata))
1028
1029 tokens = self._parse_property_files_string(property_files_string)
1030 # "6" indcludes the four entries above, one metadata entry, and one entry
1031 # for payload-metadata.bin.
1032 self.assertEqual(6, len(tokens))
1033 self._verify_entries(
1034 zip_file, tokens, ('care_map.txt', 'compatibility.zip'))
1035
1036 def test_Verify(self):
Tao Bao3bf8c652018-03-16 12:59:42 -07001037 zip_file = self.construct_zip_package_withValidPayload(with_metadata=True)
Tao Baob6304672018-03-08 16:28:33 -08001038 property_files = AbOtaPropertyFiles()
1039 with zipfile.ZipFile(zip_file, 'r') as zip_fp:
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -07001040 raw_metadata = property_files.GetPropertyFilesString(
Tao Baob6304672018-03-08 16:28:33 -08001041 zip_fp, reserve_space=False)
1042
1043 property_files.Verify(zip_fp, raw_metadata)
1044
1045
Tao Baoc0746f42018-02-21 13:17:22 -08001046class NonAbOtaPropertyFilesTest(PropertyFilesTest):
1047 """Additional sanity checks specialized for NonAbOtaPropertyFiles."""
1048
1049 def test_init(self):
1050 property_files = NonAbOtaPropertyFiles()
1051 self.assertEqual('ota-property-files', property_files.name)
1052 self.assertEqual((), property_files.required)
1053 self.assertEqual((), property_files.optional)
1054
1055 def test_Compute(self):
1056 entries = ()
Tao Bao3bf8c652018-03-16 12:59:42 -07001057 zip_file = self.construct_zip_package(entries)
Tao Baoc0746f42018-02-21 13:17:22 -08001058 property_files = NonAbOtaPropertyFiles()
1059 with zipfile.ZipFile(zip_file) as zip_fp:
1060 property_files_string = property_files.Compute(zip_fp)
1061
1062 tokens = self._parse_property_files_string(property_files_string)
1063 self.assertEqual(1, len(tokens))
1064 self._verify_entries(zip_file, tokens, entries)
1065
1066 def test_Finalize(self):
1067 entries = [
1068 'META-INF/com/android/metadata',
1069 ]
Tao Bao3bf8c652018-03-16 12:59:42 -07001070 zip_file = self.construct_zip_package(entries)
Tao Baoc0746f42018-02-21 13:17:22 -08001071 property_files = NonAbOtaPropertyFiles()
1072 with zipfile.ZipFile(zip_file) as zip_fp:
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -07001073 raw_metadata = property_files.GetPropertyFilesString(
Tao Baoc0746f42018-02-21 13:17:22 -08001074 zip_fp, reserve_space=False)
1075 property_files_string = property_files.Finalize(zip_fp, len(raw_metadata))
1076 tokens = self._parse_property_files_string(property_files_string)
1077
1078 self.assertEqual(1, len(tokens))
1079 # 'META-INF/com/android/metadata' will be key'd as 'metadata'.
1080 entries[0] = 'metadata'
1081 self._verify_entries(zip_file, tokens, entries)
1082
1083 def test_Verify(self):
1084 entries = (
1085 'META-INF/com/android/metadata',
1086 )
Tao Bao3bf8c652018-03-16 12:59:42 -07001087 zip_file = self.construct_zip_package(entries)
Tao Baoc0746f42018-02-21 13:17:22 -08001088 property_files = NonAbOtaPropertyFiles()
1089 with zipfile.ZipFile(zip_file) as zip_fp:
Zhomart Mukhamejanov603655f2018-05-04 12:35:09 -07001090 raw_metadata = property_files.GetPropertyFilesString(
Tao Baoc0746f42018-02-21 13:17:22 -08001091 zip_fp, reserve_space=False)
1092
1093 property_files.Verify(zip_fp, raw_metadata)
1094
1095
Tao Baofabe0832018-01-17 15:52:28 -08001096class PayloadSignerTest(unittest.TestCase):
1097
1098 SIGFILE = 'sigfile.bin'
1099 SIGNED_SIGFILE = 'signed-sigfile.bin'
1100
1101 def setUp(self):
Tao Bao04e1f012018-02-04 12:13:35 -08001102 self.testdata_dir = test_utils.get_testdata_dir()
Tao Baofabe0832018-01-17 15:52:28 -08001103 self.assertTrue(os.path.exists(self.testdata_dir))
1104
1105 common.OPTIONS.payload_signer = None
1106 common.OPTIONS.payload_signer_args = []
1107 common.OPTIONS.package_key = os.path.join(self.testdata_dir, 'testkey')
1108 common.OPTIONS.key_passwords = {
1109 common.OPTIONS.package_key : None,
1110 }
1111
1112 def tearDown(self):
1113 common.Cleanup()
1114
1115 def _assertFilesEqual(self, file1, file2):
1116 with open(file1, 'rb') as fp1, open(file2, 'rb') as fp2:
1117 self.assertEqual(fp1.read(), fp2.read())
1118
1119 def test_init(self):
1120 payload_signer = PayloadSigner()
1121 self.assertEqual('openssl', payload_signer.signer)
1122
1123 def test_init_withPassword(self):
1124 common.OPTIONS.package_key = os.path.join(
1125 self.testdata_dir, 'testkey_with_passwd')
1126 common.OPTIONS.key_passwords = {
1127 common.OPTIONS.package_key : 'foo',
1128 }
1129 payload_signer = PayloadSigner()
1130 self.assertEqual('openssl', payload_signer.signer)
1131
1132 def test_init_withExternalSigner(self):
1133 common.OPTIONS.payload_signer = 'abc'
1134 common.OPTIONS.payload_signer_args = ['arg1', 'arg2']
1135 payload_signer = PayloadSigner()
1136 self.assertEqual('abc', payload_signer.signer)
1137 self.assertEqual(['arg1', 'arg2'], payload_signer.signer_args)
1138
1139 def test_Sign(self):
1140 payload_signer = PayloadSigner()
1141 input_file = os.path.join(self.testdata_dir, self.SIGFILE)
1142 signed_file = payload_signer.Sign(input_file)
1143
1144 verify_file = os.path.join(self.testdata_dir, self.SIGNED_SIGFILE)
1145 self._assertFilesEqual(verify_file, signed_file)
1146
1147 def test_Sign_withExternalSigner_openssl(self):
1148 """Uses openssl as the external payload signer."""
1149 common.OPTIONS.payload_signer = 'openssl'
1150 common.OPTIONS.payload_signer_args = [
1151 'pkeyutl', '-sign', '-keyform', 'DER', '-inkey',
1152 os.path.join(self.testdata_dir, 'testkey.pk8'),
1153 '-pkeyopt', 'digest:sha256']
1154 payload_signer = PayloadSigner()
1155 input_file = os.path.join(self.testdata_dir, self.SIGFILE)
1156 signed_file = payload_signer.Sign(input_file)
1157
1158 verify_file = os.path.join(self.testdata_dir, self.SIGNED_SIGFILE)
1159 self._assertFilesEqual(verify_file, signed_file)
1160
1161 def test_Sign_withExternalSigner_script(self):
1162 """Uses testdata/payload_signer.sh as the external payload signer."""
1163 common.OPTIONS.payload_signer = os.path.join(
1164 self.testdata_dir, 'payload_signer.sh')
1165 common.OPTIONS.payload_signer_args = [
1166 os.path.join(self.testdata_dir, 'testkey.pk8')]
1167 payload_signer = PayloadSigner()
1168 input_file = os.path.join(self.testdata_dir, self.SIGFILE)
1169 signed_file = payload_signer.Sign(input_file)
1170
1171 verify_file = os.path.join(self.testdata_dir, self.SIGNED_SIGFILE)
1172 self._assertFilesEqual(verify_file, signed_file)
Tao Baoc7b403a2018-01-30 18:19:04 -08001173
1174
1175class PayloadTest(unittest.TestCase):
1176
1177 def setUp(self):
Tao Bao04e1f012018-02-04 12:13:35 -08001178 self.testdata_dir = test_utils.get_testdata_dir()
Tao Baoc7b403a2018-01-30 18:19:04 -08001179 self.assertTrue(os.path.exists(self.testdata_dir))
1180
1181 common.OPTIONS.wipe_user_data = False
1182 common.OPTIONS.payload_signer = None
1183 common.OPTIONS.payload_signer_args = None
1184 common.OPTIONS.package_key = os.path.join(self.testdata_dir, 'testkey')
1185 common.OPTIONS.key_passwords = {
1186 common.OPTIONS.package_key : None,
1187 }
1188
1189 def tearDown(self):
1190 common.Cleanup()
1191
1192 @staticmethod
Tao Baof7140c02018-01-30 17:09:24 -08001193 def _create_payload_full(secondary=False):
1194 target_file = construct_target_files(secondary)
Tao Bao667ff572018-02-10 00:02:40 -08001195 payload = Payload(secondary)
Tao Baoc7b403a2018-01-30 18:19:04 -08001196 payload.Generate(target_file)
1197 return payload
1198
Tao Baof7140c02018-01-30 17:09:24 -08001199 @staticmethod
1200 def _create_payload_incremental():
1201 target_file = construct_target_files()
1202 source_file = construct_target_files()
Tao Baoc7b403a2018-01-30 18:19:04 -08001203 payload = Payload()
1204 payload.Generate(target_file, source_file)
1205 return payload
1206
1207 def test_Generate_full(self):
1208 payload = self._create_payload_full()
1209 self.assertTrue(os.path.exists(payload.payload_file))
1210
1211 def test_Generate_incremental(self):
1212 payload = self._create_payload_incremental()
1213 self.assertTrue(os.path.exists(payload.payload_file))
1214
1215 def test_Generate_additionalArgs(self):
Tao Baof7140c02018-01-30 17:09:24 -08001216 target_file = construct_target_files()
1217 source_file = construct_target_files()
Tao Baoc7b403a2018-01-30 18:19:04 -08001218 payload = Payload()
1219 # This should work the same as calling payload.Generate(target_file,
1220 # source_file).
1221 payload.Generate(
1222 target_file, additional_args=["--source_image", source_file])
1223 self.assertTrue(os.path.exists(payload.payload_file))
1224
1225 def test_Generate_invalidInput(self):
Tao Baof7140c02018-01-30 17:09:24 -08001226 target_file = construct_target_files()
Tao Baoc7b403a2018-01-30 18:19:04 -08001227 common.ZipDelete(target_file, 'IMAGES/vendor.img')
1228 payload = Payload()
1229 self.assertRaises(AssertionError, payload.Generate, target_file)
1230
1231 def test_Sign_full(self):
1232 payload = self._create_payload_full()
1233 payload.Sign(PayloadSigner())
1234
1235 output_file = common.MakeTempFile(suffix='.zip')
1236 with zipfile.ZipFile(output_file, 'w') as output_zip:
1237 payload.WriteToZip(output_zip)
1238
1239 import check_ota_package_signature
1240 check_ota_package_signature.VerifyAbOtaPayload(
1241 os.path.join(self.testdata_dir, 'testkey.x509.pem'),
1242 output_file)
1243
1244 def test_Sign_incremental(self):
1245 payload = self._create_payload_incremental()
1246 payload.Sign(PayloadSigner())
1247
1248 output_file = common.MakeTempFile(suffix='.zip')
1249 with zipfile.ZipFile(output_file, 'w') as output_zip:
1250 payload.WriteToZip(output_zip)
1251
1252 import check_ota_package_signature
1253 check_ota_package_signature.VerifyAbOtaPayload(
1254 os.path.join(self.testdata_dir, 'testkey.x509.pem'),
1255 output_file)
1256
1257 def test_Sign_withDataWipe(self):
1258 common.OPTIONS.wipe_user_data = True
1259 payload = self._create_payload_full()
1260 payload.Sign(PayloadSigner())
1261
1262 with open(payload.payload_properties) as properties_fp:
1263 self.assertIn("POWERWASH=1", properties_fp.read())
1264
Tao Bao667ff572018-02-10 00:02:40 -08001265 def test_Sign_secondary(self):
1266 payload = self._create_payload_full(secondary=True)
1267 payload.Sign(PayloadSigner())
1268
1269 with open(payload.payload_properties) as properties_fp:
1270 self.assertIn("SWITCH_SLOT_ON_REBOOT=0", properties_fp.read())
1271
Tao Baoc7b403a2018-01-30 18:19:04 -08001272 def test_Sign_badSigner(self):
1273 """Tests that signing failure can be captured."""
1274 payload = self._create_payload_full()
1275 payload_signer = PayloadSigner()
1276 payload_signer.signer_args.append('bad-option')
1277 self.assertRaises(AssertionError, payload.Sign, payload_signer)
1278
1279 def test_WriteToZip(self):
1280 payload = self._create_payload_full()
1281 payload.Sign(PayloadSigner())
1282
1283 output_file = common.MakeTempFile(suffix='.zip')
1284 with zipfile.ZipFile(output_file, 'w') as output_zip:
1285 payload.WriteToZip(output_zip)
1286
1287 with zipfile.ZipFile(output_file) as verify_zip:
1288 # First make sure we have the essential entries.
1289 namelist = verify_zip.namelist()
1290 self.assertIn(Payload.PAYLOAD_BIN, namelist)
1291 self.assertIn(Payload.PAYLOAD_PROPERTIES_TXT, namelist)
1292
1293 # Then assert these entries are stored.
1294 for entry_info in verify_zip.infolist():
1295 if entry_info.filename not in (Payload.PAYLOAD_BIN,
1296 Payload.PAYLOAD_PROPERTIES_TXT):
1297 continue
1298 self.assertEqual(zipfile.ZIP_STORED, entry_info.compress_type)
1299
1300 def test_WriteToZip_unsignedPayload(self):
1301 """Unsigned payloads should not be allowed to be written to zip."""
1302 payload = self._create_payload_full()
1303
1304 output_file = common.MakeTempFile(suffix='.zip')
1305 with zipfile.ZipFile(output_file, 'w') as output_zip:
1306 self.assertRaises(AssertionError, payload.WriteToZip, output_zip)
1307
1308 # Also test with incremental payload.
1309 payload = self._create_payload_incremental()
1310
1311 output_file = common.MakeTempFile(suffix='.zip')
1312 with zipfile.ZipFile(output_file, 'w') as output_zip:
1313 self.assertRaises(AssertionError, payload.WriteToZip, output_zip)
Tao Baof7140c02018-01-30 17:09:24 -08001314
1315 def test_WriteToZip_secondary(self):
1316 payload = self._create_payload_full(secondary=True)
1317 payload.Sign(PayloadSigner())
1318
1319 output_file = common.MakeTempFile(suffix='.zip')
1320 with zipfile.ZipFile(output_file, 'w') as output_zip:
Tao Bao667ff572018-02-10 00:02:40 -08001321 payload.WriteToZip(output_zip)
Tao Baof7140c02018-01-30 17:09:24 -08001322
1323 with zipfile.ZipFile(output_file) as verify_zip:
1324 # First make sure we have the essential entries.
1325 namelist = verify_zip.namelist()
1326 self.assertIn(Payload.SECONDARY_PAYLOAD_BIN, namelist)
1327 self.assertIn(Payload.SECONDARY_PAYLOAD_PROPERTIES_TXT, namelist)
1328
1329 # Then assert these entries are stored.
1330 for entry_info in verify_zip.infolist():
1331 if entry_info.filename not in (
1332 Payload.SECONDARY_PAYLOAD_BIN,
1333 Payload.SECONDARY_PAYLOAD_PROPERTIES_TXT):
1334 continue
1335 self.assertEqual(zipfile.ZIP_STORED, entry_info.compress_type)