| 1 |
# Copyright 2020, New York University and the TUF contributors |
| 2 |
# SPDX-License-Identifier: MIT OR Apache-2.0 |
| 3 |
"""Unit tests for api/metadata.py""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import json |
| 8 |
import logging |
| 9 |
import os |
| 10 |
import shutil |
| 11 |
import sys |
| 12 |
import tempfile |
| 13 |
import unittest |
| 14 |
from copy import copy, deepcopy |
| 15 |
from datetime import datetime, timedelta, timezone |
| 16 |
from pathlib import Path |
| 17 |
from typing import ClassVar |
| 18 |
|
| 19 |
from securesystemslib import exceptions as sslib_exceptions |
| 20 |
from securesystemslib.signer import ( |
| 21 |
CryptoSigner, |
| 22 |
Key, |
| 23 |
SecretsHandler, |
| 24 |
Signer, |
| 25 |
SSlibKey, |
| 26 |
) |
| 27 |
|
| 28 |
from tests import utils |
| 29 |
from tuf.api import exceptions |
| 30 |
from tuf.api.dsse import SimpleEnvelope |
| 31 |
from tuf.api.metadata import ( |
| 32 |
TOP_LEVEL_ROLE_NAMES, |
| 33 |
DelegatedRole, |
| 34 |
Delegations, |
| 35 |
Metadata, |
| 36 |
MetaFile, |
| 37 |
Root, |
| 38 |
RootVerificationResult, |
| 39 |
Signature, |
| 40 |
Snapshot, |
| 41 |
SuccinctRoles, |
| 42 |
TargetFile, |
| 43 |
Targets, |
| 44 |
Timestamp, |
| 45 |
VerificationResult, |
| 46 |
) |
| 47 |
from tuf.api.serialization import DeserializationError, SerializationError |
| 48 |
from tuf.api.serialization.json import JSONSerializer |
| 49 |
|
| 50 |
logger = logging.getLogger(__name__) |
| 51 |
|
| 52 |
|
| 53 |
class TestMetadata(unittest.TestCase): |
| 54 |
"""Tests for public API of all classes in 'tuf/api/metadata.py'.""" |
| 55 |
|
| 56 |
temporary_directory: ClassVar[str] |
| 57 |
repo_dir: ClassVar[str] |
| 58 |
keystore_dir: ClassVar[str] |
| 59 |
signers: ClassVar[dict[str, Signer]] |
| 60 |
|
| 61 |
@classmethod |
| 62 |
def setUpClass(cls) -> None: |
| 63 |
# Create a temporary directory to store the repository, metadata, and |
| 64 |
# target files. 'temporary_directory' must be deleted in |
| 65 |
# TearDownClass() so that temporary files are always removed, even when |
| 66 |
# exceptions occur. |
| 67 |
cls.temporary_directory = tempfile.mkdtemp(dir=os.getcwd()) |
| 68 |
|
| 69 |
test_repo_data = os.path.join( |
| 70 |
os.path.dirname(os.path.realpath(__file__)), "repository_data" |
| 71 |
) |
| 72 |
|
| 73 |
cls.repo_dir = os.path.join(cls.temporary_directory, "repository") |
| 74 |
shutil.copytree( |
| 75 |
os.path.join(test_repo_data, "repository"), cls.repo_dir |
| 76 |
) |
| 77 |
|
| 78 |
cls.keystore_dir = os.path.join(cls.temporary_directory, "keystore") |
| 79 |
shutil.copytree( |
| 80 |
os.path.join(test_repo_data, "keystore"), cls.keystore_dir |
| 81 |
) |
| 82 |
|
| 83 |
path = os.path.join(cls.repo_dir, "metadata", "root.json") |
| 84 |
root = Metadata[Root].from_file(path).signed |
| 85 |
|
| 86 |
# Load signers |
| 87 |
|
| 88 |
cls.signers = {} |
| 89 |
for role in [Snapshot.type, Targets.type, Timestamp.type]: |
| 90 |
uri = f"file2:{os.path.join(cls.keystore_dir, role + '_key')}" |
| 91 |
role_obj = root.get_delegated_role(role) |
| 92 |
key = root.get_key(role_obj.keyids[0]) |
| 93 |
cls.signers[role] = CryptoSigner.from_priv_key_uri(uri, key) |
| 94 |
|
| 95 |
@classmethod |
| 96 |
def tearDownClass(cls) -> None: |
| 97 |
# Remove the temporary repository directory, which should contain all |
| 98 |
# the metadata, targets, and key files generated for the test cases. |
| 99 |
shutil.rmtree(cls.temporary_directory) |
| 100 |
|
| 101 |
def test_generic_read(self) -> None: |
| 102 |
for metadata, inner_metadata_cls in [ |
| 103 |
(Root.type, Root), |
| 104 |
(Snapshot.type, Snapshot), |
| 105 |
(Timestamp.type, Timestamp), |
| 106 |
(Targets.type, Targets), |
| 107 |
]: |
| 108 |
# Load JSON-formatted metadata of each supported type from file |
| 109 |
# and from out-of-band read JSON string |
| 110 |
path = os.path.join(self.repo_dir, "metadata", metadata + ".json") |
| 111 |
md_obj = Metadata.from_file(path) |
| 112 |
with open(path, "rb") as f: |
| 113 |
md_obj2 = Metadata.from_bytes(f.read()) |
| 114 |
|
| 115 |
# Assert that both methods instantiate the right inner class for |
| 116 |
# each metadata type and ... |
| 117 |
self.assertTrue(isinstance(md_obj.signed, inner_metadata_cls)) |
| 118 |
self.assertTrue(isinstance(md_obj2.signed, inner_metadata_cls)) |
| 119 |
|
| 120 |
# ... and return the same object (compared by dict representation) |
| 121 |
self.assertDictEqual(md_obj.to_dict(), md_obj2.to_dict()) |
| 122 |
|
| 123 |
# Assert that it chokes correctly on an unknown metadata type |
| 124 |
bad_metadata_path = "bad-metadata.json" |
| 125 |
bad_metadata = {"signed": {"_type": "bad-metadata"}} |
| 126 |
bad_string = json.dumps(bad_metadata).encode("utf-8") |
| 127 |
with open(bad_metadata_path, "wb") as f: |
| 128 |
f.write(bad_string) |
| 129 |
|
| 130 |
with self.assertRaises(DeserializationError): |
| 131 |
Metadata.from_file(bad_metadata_path) |
| 132 |
with self.assertRaises(DeserializationError): |
| 133 |
Metadata.from_bytes(bad_string) |
| 134 |
|
| 135 |
os.remove(bad_metadata_path) |
| 136 |
|
| 137 |
def test_md_read_write_file_exceptions(self) -> None: |
| 138 |
# Test writing to a file with bad filename |
| 139 |
with self.assertRaises(exceptions.StorageError): |
| 140 |
Metadata.from_file("bad-metadata.json") |
| 141 |
|
| 142 |
# Test serializing to a file with bad filename |
| 143 |
with self.assertRaises(exceptions.StorageError): |
| 144 |
md = Metadata.from_file( |
| 145 |
os.path.join(self.repo_dir, "metadata", "root.json") |
| 146 |
) |
| 147 |
md.to_file("") |
| 148 |
|
| 149 |
def test_compact_json(self) -> None: |
| 150 |
path = os.path.join(self.repo_dir, "metadata", "targets.json") |
| 151 |
md_obj = Metadata.from_file(path) |
| 152 |
self.assertTrue( |
| 153 |
len(JSONSerializer(compact=True).serialize(md_obj)) |
| 154 |
< len(JSONSerializer().serialize(md_obj)) |
| 155 |
) |
| 156 |
|
| 157 |
def test_read_write_read_compare(self) -> None: |
| 158 |
for metadata in TOP_LEVEL_ROLE_NAMES: |
| 159 |
path = os.path.join(self.repo_dir, "metadata", metadata + ".json") |
| 160 |
md_obj = Metadata.from_file(path) |
| 161 |
|
| 162 |
path_2 = path + ".tmp" |
| 163 |
md_obj.to_file(path_2) |
| 164 |
md_obj_2 = Metadata.from_file(path_2) |
| 165 |
self.assertDictEqual(md_obj.to_dict(), md_obj_2.to_dict()) |
| 166 |
|
| 167 |
os.remove(path_2) |
| 168 |
|
| 169 |
def test_serialize_with_validate(self) -> None: |
| 170 |
# Assert that by changing one required attribute validation will fail. |
| 171 |
root = Metadata.from_file( |
| 172 |
os.path.join(self.repo_dir, "metadata", "root.json") |
| 173 |
) |
| 174 |
root.signed.version = 0 |
| 175 |
with self.assertRaises(SerializationError): |
| 176 |
root.to_bytes(JSONSerializer(validate=True)) |
| 177 |
|
| 178 |
def test_to_from_bytes(self) -> None: |
| 179 |
for metadata in TOP_LEVEL_ROLE_NAMES: |
| 180 |
path = os.path.join(self.repo_dir, "metadata", metadata + ".json") |
| 181 |
with open(path, "rb") as f: |
| 182 |
metadata_bytes = f.read() |
| 183 |
md_obj = Metadata.from_bytes(metadata_bytes) |
| 184 |
# Compare that from_bytes/to_bytes doesn't change the content |
| 185 |
# for two cases for the serializer: noncompact and compact. |
| 186 |
|
| 187 |
# Case 1: test noncompact by overriding the default serializer. |
| 188 |
self.assertEqual(md_obj.to_bytes(JSONSerializer()), metadata_bytes) |
| 189 |
|
| 190 |
# Case 2: test compact by using the default serializer. |
| 191 |
obj_bytes = md_obj.to_bytes() |
| 192 |
metadata_obj_2 = Metadata.from_bytes(obj_bytes) |
| 193 |
self.assertEqual(metadata_obj_2.to_bytes(), obj_bytes) |
| 194 |
|
| 195 |
def test_sign_verify(self) -> None: |
| 196 |
path = os.path.join(self.repo_dir, "metadata") |
| 197 |
root = Metadata[Root].from_file(os.path.join(path, "root.json")).signed |
| 198 |
|
| 199 |
# Locate the public keys we need from root |
| 200 |
targets_keyid = next(iter(root.roles[Targets.type].keyids)) |
| 201 |
targets_key = root.keys[targets_keyid] |
| 202 |
snapshot_keyid = next(iter(root.roles[Snapshot.type].keyids)) |
| 203 |
snapshot_key = root.keys[snapshot_keyid] |
| 204 |
timestamp_keyid = next(iter(root.roles[Timestamp.type].keyids)) |
| 205 |
timestamp_key = root.keys[timestamp_keyid] |
| 206 |
|
| 207 |
# Load sample metadata (targets) and assert ... |
| 208 |
md_obj = Metadata.from_file(os.path.join(path, "targets.json")) |
| 209 |
sig = md_obj.signatures[targets_keyid] |
| 210 |
data = md_obj.signed_bytes |
| 211 |
|
| 212 |
# ... it has a single existing signature, |
| 213 |
self.assertEqual(len(md_obj.signatures), 1) |
| 214 |
# ... which is valid for the correct key. |
| 215 |
targets_key.verify_signature(sig, data) |
| 216 |
with self.assertRaises(sslib_exceptions.VerificationError): |
| 217 |
snapshot_key.verify_signature(sig, data) |
| 218 |
|
| 219 |
# Append a new signature with the unrelated key and assert that ... |
| 220 |
snapshot_sig = md_obj.sign(self.signers[Snapshot.type], append=True) |
| 221 |
# ... there are now two signatures, and |
| 222 |
self.assertEqual(len(md_obj.signatures), 2) |
| 223 |
# ... both are valid for the corresponding keys. |
| 224 |
targets_key.verify_signature(sig, data) |
| 225 |
snapshot_key.verify_signature(snapshot_sig, data) |
| 226 |
# ... the returned (appended) signature is for snapshot key |
| 227 |
self.assertEqual(snapshot_sig.keyid, snapshot_keyid) |
| 228 |
|
| 229 |
# Create and assign (don't append) a new signature and assert that ... |
| 230 |
ts_sig = md_obj.sign(self.signers[Timestamp.type], append=False) |
| 231 |
# ... there now is only one signature, |
| 232 |
self.assertEqual(len(md_obj.signatures), 1) |
| 233 |
# ... valid for that key. |
| 234 |
timestamp_key.verify_signature(ts_sig, data) |
| 235 |
with self.assertRaises(sslib_exceptions.VerificationError): |
| 236 |
targets_key.verify_signature(ts_sig, data) |
| 237 |
|
| 238 |
def test_sign_failures(self) -> None: |
| 239 |
# Test throwing UnsignedMetadataError because of signing problems |
| 240 |
md = Metadata.from_file( |
| 241 |
os.path.join(self.repo_dir, "metadata", "snapshot.json") |
| 242 |
) |
| 243 |
|
| 244 |
class FailingSigner(Signer): |
| 245 |
@classmethod |
| 246 |
def from_priv_key_uri( |
| 247 |
cls, |
| 248 |
_priv_key_uri: str, |
| 249 |
_public_key: Key, |
| 250 |
_secrets_handler: SecretsHandler | None = None, |
| 251 |
) -> Signer: |
| 252 |
raise RuntimeError("Not a real signer") |
| 253 |
|
| 254 |
@property |
| 255 |
def public_key(self) -> Key: |
| 256 |
raise RuntimeError("Not a real signer") |
| 257 |
|
| 258 |
def sign(self, _payload: bytes) -> Signature: |
| 259 |
raise RuntimeError("signing failed") |
| 260 |
|
| 261 |
failing_signer = FailingSigner() |
| 262 |
|
| 263 |
with self.assertRaises(exceptions.UnsignedMetadataError): |
| 264 |
md.sign(failing_signer) |
| 265 |
|
| 266 |
def test_key_verify_failures(self) -> None: |
| 267 |
root_path = os.path.join(self.repo_dir, "metadata", "root.json") |
| 268 |
root = Metadata[Root].from_file(root_path).signed |
| 269 |
|
| 270 |
# Locate the timestamp public key we need from root |
| 271 |
timestamp_keyid = next(iter(root.roles[Timestamp.type].keyids)) |
| 272 |
timestamp_key = root.keys[timestamp_keyid] |
| 273 |
|
| 274 |
# Load sample metadata (timestamp) |
| 275 |
path = os.path.join(self.repo_dir, "metadata", "timestamp.json") |
| 276 |
md_obj = Metadata.from_file(path) |
| 277 |
sig = md_obj.signatures[timestamp_keyid] |
| 278 |
data = md_obj.signed_bytes |
| 279 |
|
| 280 |
# Test failure on unknown scheme (securesystemslib |
| 281 |
# UnsupportedAlgorithmError) |
| 282 |
scheme = timestamp_key.scheme |
| 283 |
timestamp_key.scheme = "foo" |
| 284 |
with self.assertRaises(sslib_exceptions.VerificationError): |
| 285 |
timestamp_key.verify_signature(sig, data) |
| 286 |
timestamp_key.scheme = scheme |
| 287 |
|
| 288 |
# Test failure on broken public key data (securesystemslib |
| 289 |
# CryptoError) |
| 290 |
public = timestamp_key.keyval["public"] |
| 291 |
timestamp_key.keyval["public"] = "ffff" |
| 292 |
with self.assertRaises(sslib_exceptions.VerificationError): |
| 293 |
timestamp_key.verify_signature(sig, data) |
| 294 |
timestamp_key.keyval["public"] = public |
| 295 |
|
| 296 |
# Test failure with invalid signature (securesystemslib |
| 297 |
# FormatError) |
| 298 |
incorrect_sig = copy(sig) |
| 299 |
incorrect_sig.signature = "foo" |
| 300 |
with self.assertRaises(sslib_exceptions.VerificationError): |
| 301 |
timestamp_key.verify_signature(incorrect_sig, data) |
| 302 |
|
| 303 |
# Test failure with valid but incorrect signature |
| 304 |
incorrect_sig.signature = "ff" * 64 |
| 305 |
with self.assertRaises(sslib_exceptions.UnverifiedSignatureError): |
| 306 |
timestamp_key.verify_signature(incorrect_sig, data) |
| 307 |
|
| 308 |
def test_metadata_signed_is_expired(self) -> None: |
| 309 |
# Use of Snapshot is arbitrary, we're just testing the base class |
| 310 |
# features with real data |
| 311 |
snapshot_path = os.path.join(self.repo_dir, "metadata", "snapshot.json") |
| 312 |
md = Metadata.from_file(snapshot_path) |
| 313 |
|
| 314 |
expected_expiry = datetime(2030, 1, 1, 0, 0, tzinfo=timezone.utc) |
| 315 |
self.assertEqual(md.signed.expires, expected_expiry) |
| 316 |
|
| 317 |
# Test is_expired with reference_time provided |
| 318 |
is_expired = md.signed.is_expired(md.signed.expires) |
| 319 |
self.assertTrue(is_expired) |
| 320 |
is_expired = md.signed.is_expired(md.signed.expires + timedelta(days=1)) |
| 321 |
self.assertTrue(is_expired) |
| 322 |
is_expired = md.signed.is_expired(md.signed.expires - timedelta(days=1)) |
| 323 |
self.assertFalse(is_expired) |
| 324 |
|
| 325 |
# Test is_expired without reference_time, |
| 326 |
# manipulating md.signed.expires |
| 327 |
expires = md.signed.expires |
| 328 |
md.signed.expires = datetime.now(timezone.utc) |
| 329 |
is_expired = md.signed.is_expired() |
| 330 |
self.assertTrue(is_expired) |
| 331 |
md.signed.expires = datetime.now(timezone.utc) + timedelta(days=1) |
| 332 |
is_expired = md.signed.is_expired() |
| 333 |
self.assertFalse(is_expired) |
| 334 |
md.signed.expires = expires |
| 335 |
|
| 336 |
def test_metadata_verify_delegate(self) -> None: |
| 337 |
root_path = os.path.join(self.repo_dir, "metadata", "root.json") |
| 338 |
root = Metadata[Root].from_file(root_path) |
| 339 |
snapshot_path = os.path.join(self.repo_dir, "metadata", "snapshot.json") |
| 340 |
snapshot = Metadata[Snapshot].from_file(snapshot_path) |
| 341 |
targets_path = os.path.join(self.repo_dir, "metadata", "targets.json") |
| 342 |
targets = Metadata[Targets].from_file(targets_path) |
| 343 |
role1_path = os.path.join(self.repo_dir, "metadata", "role1.json") |
| 344 |
role1 = Metadata[Targets].from_file(role1_path) |
| 345 |
role2_path = os.path.join(self.repo_dir, "metadata", "role2.json") |
| 346 |
role2 = Metadata[Targets].from_file(role2_path) |
| 347 |
|
| 348 |
# test the expected delegation tree |
| 349 |
root.verify_delegate(Root.type, root) |
| 350 |
root.verify_delegate(Snapshot.type, snapshot) |
| 351 |
root.verify_delegate(Targets.type, targets) |
| 352 |
targets.verify_delegate("role1", role1) |
| 353 |
role1.verify_delegate("role2", role2) |
| 354 |
|
| 355 |
# only root and targets can verify delegates |
| 356 |
with self.assertRaises(TypeError): |
| 357 |
snapshot.verify_delegate(Snapshot.type, snapshot) |
| 358 |
# verify fails for roles that are not delegated by delegator |
| 359 |
with self.assertRaises(ValueError): |
| 360 |
root.verify_delegate("role1", role1) |
| 361 |
with self.assertRaises(ValueError): |
| 362 |
targets.verify_delegate(Targets.type, targets) |
| 363 |
# verify fails when delegator has no delegations |
| 364 |
with self.assertRaises(ValueError): |
| 365 |
role2.verify_delegate("role1", role1) |
| 366 |
|
| 367 |
def test_signed_verify_delegate(self) -> None: |
| 368 |
root_path = os.path.join(self.repo_dir, "metadata", "root.json") |
| 369 |
root_md = Metadata[Root].from_file(root_path) |
| 370 |
root = root_md.signed |
| 371 |
snapshot_path = os.path.join(self.repo_dir, "metadata", "snapshot.json") |
| 372 |
snapshot_md = Metadata[Snapshot].from_file(snapshot_path) |
| 373 |
snapshot = snapshot_md.signed |
| 374 |
targets_path = os.path.join(self.repo_dir, "metadata", "targets.json") |
| 375 |
targets_md = Metadata[Targets].from_file(targets_path) |
| 376 |
targets = targets_md.signed |
| 377 |
role1_path = os.path.join(self.repo_dir, "metadata", "role1.json") |
| 378 |
role1_md = Metadata[Targets].from_file(role1_path) |
| 379 |
role1 = role1_md.signed |
| 380 |
role2_path = os.path.join(self.repo_dir, "metadata", "role2.json") |
| 381 |
role2_md = Metadata[Targets].from_file(role2_path) |
| 382 |
role2 = role2_md.signed |
| 383 |
|
| 384 |
# test the expected delegation tree |
| 385 |
root.verify_delegate( |
| 386 |
Root.type, root_md.signed_bytes, root_md.signatures |
| 387 |
) |
| 388 |
root.verify_delegate( |
| 389 |
Snapshot.type, snapshot_md.signed_bytes, snapshot_md.signatures |
| 390 |
) |
| 391 |
root.verify_delegate( |
| 392 |
Targets.type, targets_md.signed_bytes, targets_md.signatures |
| 393 |
) |
| 394 |
targets.verify_delegate( |
| 395 |
"role1", role1_md.signed_bytes, role1_md.signatures |
| 396 |
) |
| 397 |
role1.verify_delegate( |
| 398 |
"role2", role2_md.signed_bytes, role2_md.signatures |
| 399 |
) |
| 400 |
|
| 401 |
# only root and targets can verify delegates |
| 402 |
with self.assertRaises(AttributeError): |
| 403 |
snapshot.verify_delegate( |
| 404 |
Snapshot.type, snapshot_md.signed_bytes, snapshot_md.signatures |
| 405 |
) |
| 406 |
# verify fails for roles that are not delegated by delegator |
| 407 |
with self.assertRaises(ValueError): |
| 408 |
root.verify_delegate( |
| 409 |
"role1", role1_md.signed_bytes, role1_md.signatures |
| 410 |
) |
| 411 |
with self.assertRaises(ValueError): |
| 412 |
targets.verify_delegate( |
| 413 |
Targets.type, targets_md.signed_bytes, targets_md.signatures |
| 414 |
) |
| 415 |
# verify fails when delegator has no delegations |
| 416 |
with self.assertRaises(ValueError): |
| 417 |
role2.verify_delegate( |
| 418 |
"role1", role1_md.signed_bytes, role1_md.signatures |
| 419 |
) |
| 420 |
|
| 421 |
# verify fails when delegate content is modified |
| 422 |
expires = snapshot.expires |
| 423 |
snapshot.expires = expires + timedelta(days=1) |
| 424 |
with self.assertRaises(exceptions.UnsignedMetadataError): |
| 425 |
root.verify_delegate( |
| 426 |
Snapshot.type, snapshot_md.signed_bytes, snapshot_md.signatures |
| 427 |
) |
| 428 |
snapshot.expires = expires |
| 429 |
|
| 430 |
# verify fails if sslib verify fails with VerificationError |
| 431 |
# (in this case signature is malformed) |
| 432 |
keyid = next(iter(root.roles[Snapshot.type].keyids)) |
| 433 |
good_sig = snapshot_md.signatures[keyid].signature |
| 434 |
snapshot_md.signatures[keyid].signature = "foo" |
| 435 |
with self.assertRaises(exceptions.UnsignedMetadataError): |
| 436 |
root.verify_delegate( |
| 437 |
Snapshot.type, snapshot_md.signed_bytes, snapshot_md.signatures |
| 438 |
) |
| 439 |
snapshot_md.signatures[keyid].signature = good_sig |
| 440 |
|
| 441 |
# verify fails if roles keys do not sign the metadata |
| 442 |
with self.assertRaises(exceptions.UnsignedMetadataError): |
| 443 |
root.verify_delegate( |
| 444 |
Timestamp.type, snapshot_md.signed_bytes, snapshot_md.signatures |
| 445 |
) |
| 446 |
|
| 447 |
# Add a key to snapshot role, make sure the new sig fails to verify |
| 448 |
ts_keyid = next(iter(root.roles[Timestamp.type].keyids)) |
| 449 |
root.add_key(root.keys[ts_keyid], Snapshot.type) |
| 450 |
snapshot_md.signatures[ts_keyid] = Signature(ts_keyid, "ff" * 64) |
| 451 |
|
| 452 |
# verify succeeds if threshold is reached even if some signatures |
| 453 |
# fail to verify |
| 454 |
root.verify_delegate( |
| 455 |
Snapshot.type, snapshot_md.signed_bytes, snapshot_md.signatures |
| 456 |
) |
| 457 |
|
| 458 |
# verify fails if threshold of signatures is not reached |
| 459 |
root.roles[Snapshot.type].threshold = 2 |
| 460 |
with self.assertRaises(exceptions.UnsignedMetadataError): |
| 461 |
root.verify_delegate( |
| 462 |
Snapshot.type, snapshot_md.signed_bytes, snapshot_md.signatures |
| 463 |
) |
| 464 |
|
| 465 |
# verify succeeds when we correct the new signature and reach the |
| 466 |
# threshold of 2 keys |
| 467 |
snapshot_md.sign(self.signers[Timestamp.type], append=True) |
| 468 |
root.verify_delegate( |
| 469 |
Snapshot.type, snapshot_md.signed_bytes, snapshot_md.signatures |
| 470 |
) |
| 471 |
|
| 472 |
def test_verification_result(self) -> None: |
| 473 |
key = SSlibKey("", "", "", {"public": ""}) |
| 474 |
vr = VerificationResult(3, {"a": key}, {"b": key}) |
| 475 |
self.assertEqual(vr.missing, 2) |
| 476 |
self.assertFalse(vr.verified) |
| 477 |
self.assertFalse(vr) |
| 478 |
|
| 479 |
# Add a signature |
| 480 |
vr.signed["c"] = key |
| 481 |
self.assertEqual(vr.missing, 1) |
| 482 |
self.assertFalse(vr.verified) |
| 483 |
self.assertFalse(vr) |
| 484 |
|
| 485 |
# Add last missing signature |
| 486 |
vr.signed["d"] = key |
| 487 |
self.assertEqual(vr.missing, 0) |
| 488 |
self.assertTrue(vr.verified) |
| 489 |
self.assertTrue(vr) |
| 490 |
|
| 491 |
# Add one more signature |
| 492 |
vr.signed["e"] = key |
| 493 |
self.assertEqual(vr.missing, 0) |
| 494 |
self.assertTrue(vr.verified) |
| 495 |
self.assertTrue(vr) |
| 496 |
|
| 497 |
def test_root_verification_result(self) -> None: |
| 498 |
key = SSlibKey("", "", "", {"public": ""}) |
| 499 |
vr1 = VerificationResult(3, {"a": key}, {"b": key}) |
| 500 |
vr2 = VerificationResult(1, {"c": key}, {"b": key}) |
| 501 |
|
| 502 |
vr = RootVerificationResult(vr1, vr2) |
| 503 |
self.assertEqual(vr.signed, {"a": key, "c": key}) |
| 504 |
self.assertEqual(vr.unsigned, {"b": key}) |
| 505 |
self.assertFalse(vr.verified) |
| 506 |
self.assertFalse(vr) |
| 507 |
|
| 508 |
vr1.signed["c"] = key |
| 509 |
vr1.signed["f"] = key |
| 510 |
self.assertEqual(vr.signed, {"a": key, "c": key, "f": key}) |
| 511 |
self.assertEqual(vr.unsigned, {"b": key}) |
| 512 |
self.assertTrue(vr.verified) |
| 513 |
self.assertTrue(vr) |
| 514 |
|
| 515 |
def test_signed_get_verification_result(self) -> None: |
| 516 |
# Setup: Load test metadata and keys |
| 517 |
root_path = os.path.join(self.repo_dir, "metadata", "root.json") |
| 518 |
root = Metadata[Root].from_file(root_path) |
| 519 |
|
| 520 |
key1_id = root.signed.roles[Root.type].keyids[0] |
| 521 |
key1 = root.signed.get_key(key1_id) |
| 522 |
|
| 523 |
key2_id = root.signed.roles[Timestamp.type].keyids[0] |
| 524 |
key2 = root.signed.get_key(key2_id) |
| 525 |
|
| 526 |
key3_id = "123456789abcdefg" |
| 527 |
|
| 528 |
key4_id = self.signers[Snapshot.type].public_key.keyid |
| 529 |
|
| 530 |
# Test: 1 authorized key, 1 valid signature |
| 531 |
result = root.signed.get_verification_result( |
| 532 |
Root.type, root.signed_bytes, root.signatures |
| 533 |
) |
| 534 |
self.assertTrue(result) |
| 535 |
self.assertEqual(result.signed, {key1_id: key1}) |
| 536 |
self.assertEqual(result.unsigned, {}) |
| 537 |
|
| 538 |
# Test: 2 authorized keys, 1 invalid signature |
| 539 |
# Adding a key, i.e. metadata change, invalidates existing signature |
| 540 |
root.signed.add_key(key2, Root.type) |
| 541 |
result = root.signed.get_verification_result( |
| 542 |
Root.type, root.signed_bytes, root.signatures |
| 543 |
) |
| 544 |
self.assertFalse(result) |
| 545 |
self.assertEqual(result.signed, {}) |
| 546 |
self.assertEqual(result.unsigned, {key1_id: key1, key2_id: key2}) |
| 547 |
|
| 548 |
# Test: 3 authorized keys, 1 invalid signature, 1 key missing key data |
| 549 |
# Adding a keyid w/o key, fails verification but this key is not listed |
| 550 |
# in unsigned |
| 551 |
root.signed.roles[Root.type].keyids.append(key3_id) |
| 552 |
result = root.signed.get_verification_result( |
| 553 |
Root.type, root.signed_bytes, root.signatures |
| 554 |
) |
| 555 |
self.assertFalse(result) |
| 556 |
self.assertEqual(result.signed, {}) |
| 557 |
self.assertEqual(result.unsigned, {key1_id: key1, key2_id: key2}) |
| 558 |
|
| 559 |
# Test: 3 authorized keys, 1 valid signature, 1 invalid signature, 1 |
| 560 |
# key missing key data |
| 561 |
root.sign(self.signers[Timestamp.type], append=True) |
| 562 |
result = root.signed.get_verification_result( |
| 563 |
Root.type, root.signed_bytes, root.signatures |
| 564 |
) |
| 565 |
self.assertTrue(result) |
| 566 |
self.assertEqual(result.signed, {key2_id: key2}) |
| 567 |
self.assertEqual(result.unsigned, {key1_id: key1}) |
| 568 |
|
| 569 |
# Test: 3 authorized keys, 1 valid signature, 1 invalid signature, 1 |
| 570 |
# key missing key data, 1 ignored unrelated signature |
| 571 |
root.sign(self.signers[Snapshot.type], append=True) |
| 572 |
self.assertEqual( |
| 573 |
set(root.signatures.keys()), {key1_id, key2_id, key4_id} |
| 574 |
) |
| 575 |
self.assertTrue(result) |
| 576 |
self.assertEqual(result.signed, {key2_id: key2}) |
| 577 |
self.assertEqual(result.unsigned, {key1_id: key1}) |
| 578 |
|
| 579 |
# See test_signed_verify_delegate for more related tests ... |
| 580 |
|
| 581 |
def test_root_get_root_verification_result(self) -> None: |
| 582 |
# Setup: Load test metadata and keys |
| 583 |
root_path = os.path.join(self.repo_dir, "metadata", "root.json") |
| 584 |
root = Metadata[Root].from_file(root_path) |
| 585 |
|
| 586 |
key1_id = root.signed.roles[Root.type].keyids[0] |
| 587 |
key1 = root.signed.get_key(key1_id) |
| 588 |
|
| 589 |
key2_id = root.signed.roles[Timestamp.type].keyids[0] |
| 590 |
key2 = root.signed.get_key(key2_id) |
| 591 |
|
| 592 |
# Test: Verify with no previous root version |
| 593 |
result = root.signed.get_root_verification_result( |
| 594 |
None, root.signed_bytes, root.signatures |
| 595 |
) |
| 596 |
self.assertTrue(result) |
| 597 |
self.assertEqual(result.signed, {key1_id: key1}) |
| 598 |
self.assertEqual(result.unsigned, {}) |
| 599 |
|
| 600 |
# Test: Verify with other root that is not version N-1 |
| 601 |
prev_root: Metadata[Root] = deepcopy(root) |
| 602 |
with self.assertRaises(ValueError): |
| 603 |
result = root.signed.get_root_verification_result( |
| 604 |
prev_root.signed, root.signed_bytes, root.signatures |
| 605 |
) |
| 606 |
|
| 607 |
# Test: Verify with previous root |
| 608 |
prev_root.signed.version -= 1 |
| 609 |
result = root.signed.get_root_verification_result( |
| 610 |
prev_root.signed, root.signed_bytes, root.signatures |
| 611 |
) |
| 612 |
self.assertTrue(result) |
| 613 |
self.assertEqual(result.signed, {key1_id: key1}) |
| 614 |
self.assertEqual(result.unsigned, {}) |
| 615 |
|
| 616 |
# Test: Add a signer to previous root (threshold still 1) |
| 617 |
prev_root.signed.add_key(key2, Root.type) |
| 618 |
result = root.signed.get_root_verification_result( |
| 619 |
prev_root.signed, root.signed_bytes, root.signatures |
| 620 |
) |
| 621 |
self.assertTrue(result) |
| 622 |
self.assertEqual(result.signed, {key1_id: key1}) |
| 623 |
self.assertEqual(result.unsigned, {key2_id: key2}) |
| 624 |
|
| 625 |
# Test: Increase threshold in previous root |
| 626 |
prev_root.signed.roles[Root.type].threshold += 1 |
| 627 |
result = root.signed.get_root_verification_result( |
| 628 |
prev_root.signed, root.signed_bytes, root.signatures |
| 629 |
) |
| 630 |
self.assertFalse(result) |
| 631 |
self.assertEqual(result.signed, {key1_id: key1}) |
| 632 |
self.assertEqual(result.unsigned, {key2_id: key2}) |
| 633 |
|
| 634 |
# Test: Sign root with both keys |
| 635 |
root.sign(self.signers[Timestamp.type], append=True) |
| 636 |
result = root.signed.get_root_verification_result( |
| 637 |
prev_root.signed, root.signed_bytes, root.signatures |
| 638 |
) |
| 639 |
self.assertTrue(result) |
| 640 |
self.assertEqual(result.signed, {key1_id: key1, key2_id: key2}) |
| 641 |
self.assertEqual(result.unsigned, {}) |
| 642 |
|
| 643 |
# Test: Sign root with an unrelated key |
| 644 |
root.sign(self.signers[Snapshot.type], append=True) |
| 645 |
result = root.signed.get_root_verification_result( |
| 646 |
prev_root.signed, root.signed_bytes, root.signatures |
| 647 |
) |
| 648 |
self.assertTrue(result) |
| 649 |
self.assertEqual(result.signed, {key1_id: key1, key2_id: key2}) |
| 650 |
self.assertEqual(result.unsigned, {}) |
| 651 |
|
| 652 |
# Test: Remove key1 from previous root |
| 653 |
prev_root.signed.revoke_key(key1_id, Root.type) |
| 654 |
result = root.signed.get_root_verification_result( |
| 655 |
prev_root.signed, root.signed_bytes, root.signatures |
| 656 |
) |
| 657 |
self.assertFalse(result) |
| 658 |
self.assertEqual(result.signed, {key1_id: key1, key2_id: key2}) |
| 659 |
self.assertEqual(result.unsigned, {}) |
| 660 |
|
| 661 |
# Test: Lower threshold in previous root |
| 662 |
prev_root.signed.roles[Root.type].threshold -= 1 |
| 663 |
result = root.signed.get_root_verification_result( |
| 664 |
prev_root.signed, root.signed_bytes, root.signatures |
| 665 |
) |
| 666 |
self.assertTrue(result) |
| 667 |
self.assertEqual(result.signed, {key1_id: key1, key2_id: key2}) |
| 668 |
self.assertEqual(result.unsigned, {}) |
| 669 |
|
| 670 |
def test_root_add_key_and_revoke_key(self) -> None: |
| 671 |
root_path = os.path.join(self.repo_dir, "metadata", "root.json") |
| 672 |
root = Metadata[Root].from_file(root_path) |
| 673 |
|
| 674 |
# Create a new key |
| 675 |
signer = CryptoSigner.generate_ecdsa() |
| 676 |
key = signer.public_key |
| 677 |
|
| 678 |
# Assert that root does not contain the new key |
| 679 |
self.assertNotIn(key.keyid, root.signed.roles[Root.type].keyids) |
| 680 |
self.assertNotIn(key.keyid, root.signed.keys) |
| 681 |
|
| 682 |
# Assert that add_key with old argument order will raise an error |
| 683 |
with self.assertRaises(ValueError): |
| 684 |
root.signed.add_key(Root.type, key) # type: ignore [arg-type] |
| 685 |
|
| 686 |
# Add new root key |
| 687 |
root.signed.add_key(key, Root.type) |
| 688 |
|
| 689 |
# Assert that key is added |
| 690 |
self.assertIn(key.keyid, root.signed.roles[Root.type].keyids) |
| 691 |
self.assertIn(key.keyid, root.signed.keys) |
| 692 |
|
| 693 |
# Confirm that the newly added key does not break |
| 694 |
# the object serialization |
| 695 |
root.to_dict() |
| 696 |
|
| 697 |
# Try adding the same key again and assert its ignored. |
| 698 |
pre_add_keyid = root.signed.roles[Root.type].keyids.copy() |
| 699 |
root.signed.add_key(key, Root.type) |
| 700 |
self.assertEqual(pre_add_keyid, root.signed.roles[Root.type].keyids) |
| 701 |
|
| 702 |
# Add the same key to targets role as well |
| 703 |
root.signed.add_key(key, Targets.type) |
| 704 |
|
| 705 |
# Add the same key to a nonexistent role. |
| 706 |
with self.assertRaises(ValueError): |
| 707 |
root.signed.add_key(key, "nosuchrole") |
| 708 |
|
| 709 |
# Remove the key from root role (targets role still uses it) |
| 710 |
root.signed.revoke_key(key.keyid, Root.type) |
| 711 |
self.assertNotIn(key.keyid, root.signed.roles[Root.type].keyids) |
| 712 |
self.assertIn(key.keyid, root.signed.keys) |
| 713 |
|
| 714 |
# Remove the key from targets as well |
| 715 |
root.signed.revoke_key(key.keyid, Targets.type) |
| 716 |
self.assertNotIn(key.keyid, root.signed.roles[Targets.type].keyids) |
| 717 |
self.assertNotIn(key.keyid, root.signed.keys) |
| 718 |
|
| 719 |
with self.assertRaises(ValueError): |
| 720 |
root.signed.revoke_key("nosuchkey", Root.type) |
| 721 |
with self.assertRaises(ValueError): |
| 722 |
root.signed.revoke_key(key.keyid, "nosuchrole") |
| 723 |
|
| 724 |
def test_is_target_in_pathpattern(self) -> None: |
| 725 |
supported_use_cases = [ |
| 726 |
("foo.tgz", "foo.tgz"), |
| 727 |
("foo.tgz", "*"), |
| 728 |
("foo.tgz", "*.tgz"), |
| 729 |
("foo-version-a.tgz", "foo-version-?.tgz"), |
| 730 |
("targets/foo.tgz", "targets/*.tgz"), |
| 731 |
("foo/bar/zoo/k.tgz", "foo/bar/zoo/*"), |
| 732 |
("foo/bar/zoo/k.tgz", "foo/*/zoo/*"), |
| 733 |
("foo/bar/zoo/k.tgz", "*/*/*/*"), |
| 734 |
("foo/bar", "f?o/bar"), |
| 735 |
("foo/bar", "*o/bar"), |
| 736 |
] |
| 737 |
for targetpath, pathpattern in supported_use_cases: |
| 738 |
self.assertTrue( |
| 739 |
DelegatedRole._is_target_in_pathpattern(targetpath, pathpattern) |
| 740 |
) |
| 741 |
|
| 742 |
invalid_use_cases = [ |
| 743 |
("targets/foo.tgz", "*.tgz"), |
| 744 |
("/foo.tgz", "*.tgz"), |
| 745 |
("targets/foo.tgz", "*"), |
| 746 |
("foo-version-alpha.tgz", "foo-version-?.tgz"), |
| 747 |
("foo//bar", "*/bar"), |
| 748 |
("foo/bar", "f?/bar"), |
| 749 |
("FOO.tgz", "foo.tgz"), |
| 750 |
("foo/bar", "Foo/*"), |
| 751 |
] |
| 752 |
for targetpath, pathpattern in invalid_use_cases: |
| 753 |
self.assertFalse( |
| 754 |
DelegatedRole._is_target_in_pathpattern(targetpath, pathpattern) |
| 755 |
) |
| 756 |
|
| 757 |
def test_targets_key_api(self) -> None: |
| 758 |
targets_path = os.path.join(self.repo_dir, "metadata", "targets.json") |
| 759 |
targets: Targets = Metadata[Targets].from_file(targets_path).signed |
| 760 |
|
| 761 |
# Add a new delegated role "role2" in targets |
| 762 |
delegated_role = DelegatedRole.from_dict( |
| 763 |
{ |
| 764 |
"keyids": [], |
| 765 |
"name": "role2", |
| 766 |
"paths": ["fn3", "fn4"], |
| 767 |
"terminating": False, |
| 768 |
"threshold": 1, |
| 769 |
} |
| 770 |
) |
| 771 |
assert isinstance(targets.delegations, Delegations) |
| 772 |
assert isinstance(targets.delegations.roles, dict) |
| 773 |
targets.delegations.roles["role2"] = delegated_role |
| 774 |
|
| 775 |
key_dict = { |
| 776 |
"keytype": "ed25519", |
| 777 |
"keyval": { |
| 778 |
"public": "edcd0a32a07dce33f7c7873aaffbff36d20ea30787574ead335eefd337e4dacd" |
| 779 |
}, |
| 780 |
"scheme": "ed25519", |
| 781 |
} |
| 782 |
key = Key.from_dict("id2", key_dict) |
| 783 |
|
| 784 |
# Assert that add_key with old argument order will raise an error |
| 785 |
with self.assertRaises(ValueError): |
| 786 |
targets.add_key(Root.type, key) # type: ignore [arg-type] |
| 787 |
|
| 788 |
# Assert that delegated role "role1" does not contain the new key |
| 789 |
self.assertNotIn(key.keyid, targets.delegations.roles["role1"].keyids) |
| 790 |
targets.add_key(key, "role1") |
| 791 |
|
| 792 |
# Assert that the new key is added to the delegated role "role1" |
| 793 |
self.assertIn(key.keyid, targets.delegations.roles["role1"].keyids) |
| 794 |
|
| 795 |
# Confirm that the newly added key does not break the obj serialization |
| 796 |
targets.to_dict() |
| 797 |
|
| 798 |
# Try adding the same key again and assert its ignored. |
| 799 |
past_keyid = targets.delegations.roles["role1"].keyids.copy() |
| 800 |
targets.add_key(key, "role1") |
| 801 |
self.assertEqual(past_keyid, targets.delegations.roles["role1"].keyids) |
| 802 |
|
| 803 |
# Try adding a key to a delegated role that doesn't exists |
| 804 |
with self.assertRaises(ValueError): |
| 805 |
targets.add_key(key, "nosuchrole") |
| 806 |
|
| 807 |
# Add the same key to "role2" as well |
| 808 |
targets.add_key(key, "role2") |
| 809 |
|
| 810 |
# Remove the key from "role1" role ("role2" still uses it) |
| 811 |
targets.revoke_key(key.keyid, "role1") |
| 812 |
|
| 813 |
# Assert that delegated role "role1" doesn't contain the key. |
| 814 |
self.assertNotIn(key.keyid, targets.delegations.roles["role1"].keyids) |
| 815 |
self.assertIn(key.keyid, targets.delegations.roles["role2"].keyids) |
| 816 |
|
| 817 |
# Remove the key from "role2" as well |
| 818 |
targets.revoke_key(key.keyid, "role2") |
| 819 |
self.assertNotIn(key.keyid, targets.delegations.roles["role2"].keyids) |
| 820 |
|
| 821 |
# Try remove key not used by "role1" |
| 822 |
with self.assertRaises(ValueError): |
| 823 |
targets.revoke_key(key.keyid, "role1") |
| 824 |
|
| 825 |
# Try removing a key from delegated role that doesn't exists |
| 826 |
with self.assertRaises(ValueError): |
| 827 |
targets.revoke_key(key.keyid, "nosuchrole") |
| 828 |
|
| 829 |
# Remove delegations as a whole |
| 830 |
targets.delegations = None |
| 831 |
# Test that calling add_key and revoke_key throws an error |
| 832 |
# and that delegations is still None after each of the api calls |
| 833 |
with self.assertRaises(ValueError): |
| 834 |
targets.add_key(key, "role1") |
| 835 |
self.assertTrue(targets.delegations is None) |
| 836 |
with self.assertRaises(ValueError): |
| 837 |
targets.revoke_key(key.keyid, "role1") |
| 838 |
self.assertTrue(targets.delegations is None) |
| 839 |
|
| 840 |
def test_targets_key_api_with_succinct_roles(self) -> None: |
| 841 |
targets_path = os.path.join(self.repo_dir, "metadata", "targets.json") |
| 842 |
targets: Targets = Metadata[Targets].from_file(targets_path).signed |
| 843 |
key_dict = { |
| 844 |
"keytype": "ed25519", |
| 845 |
"keyval": { |
| 846 |
"public": "edcd0a32a07dce33f7c7873aaffbff36d20ea30787574ead335eefd337e4dacd" |
| 847 |
}, |
| 848 |
"scheme": "ed25519", |
| 849 |
} |
| 850 |
key = Key.from_dict("id2", key_dict) |
| 851 |
|
| 852 |
# Remove delegated roles. |
| 853 |
assert targets.delegations is not None |
| 854 |
assert targets.delegations.roles is not None |
| 855 |
targets.delegations.roles = None |
| 856 |
targets.delegations.keys = {} |
| 857 |
|
| 858 |
# Add succinct_roles information. |
| 859 |
targets.delegations.succinct_roles = SuccinctRoles([], 1, 8, "foo") |
| 860 |
self.assertEqual(len(targets.delegations.keys), 0) |
| 861 |
self.assertEqual(len(targets.delegations.succinct_roles.keyids), 0) |
| 862 |
|
| 863 |
# Add a key to succinct_roles and verify it's saved. |
| 864 |
targets.add_key(key) |
| 865 |
self.assertIn(key.keyid, targets.delegations.keys) |
| 866 |
self.assertIn(key.keyid, targets.delegations.succinct_roles.keyids) |
| 867 |
self.assertEqual(len(targets.delegations.keys), 1) |
| 868 |
|
| 869 |
# Try adding the same key again and verify that noting is added. |
| 870 |
targets.add_key(key) |
| 871 |
self.assertEqual(len(targets.delegations.keys), 1) |
| 872 |
|
| 873 |
# Remove the key and verify it's not stored anymore. |
| 874 |
targets.revoke_key(key.keyid) |
| 875 |
self.assertNotIn(key.keyid, targets.delegations.keys) |
| 876 |
self.assertNotIn(key.keyid, targets.delegations.succinct_roles.keyids) |
| 877 |
self.assertEqual(len(targets.delegations.keys), 0) |
| 878 |
|
| 879 |
# Try removing it again. |
| 880 |
with self.assertRaises(ValueError): |
| 881 |
targets.revoke_key(key.keyid) |
| 882 |
|
| 883 |
def test_length_and_hash_validation(self) -> None: |
| 884 |
# Test metadata files' hash and length verification. |
| 885 |
# Use timestamp to get a MetaFile object and snapshot |
| 886 |
# for untrusted metadata file to verify. |
| 887 |
timestamp_path = os.path.join( |
| 888 |
self.repo_dir, "metadata", "timestamp.json" |
| 889 |
) |
| 890 |
timestamp = Metadata[Timestamp].from_file(timestamp_path) |
| 891 |
snapshot_metafile = timestamp.signed.snapshot_meta |
| 892 |
|
| 893 |
snapshot_path = os.path.join(self.repo_dir, "metadata", "snapshot.json") |
| 894 |
|
| 895 |
with open(snapshot_path, "rb") as file: |
| 896 |
# test with data as a file object |
| 897 |
snapshot_metafile.verify_length_and_hashes(file) |
| 898 |
file.seek(0) |
| 899 |
data = file.read() |
| 900 |
# test with data as bytes |
| 901 |
snapshot_metafile.verify_length_and_hashes(data) |
| 902 |
|
| 903 |
# test with custom blake algorithm |
| 904 |
snapshot_metafile.hashes = { |
| 905 |
"blake2b-256": "963a3c31aad8e2a91cfc603fdba12555e48dd0312674ac48cce2c19c243236a1" |
| 906 |
} |
| 907 |
snapshot_metafile.verify_length_and_hashes(data) |
| 908 |
|
| 909 |
# test exceptions |
| 910 |
expected_length = snapshot_metafile.length |
| 911 |
snapshot_metafile.length = 2345 |
| 912 |
with self.assertRaises(exceptions.LengthOrHashMismatchError): |
| 913 |
snapshot_metafile.verify_length_and_hashes(data) |
| 914 |
|
| 915 |
snapshot_metafile.length = expected_length |
| 916 |
snapshot_metafile.hashes = {"sha256": "incorrecthash"} |
| 917 |
with self.assertRaises(exceptions.LengthOrHashMismatchError): |
| 918 |
snapshot_metafile.verify_length_and_hashes(data) |
| 919 |
|
| 920 |
snapshot_metafile.hashes = { |
| 921 |
"unsupported-alg": "8f88e2ba48b412c3843e9bb26e1b6f8fc9e98aceb0fbaa97ba37b4c98717d7ab" |
| 922 |
} |
| 923 |
with self.assertRaises(exceptions.LengthOrHashMismatchError): |
| 924 |
snapshot_metafile.verify_length_and_hashes(data) |
| 925 |
|
| 926 |
# Test wrong algorithm format (sslib.FormatError) |
| 927 |
snapshot_metafile.hashes = { |
| 928 |
256: "8f88e2ba48b412c3843e9bb26e1b6f8fc9e98aceb0fbaa97ba37b4c98717d7ab" # type: ignore[dict-item] |
| 929 |
} |
| 930 |
with self.assertRaises(exceptions.LengthOrHashMismatchError): |
| 931 |
snapshot_metafile.verify_length_and_hashes(data) |
| 932 |
|
| 933 |
# test optional length and hashes |
| 934 |
snapshot_metafile.length = None |
| 935 |
snapshot_metafile.hashes = None |
| 936 |
snapshot_metafile.verify_length_and_hashes(data) |
| 937 |
|
| 938 |
# Test target files' hash and length verification |
| 939 |
targets_path = os.path.join(self.repo_dir, "metadata", "targets.json") |
| 940 |
targets = Metadata[Targets].from_file(targets_path) |
| 941 |
file1_targetfile = targets.signed.targets["file1.txt"] |
| 942 |
filepath = os.path.join(self.repo_dir, Targets.type, "file1.txt") |
| 943 |
|
| 944 |
with open(filepath, "rb") as file1: |
| 945 |
file1_targetfile.verify_length_and_hashes(file1) |
| 946 |
|
| 947 |
# test exceptions |
| 948 |
expected_length = file1_targetfile.length |
| 949 |
file1_targetfile.length = 2345 |
| 950 |
with self.assertRaises(exceptions.LengthOrHashMismatchError): |
| 951 |
file1_targetfile.verify_length_and_hashes(file1) |
| 952 |
|
| 953 |
file1_targetfile.length = expected_length |
| 954 |
file1_targetfile.hashes = {"sha256": "incorrecthash"} |
| 955 |
with self.assertRaises(exceptions.LengthOrHashMismatchError): |
| 956 |
file1_targetfile.verify_length_and_hashes(file1) |
| 957 |
|
| 958 |
def test_targetfile_from_file(self) -> None: |
| 959 |
# Test with an existing file and valid hash algorithm |
| 960 |
file_path = os.path.join(self.repo_dir, Targets.type, "file1.txt") |
| 961 |
targetfile_from_file = TargetFile.from_file( |
| 962 |
file_path, file_path, ["sha256"] |
| 963 |
) |
| 964 |
|
| 965 |
with open(file_path, "rb") as file: |
| 966 |
targetfile_from_file.verify_length_and_hashes(file) |
| 967 |
|
| 968 |
# Test with a non-existing file |
| 969 |
file_path = os.path.join(self.repo_dir, Targets.type, "file123.txt") |
| 970 |
with self.assertRaises(FileNotFoundError): |
| 971 |
TargetFile.from_file(file_path, file_path, ["sha256"]) |
| 972 |
|
| 973 |
# Test with an unsupported algorithm |
| 974 |
file_path = os.path.join(self.repo_dir, Targets.type, "file1.txt") |
| 975 |
with self.assertRaises(ValueError): |
| 976 |
TargetFile.from_file(file_path, file_path, ["123"]) |
| 977 |
|
| 978 |
def test_targetfile_custom(self) -> None: |
| 979 |
# Test creating TargetFile and accessing custom. |
| 980 |
targetfile = TargetFile( |
| 981 |
100, {"sha256": "abc"}, "file.txt", {"custom": "foo"} |
| 982 |
) |
| 983 |
self.assertEqual(targetfile.custom, "foo") |
| 984 |
|
| 985 |
def test_targetfile_from_data(self) -> None: |
| 986 |
data = b"Inline test content" |
| 987 |
target_file_path = os.path.join( |
| 988 |
self.repo_dir, Targets.type, "file1.txt" |
| 989 |
) |
| 990 |
|
| 991 |
# Test with a valid hash algorithm |
| 992 |
targetfile_from_data = TargetFile.from_data( |
| 993 |
target_file_path, data, ["sha256"] |
| 994 |
) |
| 995 |
targetfile_from_data.verify_length_and_hashes(data) |
| 996 |
|
| 997 |
# Test with no algorithms specified |
| 998 |
targetfile_from_data = TargetFile.from_data(target_file_path, data) |
| 999 |
targetfile_from_data.verify_length_and_hashes(data) |
| 1000 |
|
| 1001 |
# Test with custom blake hash algorithm |
| 1002 |
targetfile_from_data = TargetFile.from_data( |
| 1003 |
target_file_path, data, ["blake2b-256"] |
| 1004 |
) |
| 1005 |
targetfile_from_data.verify_length_and_hashes(data) |
| 1006 |
|
| 1007 |
def test_metafile_from_data(self) -> None: |
| 1008 |
data = b"Inline test content" |
| 1009 |
|
| 1010 |
# Test with a valid hash algorithm |
| 1011 |
metafile = MetaFile.from_data(1, data, ["sha256"]) |
| 1012 |
metafile.verify_length_and_hashes(data) |
| 1013 |
|
| 1014 |
# Test with an invalid hash algorithm |
| 1015 |
with self.assertRaises(ValueError): |
| 1016 |
metafile = MetaFile.from_data(1, data, ["invalid_algorithm"]) |
| 1017 |
metafile.verify_length_and_hashes(data) |
| 1018 |
|
| 1019 |
self.assertEqual( |
| 1020 |
metafile, |
| 1021 |
MetaFile( |
| 1022 |
1, |
| 1023 |
19, |
| 1024 |
{ |
| 1025 |
"sha256": "fcee2e6d56ab08eab279016f7db7e4e1d172ccea78e15f4cf8bd939991a418fa" |
| 1026 |
}, |
| 1027 |
), |
| 1028 |
) |
| 1029 |
|
| 1030 |
# Test with custom blake hash algorithm |
| 1031 |
metafile = MetaFile.from_data(1, data, ["blake2b-256"]) |
| 1032 |
metafile.verify_length_and_hashes(data) |
| 1033 |
|
| 1034 |
def test_targetfile_get_prefixed_paths(self) -> None: |
| 1035 |
target = TargetFile(100, {"sha256": "abc", "md5": "def"}, "a/b/f.ext") |
| 1036 |
self.assertEqual( |
| 1037 |
target.get_prefixed_paths(), ["a/b/abc.f.ext", "a/b/def.f.ext"] |
| 1038 |
) |
| 1039 |
|
| 1040 |
target = TargetFile(100, {"sha256": "abc", "md5": "def"}, "") |
| 1041 |
self.assertEqual(target.get_prefixed_paths(), ["abc.", "def."]) |
| 1042 |
|
| 1043 |
target = TargetFile(100, {"sha256": "abc", "md5": "def"}, "a/b/") |
| 1044 |
self.assertEqual(target.get_prefixed_paths(), ["a/b/abc.", "a/b/def."]) |
| 1045 |
|
| 1046 |
target = TargetFile(100, {"sha256": "abc", "md5": "def"}, "f.ext") |
| 1047 |
self.assertEqual( |
| 1048 |
target.get_prefixed_paths(), ["abc.f.ext", "def.f.ext"] |
| 1049 |
) |
| 1050 |
|
| 1051 |
target = TargetFile(100, {"sha256": "abc", "md5": "def"}, "a/b/.ext") |
| 1052 |
self.assertEqual( |
| 1053 |
target.get_prefixed_paths(), ["a/b/abc..ext", "a/b/def..ext"] |
| 1054 |
) |
| 1055 |
|
| 1056 |
target = TargetFile(100, {"sha256": "abc"}, "/root/file.ext") |
| 1057 |
self.assertEqual(target.get_prefixed_paths(), ["/root/abc.file.ext"]) |
| 1058 |
|
| 1059 |
target = TargetFile(100, {"sha256": "abc"}, "/") |
| 1060 |
self.assertEqual(target.get_prefixed_paths(), ["/abc."]) |
| 1061 |
|
| 1062 |
def test_is_delegated_role(self) -> None: |
| 1063 |
# test path matches |
| 1064 |
# see more extensive tests in test_is_target_in_pathpattern() |
| 1065 |
for paths in [ |
| 1066 |
["a/path"], |
| 1067 |
["otherpath", "a/path"], |
| 1068 |
["*/?ath"], |
| 1069 |
]: |
| 1070 |
role = DelegatedRole("", [], 1, False, paths, None) |
| 1071 |
self.assertFalse(role.is_delegated_path("a/non-matching path")) |
| 1072 |
self.assertTrue(role.is_delegated_path("a/path")) |
| 1073 |
|
| 1074 |
# test path hash prefix matches: sha256 sum of "a/path" is 927b0ecf9... |
| 1075 |
for hash_prefixes in [ |
| 1076 |
["927b0ecf9"], |
| 1077 |
["other prefix", "927b0ecf9"], |
| 1078 |
["927b0"], |
| 1079 |
["92"], |
| 1080 |
]: |
| 1081 |
role = DelegatedRole("", [], 1, False, None, hash_prefixes) |
| 1082 |
self.assertFalse(role.is_delegated_path("a/non-matching path")) |
| 1083 |
self.assertTrue(role.is_delegated_path("a/path")) |
| 1084 |
|
| 1085 |
def test_is_delegated_role_in_succinct_roles(self) -> None: |
| 1086 |
succinct_roles = SuccinctRoles([], 1, 5, "bin") |
| 1087 |
false_role_name_examples = [ |
| 1088 |
"foo", |
| 1089 |
"bin-", |
| 1090 |
"bin-s", |
| 1091 |
"bin-0t", |
| 1092 |
"bin-20", |
| 1093 |
"bin-100", |
| 1094 |
] |
| 1095 |
for role_name in false_role_name_examples: |
| 1096 |
msg = f"Error for {role_name}" |
| 1097 |
self.assertFalse(succinct_roles.is_delegated_role(role_name), msg) |
| 1098 |
|
| 1099 |
# delegated role name suffixes are in hex format. |
| 1100 |
true_name_examples = ["bin-00", "bin-0f", "bin-1f"] |
| 1101 |
for role_name in true_name_examples: |
| 1102 |
msg = f"Error for {role_name}" |
| 1103 |
self.assertTrue(succinct_roles.is_delegated_role(role_name), msg) |
| 1104 |
|
| 1105 |
def test_get_roles_in_succinct_roles(self) -> None: |
| 1106 |
succinct_roles = SuccinctRoles([], 1, 16, "bin") |
| 1107 |
# bin names are in hex format and 4 hex digits are enough to represent |
| 1108 |
# all bins between 0 and 2^16 - 1 meaning suffix_len must be 4 |
| 1109 |
expected_suffix_length = 4 |
| 1110 |
self.assertEqual(succinct_roles.suffix_len, expected_suffix_length) |
| 1111 |
for bin_numer, role_name in enumerate(succinct_roles.get_roles()): |
| 1112 |
# This adds zero-padding if the bin_numer is represented by a hex |
| 1113 |
# number with a length less than expected_suffix_length. |
| 1114 |
expected_bin_suffix = f"{bin_numer:0{expected_suffix_length}x}" |
| 1115 |
self.assertEqual(role_name, f"bin-{expected_bin_suffix}") |
| 1116 |
|
| 1117 |
def test_delegations_get_delegated_role(self) -> None: |
| 1118 |
delegations = Delegations({}, {}) |
| 1119 |
targets = Targets(delegations=delegations) |
| 1120 |
|
| 1121 |
with self.assertRaises(ValueError): |
| 1122 |
targets.get_delegated_role("abc") |
| 1123 |
|
| 1124 |
# test "normal" delegated role (path or path_hash_prefix) |
| 1125 |
role = DelegatedRole("delegated", [], 1, False, []) |
| 1126 |
delegations.roles = {"delegated": role} |
| 1127 |
with self.assertRaises(ValueError): |
| 1128 |
targets.get_delegated_role("not-delegated") |
| 1129 |
self.assertEqual(targets.get_delegated_role("delegated"), role) |
| 1130 |
delegations.roles = None |
| 1131 |
|
| 1132 |
# test succinct delegation |
| 1133 |
bit_len = 3 |
| 1134 |
role2 = SuccinctRoles([], 1, bit_len, "prefix") |
| 1135 |
delegations.succinct_roles = role2 |
| 1136 |
for name in ["prefix-", "prefix--1", f"prefix-{2**bit_len:0x}"]: |
| 1137 |
with self.assertRaises(ValueError, msg=f"role name '{name}'"): |
| 1138 |
targets.get_delegated_role(name) |
| 1139 |
for i in range(2**bit_len): |
| 1140 |
self.assertEqual( |
| 1141 |
targets.get_delegated_role(f"prefix-{i:0x}"), role2 |
| 1142 |
) |
| 1143 |
|
| 1144 |
|
| 1145 |
class TestSimpleEnvelope(unittest.TestCase): |
| 1146 |
"""Tests for public API in 'tuf/api/dsse.py'.""" |
| 1147 |
|
| 1148 |
@classmethod |
| 1149 |
def setUpClass(cls) -> None: |
| 1150 |
repo_data_dir = Path(utils.TESTS_DIR) / "repository_data" |
| 1151 |
cls.metadata_dir = repo_data_dir / "repository" / "metadata" |
| 1152 |
cls.keystore_dir = repo_data_dir / "keystore" |
| 1153 |
cls.signers = {} |
| 1154 |
root_path = os.path.join(cls.metadata_dir, "root.json") |
| 1155 |
root: Root = Metadata.from_file(root_path).signed |
| 1156 |
|
| 1157 |
for role in [Snapshot, Targets, Timestamp]: |
| 1158 |
uri = f"file2:{os.path.join(cls.keystore_dir, role.type + '_key')}" |
| 1159 |
role_obj = root.get_delegated_role(role.type) |
| 1160 |
key = root.get_key(role_obj.keyids[0]) |
| 1161 |
cls.signers[role.type] = CryptoSigner.from_priv_key_uri(uri, key) |
| 1162 |
|
| 1163 |
def test_serialization(self) -> None: |
| 1164 |
"""Basic de/serialization test. |
| 1165 |
|
| 1166 |
1. Load test metadata for each role |
| 1167 |
2. Wrap metadata payloads in envelope serializing the payload |
| 1168 |
3. Serialize envelope |
| 1169 |
4. De-serialize envelope |
| 1170 |
5. De-serialize payload |
| 1171 |
|
| 1172 |
""" |
| 1173 |
for role in [Root, Timestamp, Snapshot, Targets]: |
| 1174 |
metadata_path = self.metadata_dir / f"{role.type}.json" |
| 1175 |
metadata = Metadata.from_file(str(metadata_path)) |
| 1176 |
self.assertIsInstance(metadata.signed, role) |
| 1177 |
|
| 1178 |
envelope = SimpleEnvelope.from_signed(metadata.signed) |
| 1179 |
envelope_bytes = envelope.to_bytes() |
| 1180 |
|
| 1181 |
envelope2 = SimpleEnvelope.from_bytes(envelope_bytes) |
| 1182 |
payload = envelope2.get_signed() |
| 1183 |
self.assertEqual(metadata.signed, payload) |
| 1184 |
|
| 1185 |
def test_fail_envelope_serialization(self) -> None: |
| 1186 |
envelope = SimpleEnvelope(b"foo", "bar", []) # type: ignore[arg-type] |
| 1187 |
with self.assertRaises(SerializationError): |
| 1188 |
envelope.to_bytes() |
| 1189 |
|
| 1190 |
def test_fail_envelope_deserialization(self) -> None: |
| 1191 |
with self.assertRaises(DeserializationError): |
| 1192 |
SimpleEnvelope.from_bytes(b"[") |
| 1193 |
|
| 1194 |
def test_fail_payload_serialization(self) -> None: |
| 1195 |
with self.assertRaises(SerializationError): |
| 1196 |
SimpleEnvelope.from_signed("foo") # type: ignore[type-var] |
| 1197 |
|
| 1198 |
def test_fail_payload_deserialization(self) -> None: |
| 1199 |
payloads = [b"[", b'{"_type": "foo"}'] |
| 1200 |
for payload in payloads: |
| 1201 |
envelope = SimpleEnvelope(payload, "bar", {}) |
| 1202 |
with self.assertRaises(DeserializationError): |
| 1203 |
envelope.get_signed() |
| 1204 |
|
| 1205 |
def test_verify_delegate(self) -> None: |
| 1206 |
"""Basic verification test. |
| 1207 |
|
| 1208 |
1. Load test metadata for each role |
| 1209 |
2. Wrap non-root payloads in envelope serializing the payload |
| 1210 |
3. Sign with correct delegated key |
| 1211 |
4. Verify delegate with root |
| 1212 |
|
| 1213 |
""" |
| 1214 |
root_path = self.metadata_dir / "root.json" |
| 1215 |
root = Metadata[Root].from_file(str(root_path)).signed |
| 1216 |
|
| 1217 |
for role in [Timestamp, Snapshot, Targets]: |
| 1218 |
metadata_path = self.metadata_dir / f"{role.type}.json" |
| 1219 |
metadata = Metadata.from_file(str(metadata_path)) |
| 1220 |
self.assertIsInstance(metadata.signed, role) |
| 1221 |
|
| 1222 |
signer = self.signers[role.type] |
| 1223 |
self.assertIn(signer.public_key.keyid, root.roles[role.type].keyids) |
| 1224 |
|
| 1225 |
envelope = SimpleEnvelope.from_signed(metadata.signed) |
| 1226 |
envelope.sign(signer) |
| 1227 |
self.assertTrue(len(envelope.signatures) == 1) |
| 1228 |
|
| 1229 |
root.verify_delegate(role.type, envelope.pae(), envelope.signatures) |
| 1230 |
|
| 1231 |
|
| 1232 |
# Run unit test. |
| 1233 |
if __name__ == "__main__": |
| 1234 |
utils.configure_test_logging(sys.argv) |
| 1235 |
unittest.main() |