Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | """Generate test data for PSA cryptographic mechanisms. |
Gilles Peskine | 0298bda | 2021-03-10 02:34:37 +0100 | [diff] [blame] | 3 | |
| 4 | With no arguments, generate all test data. With non-option arguments, |
| 5 | generate only the specified files. |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 6 | """ |
| 7 | |
| 8 | # Copyright The Mbed TLS Contributors |
| 9 | # SPDX-License-Identifier: Apache-2.0 |
| 10 | # |
| 11 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 12 | # not use this file except in compliance with the License. |
| 13 | # You may obtain a copy of the License at |
| 14 | # |
| 15 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 16 | # |
| 17 | # Unless required by applicable law or agreed to in writing, software |
| 18 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 19 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 20 | # See the License for the specific language governing permissions and |
| 21 | # limitations under the License. |
| 22 | |
| 23 | import argparse |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 24 | import os |
| 25 | import re |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 26 | import sys |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 27 | from typing import Callable, Dict, FrozenSet, Iterable, Iterator, List, Optional, TypeVar |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 28 | |
| 29 | import scripts_path # pylint: disable=unused-import |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 30 | from mbedtls_dev import crypto_knowledge |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 31 | from mbedtls_dev import macro_collector |
Gilles Peskine | 897dff9 | 2021-03-10 15:03:44 +0100 | [diff] [blame] | 32 | from mbedtls_dev import psa_storage |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 33 | from mbedtls_dev import test_case |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 34 | |
| 35 | T = TypeVar('T') #pylint: disable=invalid-name |
| 36 | |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 37 | |
Gilles Peskine | 7f75687 | 2021-02-16 12:13:12 +0100 | [diff] [blame] | 38 | def psa_want_symbol(name: str) -> str: |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 39 | """Return the PSA_WANT_xxx symbol associated with a PSA crypto feature.""" |
| 40 | if name.startswith('PSA_'): |
| 41 | return name[:4] + 'WANT_' + name[4:] |
| 42 | else: |
| 43 | raise ValueError('Unable to determine the PSA_WANT_ symbol for ' + name) |
| 44 | |
Gilles Peskine | 7f75687 | 2021-02-16 12:13:12 +0100 | [diff] [blame] | 45 | def finish_family_dependency(dep: str, bits: int) -> str: |
| 46 | """Finish dep if it's a family dependency symbol prefix. |
| 47 | |
| 48 | A family dependency symbol prefix is a PSA_WANT_ symbol that needs to be |
| 49 | qualified by the key size. If dep is such a symbol, finish it by adjusting |
| 50 | the prefix and appending the key size. Other symbols are left unchanged. |
| 51 | """ |
| 52 | return re.sub(r'_FAMILY_(.*)', r'_\1_' + str(bits), dep) |
| 53 | |
| 54 | def finish_family_dependencies(dependencies: List[str], bits: int) -> List[str]: |
| 55 | """Finish any family dependency symbol prefixes. |
| 56 | |
| 57 | Apply `finish_family_dependency` to each element of `dependencies`. |
| 58 | """ |
| 59 | return [finish_family_dependency(dep, bits) for dep in dependencies] |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 60 | |
Gilles Peskine | f8223ab | 2021-03-10 15:07:16 +0100 | [diff] [blame^] | 61 | def automatic_dependencies(*expressions: str) -> List[str]: |
| 62 | """Infer dependencies of a test case by looking for PSA_xxx symbols. |
| 63 | |
| 64 | The arguments are strings which should be C expressions. Do not use |
| 65 | string literals or comments as this function is not smart enough to |
| 66 | skip them. |
| 67 | """ |
| 68 | used = set() |
| 69 | for expr in expressions: |
| 70 | used.update(re.findall(r'PSA_(?:ALG|ECC_FAMILY|KEY_TYPE)_\w+', expr)) |
| 71 | return sorted(psa_want_symbol(name) for name in used) |
| 72 | |
Gilles Peskine | d169d60 | 2021-02-16 14:16:25 +0100 | [diff] [blame] | 73 | # A temporary hack: at the time of writing, not all dependency symbols |
| 74 | # are implemented yet. Skip test cases for which the dependency symbols are |
| 75 | # not available. Once all dependency symbols are available, this hack must |
| 76 | # be removed so that a bug in the dependency symbols proprely leads to a test |
| 77 | # failure. |
| 78 | def read_implemented_dependencies(filename: str) -> FrozenSet[str]: |
| 79 | return frozenset(symbol |
| 80 | for line in open(filename) |
| 81 | for symbol in re.findall(r'\bPSA_WANT_\w+\b', line)) |
| 82 | IMPLEMENTED_DEPENDENCIES = read_implemented_dependencies('include/psa/crypto_config.h') |
| 83 | def hack_dependencies_not_implemented(dependencies: List[str]) -> None: |
| 84 | if not all(dep.lstrip('!') in IMPLEMENTED_DEPENDENCIES |
| 85 | for dep in dependencies): |
| 86 | dependencies.append('DEPENDENCY_NOT_IMPLEMENTED_YET') |
| 87 | |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 88 | |
Gilles Peskine | b94ea51 | 2021-03-10 02:12:08 +0100 | [diff] [blame] | 89 | class Information: |
| 90 | """Gather information about PSA constructors.""" |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 91 | |
Gilles Peskine | b94ea51 | 2021-03-10 02:12:08 +0100 | [diff] [blame] | 92 | def __init__(self) -> None: |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 93 | self.constructors = self.read_psa_interface() |
| 94 | |
| 95 | @staticmethod |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 96 | def remove_unwanted_macros( |
| 97 | constructors: macro_collector.PSAMacroCollector |
| 98 | ) -> None: |
| 99 | # Mbed TLS doesn't support DSA. Don't attempt to generate any related |
| 100 | # test case. |
| 101 | constructors.key_types.discard('PSA_KEY_TYPE_DSA_KEY_PAIR') |
| 102 | constructors.key_types.discard('PSA_KEY_TYPE_DSA_PUBLIC_KEY') |
| 103 | constructors.algorithms_from_hash.pop('PSA_ALG_DSA', None) |
| 104 | constructors.algorithms_from_hash.pop('PSA_ALG_DETERMINISTIC_DSA', None) |
| 105 | |
| 106 | def read_psa_interface(self) -> macro_collector.PSAMacroCollector: |
| 107 | """Return the list of known key types, algorithms, etc.""" |
| 108 | constructors = macro_collector.PSAMacroCollector() |
| 109 | header_file_names = ['include/psa/crypto_values.h', |
| 110 | 'include/psa/crypto_extra.h'] |
| 111 | for header_file_name in header_file_names: |
| 112 | with open(header_file_name, 'rb') as header_file: |
| 113 | constructors.read_file(header_file) |
| 114 | self.remove_unwanted_macros(constructors) |
| 115 | return constructors |
| 116 | |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 117 | |
Gilles Peskine | b94ea51 | 2021-03-10 02:12:08 +0100 | [diff] [blame] | 118 | def test_case_for_key_type_not_supported( |
| 119 | verb: str, key_type: str, bits: int, |
| 120 | dependencies: List[str], |
| 121 | *args: str, |
| 122 | param_descr: str = '' |
| 123 | ) -> test_case.TestCase: |
| 124 | """Return one test case exercising a key creation method |
| 125 | for an unsupported key type or size. |
| 126 | """ |
| 127 | hack_dependencies_not_implemented(dependencies) |
| 128 | tc = test_case.TestCase() |
| 129 | short_key_type = re.sub(r'PSA_(KEY_TYPE|ECC_FAMILY)_', r'', key_type) |
| 130 | adverb = 'not' if dependencies else 'never' |
| 131 | if param_descr: |
| 132 | adverb = param_descr + ' ' + adverb |
| 133 | tc.set_description('PSA {} {} {}-bit {} supported' |
| 134 | .format(verb, short_key_type, bits, adverb)) |
| 135 | tc.set_dependencies(dependencies) |
| 136 | tc.set_function(verb + '_not_supported') |
| 137 | tc.set_arguments([key_type] + list(args)) |
| 138 | return tc |
| 139 | |
| 140 | class NotSupported: |
| 141 | """Generate test cases for when something is not supported.""" |
| 142 | |
| 143 | def __init__(self, info: Information) -> None: |
| 144 | self.constructors = info.constructors |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 145 | |
Gilles Peskine | 60b29fe | 2021-02-16 14:06:50 +0100 | [diff] [blame] | 146 | ALWAYS_SUPPORTED = frozenset([ |
| 147 | 'PSA_KEY_TYPE_DERIVE', |
| 148 | 'PSA_KEY_TYPE_RAW_DATA', |
| 149 | ]) |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 150 | def test_cases_for_key_type_not_supported( |
Gilles Peskine | 60b29fe | 2021-02-16 14:06:50 +0100 | [diff] [blame] | 151 | self, |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 152 | kt: crypto_knowledge.KeyType, |
| 153 | param: Optional[int] = None, |
| 154 | param_descr: str = '', |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 155 | ) -> Iterator[test_case.TestCase]: |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 156 | """Return test cases exercising key creation when the given type is unsupported. |
| 157 | |
| 158 | If param is present and not None, emit test cases conditioned on this |
| 159 | parameter not being supported. If it is absent or None, emit test cases |
| 160 | conditioned on the base type not being supported. |
| 161 | """ |
Gilles Peskine | 60b29fe | 2021-02-16 14:06:50 +0100 | [diff] [blame] | 162 | if kt.name in self.ALWAYS_SUPPORTED: |
| 163 | # Don't generate test cases for key types that are always supported. |
| 164 | # They would be skipped in all configurations, which is noise. |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 165 | return |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 166 | import_dependencies = [('!' if param is None else '') + |
| 167 | psa_want_symbol(kt.name)] |
| 168 | if kt.params is not None: |
| 169 | import_dependencies += [('!' if param == i else '') + |
| 170 | psa_want_symbol(sym) |
| 171 | for i, sym in enumerate(kt.params)] |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 172 | if kt.name.endswith('_PUBLIC_KEY'): |
| 173 | generate_dependencies = [] |
| 174 | else: |
| 175 | generate_dependencies = import_dependencies |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 176 | for bits in kt.sizes_to_test(): |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 177 | yield test_case_for_key_type_not_supported( |
Gilles Peskine | 7f75687 | 2021-02-16 12:13:12 +0100 | [diff] [blame] | 178 | 'import', kt.expression, bits, |
| 179 | finish_family_dependencies(import_dependencies, bits), |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 180 | test_case.hex_string(kt.key_material(bits)), |
| 181 | param_descr=param_descr, |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 182 | ) |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 183 | if not generate_dependencies and param is not None: |
| 184 | # If generation is impossible for this key type, rather than |
| 185 | # supported or not depending on implementation capabilities, |
| 186 | # only generate the test case once. |
| 187 | continue |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 188 | yield test_case_for_key_type_not_supported( |
Gilles Peskine | 7f75687 | 2021-02-16 12:13:12 +0100 | [diff] [blame] | 189 | 'generate', kt.expression, bits, |
| 190 | finish_family_dependencies(generate_dependencies, bits), |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 191 | str(bits), |
| 192 | param_descr=param_descr, |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 193 | ) |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 194 | # To be added: derive |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 195 | |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 196 | def test_cases_for_not_supported(self) -> Iterator[test_case.TestCase]: |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 197 | """Generate test cases that exercise the creation of keys of unsupported types.""" |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 198 | for key_type in sorted(self.constructors.key_types): |
| 199 | kt = crypto_knowledge.KeyType(key_type) |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 200 | yield from self.test_cases_for_key_type_not_supported(kt) |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 201 | for curve_family in sorted(self.constructors.ecc_curves): |
| 202 | for constr in ('PSA_KEY_TYPE_ECC_KEY_PAIR', |
| 203 | 'PSA_KEY_TYPE_ECC_PUBLIC_KEY'): |
| 204 | kt = crypto_knowledge.KeyType(constr, [curve_family]) |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 205 | yield from self.test_cases_for_key_type_not_supported( |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 206 | kt, param_descr='type') |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 207 | yield from self.test_cases_for_key_type_not_supported( |
Gilles Peskine | af17284 | 2021-01-27 18:24:48 +0100 | [diff] [blame] | 208 | kt, 0, param_descr='curve') |
Gilles Peskine | b94ea51 | 2021-03-10 02:12:08 +0100 | [diff] [blame] | 209 | |
| 210 | |
Gilles Peskine | 897dff9 | 2021-03-10 15:03:44 +0100 | [diff] [blame] | 211 | class StorageKey(psa_storage.Key): |
| 212 | """Representation of a key for storage format testing.""" |
| 213 | |
| 214 | def __init__(self, *, description: str, **kwargs) -> None: |
| 215 | super().__init__(**kwargs) |
| 216 | self.description = description #type: str |
| 217 | |
| 218 | class StorageFormat: |
| 219 | """Storage format stability test cases.""" |
| 220 | |
| 221 | def __init__(self, info: Information, version: int, forward: bool) -> None: |
| 222 | """Prepare to generate test cases for storage format stability. |
| 223 | |
| 224 | * `info`: information about the API. See the `Information` class. |
| 225 | * `version`: the storage format version to generate test cases for. |
| 226 | * `forward`: if true, generate forward compatibility test cases which |
| 227 | save a key and check that its representation is as intended. Otherwise |
| 228 | generate backward compatibility test cases which inject a key |
| 229 | representation and check that it can be read and used. |
| 230 | """ |
| 231 | self.constructors = info.constructors |
| 232 | self.version = version |
| 233 | self.forward = forward |
| 234 | |
| 235 | def make_test_case(self, key: StorageKey) -> test_case.TestCase: |
| 236 | """Construct a storage format test case for the given key. |
| 237 | |
| 238 | If ``forward`` is true, generate a forward compatibility test case: |
| 239 | create a key and validate that it has the expected representation. |
| 240 | Otherwise generate a backward compatibility test case: inject the |
| 241 | key representation into storage and validate that it can be read |
| 242 | correctly. |
| 243 | """ |
| 244 | verb = 'save' if self.forward else 'read' |
| 245 | tc = test_case.TestCase() |
| 246 | tc.set_description('PSA storage {}: {}'.format(verb, key.description)) |
Gilles Peskine | f8223ab | 2021-03-10 15:07:16 +0100 | [diff] [blame^] | 247 | dependencies = automatic_dependencies( |
| 248 | key.lifetime.string, key.type.string, |
| 249 | key.usage.string, key.alg.string, key.alg2.string, |
| 250 | ) |
| 251 | dependencies = finish_family_dependencies(dependencies, key.bits) |
| 252 | tc.set_dependencies(dependencies) |
Gilles Peskine | 897dff9 | 2021-03-10 15:03:44 +0100 | [diff] [blame] | 253 | tc.set_function('key_storage_' + verb) |
| 254 | if self.forward: |
| 255 | extra_arguments = [] |
| 256 | else: |
| 257 | # Some test keys have the RAW_DATA type and attributes that don't |
| 258 | # necessarily make sense. We do this to validate numerical |
| 259 | # encodings of the attributes. |
| 260 | # Raw data keys have no useful exercise anyway so there is no |
| 261 | # loss of test coverage. |
| 262 | exercise = key.type.string != 'PSA_KEY_TYPE_RAW_DATA' |
| 263 | extra_arguments = ['1' if exercise else '0'] |
| 264 | tc.set_arguments([key.lifetime.string, |
| 265 | key.type.string, str(key.bits), |
| 266 | key.usage.string, key.alg.string, key.alg2.string, |
| 267 | '"' + key.material.hex() + '"', |
| 268 | '"' + key.hex() + '"', |
| 269 | *extra_arguments]) |
| 270 | return tc |
| 271 | |
| 272 | def key_for_usage_flags( |
| 273 | self, |
| 274 | usage_flags: List[str], |
| 275 | short: Optional[str] = None |
| 276 | ) -> StorageKey: |
| 277 | """Construct a test key for the given key usage.""" |
| 278 | usage = ' | '.join(usage_flags) if usage_flags else '0' |
| 279 | if short is None: |
| 280 | short = re.sub(r'\bPSA_KEY_USAGE_', r'', usage) |
| 281 | description = 'usage: ' + short |
| 282 | key = StorageKey(version=self.version, |
| 283 | id=1, lifetime=0x00000001, |
| 284 | type='PSA_KEY_TYPE_RAW_DATA', bits=8, |
| 285 | usage=usage, alg=0, alg2=0, |
| 286 | material=b'K', |
| 287 | description=description) |
| 288 | return key |
| 289 | |
| 290 | def all_keys_for_usage_flags(self) -> Iterator[StorageKey]: |
| 291 | """Generate test keys covering usage flags.""" |
| 292 | known_flags = sorted(self.constructors.key_usage_flags) |
| 293 | yield self.key_for_usage_flags(['0']) |
| 294 | for usage_flag in known_flags: |
| 295 | yield self.key_for_usage_flags([usage_flag]) |
| 296 | for flag1, flag2 in zip(known_flags, |
| 297 | known_flags[1:] + [known_flags[0]]): |
| 298 | yield self.key_for_usage_flags([flag1, flag2]) |
| 299 | yield self.key_for_usage_flags(known_flags, short='all known') |
| 300 | |
Gilles Peskine | f8223ab | 2021-03-10 15:07:16 +0100 | [diff] [blame^] | 301 | def keys_for_type( |
| 302 | self, |
| 303 | key_type: str, |
| 304 | params: Optional[Iterable[str]] = None |
| 305 | ) -> Iterator[StorageKey]: |
| 306 | """Generate test keys for the given key type. |
| 307 | |
| 308 | For key types that depend on a parameter (e.g. elliptic curve family), |
| 309 | `param` is the parameter to pass to the constructor. Only a single |
| 310 | parameter is supported. |
| 311 | """ |
| 312 | kt = crypto_knowledge.KeyType(key_type, params) |
| 313 | for bits in kt.sizes_to_test(): |
| 314 | usage_flags = 'PSA_KEY_USAGE_EXPORT' |
| 315 | alg = 0 |
| 316 | alg2 = 0 |
| 317 | key_material = kt.key_material(bits) |
| 318 | short_expression = re.sub(r'\bPSA_(?:KEY_TYPE|ECC_FAMILY)_', |
| 319 | r'', |
| 320 | kt.expression) |
| 321 | description = 'type: {} {}-bit'.format(short_expression, bits) |
| 322 | key = StorageKey(version=self.version, |
| 323 | id=1, lifetime=0x00000001, |
| 324 | type=kt.expression, bits=bits, |
| 325 | usage=usage_flags, alg=alg, alg2=alg2, |
| 326 | material=key_material, |
| 327 | description=description) |
| 328 | yield key |
| 329 | |
| 330 | def all_keys_for_types(self) -> Iterator[StorageKey]: |
| 331 | """Generate test keys covering key types and their representations.""" |
| 332 | for key_type in sorted(self.constructors.key_types): |
| 333 | yield from self.keys_for_type(key_type) |
| 334 | for key_type in sorted(self.constructors.key_types_from_curve): |
| 335 | for curve in sorted(self.constructors.ecc_curves): |
| 336 | yield from self.keys_for_type(key_type, [curve]) |
| 337 | ## Diffie-Hellman (FFDH) is not supported yet, either in |
| 338 | ## crypto_knowledge.py or in Mbed TLS. |
| 339 | # for key_type in sorted(self.constructors.key_types_from_group): |
| 340 | # for group in sorted(self.constructors.dh_groups): |
| 341 | # yield from self.keys_for_type(key_type, [group]) |
| 342 | |
Gilles Peskine | 897dff9 | 2021-03-10 15:03:44 +0100 | [diff] [blame] | 343 | def all_test_cases(self) -> Iterator[test_case.TestCase]: |
| 344 | """Generate all storage format test cases.""" |
| 345 | for key in self.all_keys_for_usage_flags(): |
| 346 | yield self.make_test_case(key) |
Gilles Peskine | f8223ab | 2021-03-10 15:07:16 +0100 | [diff] [blame^] | 347 | for key in self.all_keys_for_types(): |
| 348 | yield self.make_test_case(key) |
| 349 | # To do: vary id, lifetime |
Gilles Peskine | 897dff9 | 2021-03-10 15:03:44 +0100 | [diff] [blame] | 350 | |
| 351 | |
Gilles Peskine | b94ea51 | 2021-03-10 02:12:08 +0100 | [diff] [blame] | 352 | class TestGenerator: |
| 353 | """Generate test data.""" |
| 354 | |
| 355 | def __init__(self, options) -> None: |
| 356 | self.test_suite_directory = self.get_option(options, 'directory', |
| 357 | 'tests/suites') |
| 358 | self.info = Information() |
| 359 | |
| 360 | @staticmethod |
| 361 | def get_option(options, name: str, default: T) -> T: |
| 362 | value = getattr(options, name, None) |
| 363 | return default if value is None else value |
| 364 | |
Gilles Peskine | 0298bda | 2021-03-10 02:34:37 +0100 | [diff] [blame] | 365 | def filename_for(self, basename: str) -> str: |
| 366 | """The location of the data file with the specified base name.""" |
| 367 | return os.path.join(self.test_suite_directory, basename + '.data') |
| 368 | |
Gilles Peskine | b94ea51 | 2021-03-10 02:12:08 +0100 | [diff] [blame] | 369 | def write_test_data_file(self, basename: str, |
| 370 | test_cases: Iterable[test_case.TestCase]) -> None: |
| 371 | """Write the test cases to a .data file. |
| 372 | |
| 373 | The output file is ``basename + '.data'`` in the test suite directory. |
| 374 | """ |
Gilles Peskine | 0298bda | 2021-03-10 02:34:37 +0100 | [diff] [blame] | 375 | filename = self.filename_for(basename) |
Gilles Peskine | b94ea51 | 2021-03-10 02:12:08 +0100 | [diff] [blame] | 376 | test_case.write_data_file(filename, test_cases) |
| 377 | |
Gilles Peskine | 0298bda | 2021-03-10 02:34:37 +0100 | [diff] [blame] | 378 | TARGETS = { |
| 379 | 'test_suite_psa_crypto_not_supported.generated': |
Gilles Peskine | 3d77839 | 2021-02-17 15:11:05 +0100 | [diff] [blame] | 380 | lambda info: NotSupported(info).test_cases_for_not_supported(), |
Gilles Peskine | 897dff9 | 2021-03-10 15:03:44 +0100 | [diff] [blame] | 381 | 'test_suite_psa_crypto_storage_format.current': |
| 382 | lambda info: StorageFormat(info, 0, True).all_test_cases(), |
| 383 | 'test_suite_psa_crypto_storage_format.v0': |
| 384 | lambda info: StorageFormat(info, 0, False).all_test_cases(), |
Gilles Peskine | 0298bda | 2021-03-10 02:34:37 +0100 | [diff] [blame] | 385 | } #type: Dict[str, Callable[[Information], Iterable[test_case.TestCase]]] |
| 386 | |
| 387 | def generate_target(self, name: str) -> None: |
| 388 | test_cases = self.TARGETS[name](self.info) |
| 389 | self.write_test_data_file(name, test_cases) |
Gilles Peskine | 14e428f | 2021-01-26 22:19:21 +0100 | [diff] [blame] | 390 | |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 391 | def main(args): |
| 392 | """Command line entry point.""" |
| 393 | parser = argparse.ArgumentParser(description=__doc__) |
Gilles Peskine | 0298bda | 2021-03-10 02:34:37 +0100 | [diff] [blame] | 394 | parser.add_argument('--list', action='store_true', |
| 395 | help='List available targets and exit') |
| 396 | parser.add_argument('targets', nargs='*', metavar='TARGET', |
| 397 | help='Target file to generate (default: all; "-": none)') |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 398 | options = parser.parse_args(args) |
| 399 | generator = TestGenerator(options) |
Gilles Peskine | 0298bda | 2021-03-10 02:34:37 +0100 | [diff] [blame] | 400 | if options.list: |
| 401 | for name in sorted(generator.TARGETS): |
| 402 | print(generator.filename_for(name)) |
| 403 | return |
| 404 | if options.targets: |
| 405 | # Allow "-" as a special case so you can run |
| 406 | # ``generate_psa_tests.py - $targets`` and it works uniformly whether |
| 407 | # ``$targets`` is empty or not. |
| 408 | options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target)) |
| 409 | for target in options.targets |
| 410 | if target != '-'] |
| 411 | else: |
| 412 | options.targets = sorted(generator.TARGETS) |
| 413 | for target in options.targets: |
| 414 | generator.generate_target(target) |
Gilles Peskine | 0994049 | 2021-01-26 22:16:30 +0100 | [diff] [blame] | 415 | |
| 416 | if __name__ == '__main__': |
| 417 | main(sys.argv[1:]) |