| 1 |
#!/usr/bin/env python |
| 2 |
# coding=utf-8 |
| 3 |
|
| 4 |
# Copyright New York University and the in-toto contributors |
| 5 |
# SPDX-License-Identifier: Apache-2.0 |
| 6 |
|
| 7 |
""" |
| 8 |
<Program Name> |
| 9 |
test_runlib.py |
| 10 |
|
| 11 |
<Author> |
| 12 |
Lukas Puehringer <[email protected]> |
| 13 |
|
| 14 |
<Started> |
| 15 |
Dec 01, 2016 |
| 16 |
|
| 17 |
<Copyright> |
| 18 |
See LICENSE for licensing information. |
| 19 |
|
| 20 |
<Purpose> |
| 21 |
Test runlib functions. |
| 22 |
|
| 23 |
""" |
| 24 |
import os |
| 25 |
import shutil |
| 26 |
import stat |
| 27 |
import subprocess |
| 28 |
import sys |
| 29 |
import tempfile |
| 30 |
import unittest |
| 31 |
from pathlib import Path |
| 32 |
|
| 33 |
import securesystemslib.exceptions |
| 34 |
import securesystemslib.formats |
| 35 |
from securesystemslib.interface import ( |
| 36 |
generate_and_write_unencrypted_rsa_keypair, |
| 37 |
import_rsa_privatekey_from_file, |
| 38 |
import_rsa_publickey_from_file, |
| 39 |
) |
| 40 |
|
| 41 |
import in_toto.exceptions |
| 42 |
import in_toto.settings |
| 43 |
from in_toto.exceptions import SignatureVerificationError |
| 44 |
from in_toto.models.link import ( |
| 45 |
FILENAME_FORMAT, |
| 46 |
UNFINISHED_FILENAME_FORMAT, |
| 47 |
Link, |
| 48 |
) |
| 49 |
from in_toto.models.metadata import Envelope, Metablock |
| 50 |
from in_toto.resolver import FileResolver |
| 51 |
from in_toto.runlib import ( |
| 52 |
_subprocess_run_duplicate_streams, |
| 53 |
in_toto_match_products, |
| 54 |
in_toto_record_start, |
| 55 |
in_toto_record_stop, |
| 56 |
in_toto_run, |
| 57 |
record_artifacts_as_dict, |
| 58 |
) |
| 59 |
from tests.common import TmpDirMixin |
| 60 |
|
| 61 |
|
| 62 |
def _apply_exclude_patterns(names, patterns): |
| 63 |
"""Temporary bridge from old `runlib._apply_exclude_patterns` with new |
| 64 |
`FileResolver._exclude`. |
| 65 |
|
| 66 |
TODO: Replace tist once resolver interface evolves |
| 67 |
""" |
| 68 |
return [ |
| 69 |
n |
| 70 |
for n in names |
| 71 |
if not FileResolver(exclude_patterns=patterns)._exclude(n) |
| 72 |
] |
| 73 |
|
| 74 |
|
| 75 |
class Test_ApplyExcludePatterns(unittest.TestCase): |
| 76 |
"""Test _apply_exclude_patterns(names, exclude_patterns)""" |
| 77 |
|
| 78 |
def test_apply_exclude_explict(self): |
| 79 |
names = ["foo", "bar", "baz"] |
| 80 |
patterns = ["foo", "bar"] |
| 81 |
expected = ["baz"] |
| 82 |
result = _apply_exclude_patterns(names, patterns) |
| 83 |
self.assertListEqual(sorted(result), sorted(expected)) |
| 84 |
|
| 85 |
def test_apply_exclude_all(self): |
| 86 |
names = ["foo", "bar", "baz"] |
| 87 |
patterns = ["*"] |
| 88 |
expected = [] |
| 89 |
result = _apply_exclude_patterns(names, patterns) |
| 90 |
self.assertListEqual(sorted(result), sorted(expected)) |
| 91 |
|
| 92 |
def test_apply_exclude_multiple_star(self): |
| 93 |
names = ["foo", "bar", "baz"] |
| 94 |
patterns = ["*a*"] |
| 95 |
expected = ["foo"] |
| 96 |
result = _apply_exclude_patterns(names, patterns) |
| 97 |
self.assertListEqual(result, expected) |
| 98 |
|
| 99 |
def test_apply_exclude_question_mark(self): |
| 100 |
names = ["foo", "bazfoo", "barfoo"] |
| 101 |
patterns = ["ba?foo"] |
| 102 |
expected = ["foo"] |
| 103 |
result = _apply_exclude_patterns(names, patterns) |
| 104 |
self.assertListEqual(result, expected) |
| 105 |
|
| 106 |
def test_apply_exclude_seq(self): |
| 107 |
names = ["baxfoo", "bazfoo", "barfoo"] |
| 108 |
patterns = ["ba[xz]foo"] |
| 109 |
expected = ["barfoo"] |
| 110 |
result = _apply_exclude_patterns(names, patterns) |
| 111 |
self.assertListEqual(result, expected) |
| 112 |
|
| 113 |
def test_apply_exclude_neg_seq(self): |
| 114 |
names = ["baxfoo", "bazfoo", "barfoo"] |
| 115 |
patterns = ["ba[!r]foo"] |
| 116 |
expected = ["barfoo"] |
| 117 |
result = _apply_exclude_patterns(names, patterns) |
| 118 |
self.assertListEqual(result, expected) |
| 119 |
|
| 120 |
|
| 121 |
class TestRecordArtifactsAsDict(unittest.TestCase, TmpDirMixin): |
| 122 |
"""Test record_artifacts_as_dict(artifacts).""" |
| 123 |
|
| 124 |
@classmethod |
| 125 |
def setUpClass(self): |
| 126 |
"""Create and change into temp test directory with dummy artifacts. |
| 127 |
|-- bar |
| 128 |
|-- foo |
| 129 |
`-- subdir |
| 130 |
|-- foosub1 |
| 131 |
|-- foosub2 |
| 132 |
`-- subsubdir |
| 133 |
`-- foosubsub |
| 134 |
""" |
| 135 |
|
| 136 |
# Backup and clear user set exclude patterns and base path |
| 137 |
self.artifact_exclude_orig = in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS |
| 138 |
self.artifact_base_path_orig = in_toto.settings.ARTIFACT_BASE_PATH |
| 139 |
in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS = [] |
| 140 |
in_toto.settings.ARTIFACT_BASE_PATH = None |
| 141 |
|
| 142 |
self.set_up_test_dir() |
| 143 |
|
| 144 |
# Create files on 3 levels |
| 145 |
os.mkdir("subdir") |
| 146 |
os.mkdir("subdir/subsubdir") |
| 147 |
|
| 148 |
self.full_file_path_list = [ |
| 149 |
"foo", |
| 150 |
"bar", |
| 151 |
"#esc!", |
| 152 |
"subdir/foosub1", |
| 153 |
"subdir/foosub2", |
| 154 |
"subdir/subsubdir/foosubsub", |
| 155 |
] |
| 156 |
|
| 157 |
for path in self.full_file_path_list: |
| 158 |
with open(path, "w", encoding="utf8") as fp: |
| 159 |
fp.write(path) |
| 160 |
|
| 161 |
@classmethod |
| 162 |
def tearDownClass(self): |
| 163 |
"""Change back to working dir, remove temp directory, restore settings.""" |
| 164 |
self.tear_down_test_dir() |
| 165 |
in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS = self.artifact_exclude_orig |
| 166 |
in_toto.settings.ARTIFACT_BASE_PATH = self.artifact_base_path_orig |
| 167 |
|
| 168 |
def tearDown(self): |
| 169 |
"""Clear the ARTIFACT_EXLCUDES after every test.""" |
| 170 |
in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS = [] |
| 171 |
in_toto.settings.ARTIFACT_BASE_PATH = None |
| 172 |
|
| 173 |
def test_bad_base_path_setting(self): |
| 174 |
"""Raise exception with bogus base path settings.""" |
| 175 |
for base_path in ["path/does/not/exist", 12345, True]: |
| 176 |
in_toto.settings.ARTIFACT_BASE_PATH = base_path |
| 177 |
with self.assertRaises((OSError, ValueError)): |
| 178 |
record_artifacts_as_dict(["."]) |
| 179 |
in_toto.settings.ARTIFACT_BASE_PATH = None |
| 180 |
|
| 181 |
with self.assertRaises((OSError, ValueError)): |
| 182 |
record_artifacts_as_dict(["."], base_path=base_path) |
| 183 |
|
| 184 |
def test_base_path_is_child_dir(self): |
| 185 |
"""Test path of recorded artifacts and cd back with child as base.""" |
| 186 |
base_path = "subdir" |
| 187 |
expected_artifacts = sorted( |
| 188 |
["foosub1", "foosub2", "subsubdir/foosubsub"] |
| 189 |
) |
| 190 |
|
| 191 |
in_toto.settings.ARTIFACT_BASE_PATH = base_path |
| 192 |
artifacts_dict = record_artifacts_as_dict(["."]) |
| 193 |
self.assertListEqual( |
| 194 |
sorted(list(artifacts_dict.keys())), expected_artifacts |
| 195 |
) |
| 196 |
in_toto.settings.ARTIFACT_BASE_PATH = None |
| 197 |
|
| 198 |
artifacts_dict = record_artifacts_as_dict(["."], base_path=base_path) |
| 199 |
self.assertListEqual( |
| 200 |
sorted(list(artifacts_dict.keys())), expected_artifacts |
| 201 |
) |
| 202 |
|
| 203 |
def test_base_path_is_parent_dir(self): |
| 204 |
"""Test path of recorded artifacts and cd back with parent as base.""" |
| 205 |
base_path = ".." |
| 206 |
expected_artifacts = sorted( |
| 207 |
["foosub1", "foosub2", "subsubdir/foosubsub"] |
| 208 |
) |
| 209 |
os.chdir("subdir/subsubdir") |
| 210 |
|
| 211 |
in_toto.settings.ARTIFACT_BASE_PATH = base_path |
| 212 |
artifacts_dict = record_artifacts_as_dict(["."]) |
| 213 |
self.assertListEqual( |
| 214 |
sorted(list(artifacts_dict.keys())), expected_artifacts |
| 215 |
) |
| 216 |
in_toto.settings.ARTIFACT_BASE_PATH = None |
| 217 |
|
| 218 |
artifacts_dict = record_artifacts_as_dict(["."], base_path=base_path) |
| 219 |
self.assertListEqual( |
| 220 |
sorted(list(artifacts_dict.keys())), expected_artifacts |
| 221 |
) |
| 222 |
|
| 223 |
os.chdir(self.test_dir) |
| 224 |
|
| 225 |
def test_lstrip_paths_valid_prefix_directory(self): |
| 226 |
lstrip_paths = ["subdir/subsubdir/"] |
| 227 |
expected_artifacts = sorted( |
| 228 |
[ |
| 229 |
"#esc!", |
| 230 |
"bar", |
| 231 |
"foo", |
| 232 |
"subdir/foosub1", |
| 233 |
"subdir/foosub2", |
| 234 |
"foosubsub", |
| 235 |
] |
| 236 |
) |
| 237 |
artifacts_dict = record_artifacts_as_dict( |
| 238 |
["."], lstrip_paths=lstrip_paths |
| 239 |
) |
| 240 |
self.assertListEqual( |
| 241 |
sorted(list(artifacts_dict.keys())), expected_artifacts |
| 242 |
) |
| 243 |
|
| 244 |
def test_lstrip_paths_substring_prefix_directory(self): |
| 245 |
lstrip_paths = ["subdir/subsubdir/", "subdir/"] |
| 246 |
with self.assertRaises(in_toto.exceptions.PrefixError): |
| 247 |
record_artifacts_as_dict(["."], lstrip_paths=lstrip_paths) |
| 248 |
|
| 249 |
def test_lstrip_paths_non_unique_key(self): |
| 250 |
os.mkdir("subdir_new") |
| 251 |
path = "subdir_new/foosub1" |
| 252 |
shutil.copy("subdir/foosub1", path) |
| 253 |
lstrip_paths = ["subdir/", "subdir_new/"] |
| 254 |
with self.assertRaises(in_toto.exceptions.PrefixError): |
| 255 |
record_artifacts_as_dict(["."], lstrip_paths=lstrip_paths) |
| 256 |
os.remove(path) |
| 257 |
os.rmdir("subdir_new") |
| 258 |
|
| 259 |
def test_lstrip_paths_invalid_prefix_directory(self): |
| 260 |
lstrip_paths = ["not/a/directory/"] |
| 261 |
expected_artifacts = sorted( |
| 262 |
[ |
| 263 |
"#esc!", |
| 264 |
"bar", |
| 265 |
"foo", |
| 266 |
"subdir/foosub1", |
| 267 |
"subdir/foosub2", |
| 268 |
"subdir/subsubdir/foosubsub", |
| 269 |
] |
| 270 |
) |
| 271 |
artifacts_dict = record_artifacts_as_dict( |
| 272 |
["."], lstrip_paths=lstrip_paths |
| 273 |
) |
| 274 |
self.assertListEqual( |
| 275 |
sorted(list(artifacts_dict.keys())), expected_artifacts |
| 276 |
) |
| 277 |
|
| 278 |
def test_lstrip_paths_valid_prefix_file(self): |
| 279 |
lstrip_paths = ["subdir/subsubdir/"] |
| 280 |
expected_artifacts = sorted(["foosubsub"]) |
| 281 |
artifacts_dict = record_artifacts_as_dict( |
| 282 |
["./subdir/subsubdir/foosubsub"], lstrip_paths=lstrip_paths |
| 283 |
) |
| 284 |
self.assertListEqual( |
| 285 |
sorted(list(artifacts_dict.keys())), expected_artifacts |
| 286 |
) |
| 287 |
|
| 288 |
def test_lstrip_paths_non_unique_key_file(self): |
| 289 |
os.mkdir("subdir/subsubdir_new") |
| 290 |
path = "subdir/subsubdir_new/foosubsub" |
| 291 |
shutil.copy("subdir/subsubdir/foosubsub", path) |
| 292 |
lstrip_paths = ["subdir/subsubdir/", "subdir/subsubdir_new/"] |
| 293 |
with self.assertRaises(in_toto.exceptions.PrefixError): |
| 294 |
record_artifacts_as_dict( |
| 295 |
[ |
| 296 |
"subdir/subsubdir/foosubsub", |
| 297 |
"subdir/subsubdir_new/foosubsub", |
| 298 |
], |
| 299 |
lstrip_paths=lstrip_paths, |
| 300 |
) |
| 301 |
os.remove(path) |
| 302 |
os.rmdir("subdir/subsubdir_new") |
| 303 |
|
| 304 |
def test_lstrip_paths_valid_unicode_prefix_file(self): |
| 305 |
# Try to create a file with unicode character |
| 306 |
try: |
| 307 |
os.mkdir("ಠ") |
| 308 |
path = "ಠ/foo" |
| 309 |
shutil.copy("foo", path) |
| 310 |
|
| 311 |
# Attempt to left strip the path now that the file has been created |
| 312 |
lstrip_paths = ["ಠ/"] |
| 313 |
expected_artifacts = sorted(["foo"]) |
| 314 |
artifacts_dict = record_artifacts_as_dict( |
| 315 |
["./ಠ/"], lstrip_paths=lstrip_paths |
| 316 |
) |
| 317 |
self.assertListEqual( |
| 318 |
sorted(list(artifacts_dict.keys())), expected_artifacts |
| 319 |
) |
| 320 |
os.remove(path) |
| 321 |
os.rmdir("ಠ") |
| 322 |
except OSError: |
| 323 |
# OS doesn't support unicode explicit files |
| 324 |
pass |
| 325 |
|
| 326 |
def test_empty_artifacts_list_record_nothing(self): |
| 327 |
"""Empty list passed. Return empty dict.""" |
| 328 |
self.assertDictEqual(record_artifacts_as_dict([]), {}) |
| 329 |
|
| 330 |
def test_not_existing_artifacts_in_list_record_nothing(self): |
| 331 |
"""List with not existing artifact passed. Return empty dict.""" |
| 332 |
self.assertDictEqual(record_artifacts_as_dict(["baz"]), {}) |
| 333 |
|
| 334 |
def test_record_dot_check_files_hash_dict_schema(self): |
| 335 |
"""Traverse dir and subdirs. Record three files.""" |
| 336 |
artifacts_dict = record_artifacts_as_dict(["."]) |
| 337 |
|
| 338 |
for val in list(artifacts_dict.values()): |
| 339 |
securesystemslib.formats.HASHDICT_SCHEMA.check_match(val) |
| 340 |
|
| 341 |
self.assertListEqual( |
| 342 |
sorted(list(artifacts_dict.keys())), |
| 343 |
sorted(self.full_file_path_list), |
| 344 |
) |
| 345 |
|
| 346 |
@staticmethod |
| 347 |
def _raise_win_dev_mode_error(): |
| 348 |
"""If the platform is Windows, raises an error that asks the user if |
| 349 |
developer mode is activated.""" |
| 350 |
if os.name == "nt": |
| 351 |
raise IOError( |
| 352 |
"Developer mode is required to work with symlinks on " |
| 353 |
"Windows. Is it enabled?" |
| 354 |
) |
| 355 |
|
| 356 |
@unittest.skipIf( |
| 357 |
"symlink" not in os.__dict__, |
| 358 |
"symlink is not supported in this platform", |
| 359 |
) |
| 360 |
def test_record_symlinked_files(self): |
| 361 |
"""Symlinked files are always recorded.""" |
| 362 |
# Symlinked **files** are always recorded ... |
| 363 |
link_pairs = [ |
| 364 |
("foo", "foo_link"), |
| 365 |
("subdir/foosub1", "subdir/foosub2_link"), |
| 366 |
("subdir/subsubdir/foosubsub", "subdir/subsubdir/foosubsub_link"), |
| 367 |
] |
| 368 |
|
| 369 |
# Create links |
| 370 |
for pair in link_pairs: |
| 371 |
# We only use the basename of the file (source) as it is on the same |
| 372 |
# level as the link (target) |
| 373 |
try: |
| 374 |
os.symlink(os.path.basename(pair[0]), pair[1]) |
| 375 |
except IOError: |
| 376 |
TestRecordArtifactsAsDict._raise_win_dev_mode_error() |
| 377 |
raise |
| 378 |
|
| 379 |
# Record files and linked files |
| 380 |
# follow_symlink_dirs does not make a difference as it only concerns linked dirs |
| 381 |
for follow_symlink_dirs in [True, False]: |
| 382 |
artifacts_dict = record_artifacts_as_dict( |
| 383 |
["."], follow_symlink_dirs=follow_symlink_dirs |
| 384 |
) |
| 385 |
|
| 386 |
# Test that everything was recorded ... |
| 387 |
self.assertListEqual( |
| 388 |
sorted(list(artifacts_dict.keys())), |
| 389 |
sorted( |
| 390 |
self.full_file_path_list + [pair[1] for pair in link_pairs] |
| 391 |
), |
| 392 |
) |
| 393 |
|
| 394 |
# ... and the hashes of each link/file pair match |
| 395 |
for pair in link_pairs: |
| 396 |
self.assertDictEqual( |
| 397 |
artifacts_dict[pair[0]], artifacts_dict[pair[1]] |
| 398 |
) |
| 399 |
|
| 400 |
for pair in link_pairs: |
| 401 |
os.unlink(pair[1]) |
| 402 |
|
| 403 |
@unittest.skipIf( |
| 404 |
"symlink" not in os.__dict__, |
| 405 |
"symlink is not supported in this platform", |
| 406 |
) |
| 407 |
def test_record_without_dead_symlinks(self): |
| 408 |
"""Dead symlinks are never recorded.""" |
| 409 |
|
| 410 |
# Dead symlinks are never recorded ... |
| 411 |
links = [ |
| 412 |
"foo_link", |
| 413 |
"subdir/foosub2_link", |
| 414 |
"subdir/subsubdir/foosubsub_link", |
| 415 |
] |
| 416 |
|
| 417 |
# Create dead links |
| 418 |
for link in links: |
| 419 |
try: |
| 420 |
os.symlink("does/not/exist", link) |
| 421 |
except IOError: |
| 422 |
TestRecordArtifactsAsDict._raise_win_dev_mode_error() |
| 423 |
raise |
| 424 |
|
| 425 |
# Record files without dead links |
| 426 |
# follow_symlink_dirs does not make a difference as it only concerns linked dirs |
| 427 |
for follow_symlink_dirs in [True, False]: |
| 428 |
artifacts_dict = record_artifacts_as_dict( |
| 429 |
["."], follow_symlink_dirs=follow_symlink_dirs |
| 430 |
) |
| 431 |
|
| 432 |
# Test only the files were recorded ... |
| 433 |
self.assertListEqual( |
| 434 |
sorted(list(artifacts_dict.keys())), |
| 435 |
sorted(self.full_file_path_list), |
| 436 |
) |
| 437 |
|
| 438 |
for link in links: |
| 439 |
os.unlink(link) |
| 440 |
|
| 441 |
@unittest.skipIf( |
| 442 |
"symlink" not in os.__dict__, |
| 443 |
"symlink is not supported in this platform", |
| 444 |
) |
| 445 |
def test_record_follow_symlinked_directories(self): |
| 446 |
"""Record files in symlinked dirs if follow_symlink_dirs is True.""" |
| 447 |
|
| 448 |
try: |
| 449 |
# Link to subdir |
| 450 |
os.symlink("subdir", "subdir_link") |
| 451 |
except IOError: |
| 452 |
TestRecordArtifactsAsDict._raise_win_dev_mode_error() |
| 453 |
raise |
| 454 |
|
| 455 |
link_pairs = [ |
| 456 |
("subdir/foosub1", "subdir_link/foosub1"), |
| 457 |
("subdir/foosub2", "subdir_link/foosub2"), |
| 458 |
("subdir/subsubdir/foosubsub", "subdir_link/subsubdir/foosubsub"), |
| 459 |
] |
| 460 |
|
| 461 |
# Record with follow_symlink_dirs TRUE |
| 462 |
artifacts_dict = record_artifacts_as_dict( |
| 463 |
["."], follow_symlink_dirs=True |
| 464 |
) |
| 465 |
# Test that all files were recorded including files in linked subdir ... |
| 466 |
self.assertListEqual( |
| 467 |
sorted(list(artifacts_dict.keys())), |
| 468 |
sorted(self.full_file_path_list + [pair[1] for pair in link_pairs]), |
| 469 |
) |
| 470 |
|
| 471 |
# ... and the hashes of each link/file pair match |
| 472 |
for pair in link_pairs: |
| 473 |
self.assertDictEqual( |
| 474 |
artifacts_dict[pair[0]], artifacts_dict[pair[1]] |
| 475 |
) |
| 476 |
|
| 477 |
# Record with follow_symlink_dirs FALSE (default) |
| 478 |
artifacts_dict = record_artifacts_as_dict(["."]) |
| 479 |
self.assertListEqual( |
| 480 |
sorted(list(artifacts_dict.keys())), |
| 481 |
sorted(self.full_file_path_list), |
| 482 |
) |
| 483 |
|
| 484 |
os.unlink("subdir_link") |
| 485 |
|
| 486 |
def test_record_files_and_subdirs(self): |
| 487 |
"""Explicitly record files and subdirs.""" |
| 488 |
artifacts_dict = record_artifacts_as_dict(["foo", "subdir"]) |
| 489 |
|
| 490 |
for val in list(artifacts_dict.values()): |
| 491 |
securesystemslib.formats.HASHDICT_SCHEMA.check_match(val) |
| 492 |
|
| 493 |
self.assertListEqual( |
| 494 |
sorted(list(artifacts_dict.keys())), |
| 495 |
sorted( |
| 496 |
[ |
| 497 |
"foo", |
| 498 |
"subdir/foosub1", |
| 499 |
"subdir/foosub2", |
| 500 |
"subdir/subsubdir/foosubsub", |
| 501 |
] |
| 502 |
), |
| 503 |
) |
| 504 |
|
| 505 |
def test_exclude_patterns(self): |
| 506 |
"""Test excluding artifacts using passed pattern or setting.""" |
| 507 |
excludes_and_results = [ |
| 508 |
# Exclude files containing 'foo' everywhere |
| 509 |
(["*foo*"], ["bar", "#esc!"]), |
| 510 |
# Exclude subdirectory and all its contents |
| 511 |
(["subdir"], ["bar", "foo", "#esc!"]), |
| 512 |
# Exclude files 'subdir/foosub1' and 'subdir/foosub2' |
| 513 |
( |
| 514 |
["*foosub?"], |
| 515 |
["bar", "foo", "#esc!", "subdir/subsubdir/foosubsub"], |
| 516 |
), |
| 517 |
# Exclude subsubdirectory and its contents |
| 518 |
( |
| 519 |
["*subsubdir"], |
| 520 |
["foo", "bar", "#esc!", "subdir/foosub1", "subdir/foosub2"], |
| 521 |
), |
| 522 |
(["/**"], []), |
| 523 |
(["*sub*"], ["foo", "bar", "#esc!"]), |
| 524 |
( |
| 525 |
["**/subdir/subsubdir"], |
| 526 |
["foo", "bar", "#esc!", "subdir/foosub1", "subdir/foosub2"], |
| 527 |
), |
| 528 |
( |
| 529 |
["subdir/foo*"], |
| 530 |
["bar", "foo", "#esc!", "subdir/subsubdir/foosubsub"], |
| 531 |
), |
| 532 |
(["**/subdir/"], ["bar", "foo", "#esc!"]), |
| 533 |
(["foo*"], ["bar", "#esc!"]), |
| 534 |
( |
| 535 |
["**/*1"], |
| 536 |
[ |
| 537 |
"bar", |
| 538 |
"foo", |
| 539 |
"#esc!", |
| 540 |
"subdir/foosub2", |
| 541 |
"subdir/subsubdir/foosubsub", |
| 542 |
], |
| 543 |
), |
| 544 |
( |
| 545 |
["**/*sub?"], |
| 546 |
["bar", "foo", "#esc!", "subdir/subsubdir/foosubsub"], |
| 547 |
), |
| 548 |
( |
| 549 |
["**/foo*[1-9]"], |
| 550 |
["bar", "foo", "#esc!", "subdir/subsubdir/foosubsub"], |
| 551 |
), |
| 552 |
(["**/[a-z][a-z][a-z][a-z][a-z][a-z]/"], ["bar", "foo", "#esc!"]), |
| 553 |
(["/subdir"], ["foo", "bar", "#esc!"]), |
| 554 |
(["subdir/"], ["foo", "bar", "#esc!"]), |
| 555 |
( |
| 556 |
["/subdir/subsubdir"], |
| 557 |
["foo", "bar", "#esc!", "subdir/foosub1", "subdir/foosub2"], |
| 558 |
), |
| 559 |
( |
| 560 |
["subdir/subsubdir/"], |
| 561 |
["foo", "bar", "#esc!", "subdir/foosub1", "subdir/foosub2"], |
| 562 |
), |
| 563 |
( |
| 564 |
["\#esc*"], # pylint: disable=W1401 |
| 565 |
[ |
| 566 |
"foo", |
| 567 |
"bar", |
| 568 |
"subdir/foosub1", |
| 569 |
"subdir/foosub2", |
| 570 |
"subdir/subsubdir/foosubsub", |
| 571 |
], |
| 572 |
), |
| 573 |
( |
| 574 |
["*esc\!"], # pylint: disable=W1401 |
| 575 |
[ |
| 576 |
"foo", |
| 577 |
"bar", |
| 578 |
"subdir/foosub1", |
| 579 |
"subdir/foosub2", |
| 580 |
"subdir/subsubdir/foosubsub", |
| 581 |
], |
| 582 |
), |
| 583 |
( |
| 584 |
["/"], |
| 585 |
[ |
| 586 |
"foo", |
| 587 |
"bar", |
| 588 |
"#esc!", |
| 589 |
"subdir/foosub1", |
| 590 |
"subdir/foosub2", |
| 591 |
"subdir/subsubdir/foosubsub", |
| 592 |
], |
| 593 |
), |
| 594 |
] |
| 595 |
|
| 596 |
for exclude_patterns, expected_results in excludes_and_results: |
| 597 |
# Exclude via setting |
| 598 |
in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS = exclude_patterns |
| 599 |
artifacts1 = record_artifacts_as_dict(["."]) |
| 600 |
|
| 601 |
# Exclude via argument |
| 602 |
in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS = None |
| 603 |
artifacts2 = record_artifacts_as_dict( |
| 604 |
["."], exclude_patterns=exclude_patterns |
| 605 |
) |
| 606 |
|
| 607 |
self.assertTrue( |
| 608 |
sorted(list(artifacts1)) |
| 609 |
== sorted(list(artifacts2)) |
| 610 |
== sorted(expected_results) |
| 611 |
) |
| 612 |
|
| 613 |
def test_bad_artifact_exclude_patterns_setting(self): |
| 614 |
"""Raise exception with bogus artifact exclude patterns settings.""" |
| 615 |
for setting in ["not a list of settings", 12345, True]: |
| 616 |
in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS = setting |
| 617 |
with self.assertRaises(ValueError): |
| 618 |
record_artifacts_as_dict(["."]) |
| 619 |
|
| 620 |
|
| 621 |
class TestLinkCmdExecTimeoutSetting(unittest.TestCase): |
| 622 |
"""Tests LINK_CMD_EXEC_TIMEOUT setting in settings.py file.""" |
| 623 |
|
| 624 |
def test_timeout_setting(self): |
| 625 |
# Save the old timeout and make sure it's saved properly |
| 626 |
timeout_old = in_toto.settings.LINK_CMD_EXEC_TIMEOUT |
| 627 |
|
| 628 |
# Modify timeout |
| 629 |
in_toto.settings.LINK_CMD_EXEC_TIMEOUT = 0.1 |
| 630 |
|
| 631 |
# check if exception is raised |
| 632 |
with self.assertRaises(subprocess.TimeoutExpired): |
| 633 |
# Call execute_link to see if new timeout is respected |
| 634 |
in_toto.runlib.execute_link( |
| 635 |
[sys.executable, "-c", "while True: pass"], True |
| 636 |
) |
| 637 |
|
| 638 |
# check if exception is raised |
| 639 |
with self.assertRaises(subprocess.TimeoutExpired): |
| 640 |
# Call execute_link to see if new timeout is respected |
| 641 |
in_toto.runlib.execute_link( |
| 642 |
[sys.executable, "-c", "while True: pass"], False |
| 643 |
) |
| 644 |
|
| 645 |
# Restore original timeout |
| 646 |
in_toto.settings.LINK_CMD_EXEC_TIMEOUT = timeout_old |
| 647 |
|
| 648 |
|
| 649 |
class TestSubprocess(unittest.TestCase): |
| 650 |
def test_run_duplicate_streams(self): |
| 651 |
"""Test output indeed duplicated.""" |
| 652 |
# Command that prints 'foo' to stdout and 'bar' to stderr. |
| 653 |
cmd = [ |
| 654 |
sys.executable, |
| 655 |
"-c", |
| 656 |
"import sys; sys.stdout.write('foo'); sys.stderr.write('bar');", |
| 657 |
] |
| 658 |
|
| 659 |
# Create and open fake targets for standard streams |
| 660 |
stdout_fd, stdout_fn = tempfile.mkstemp() |
| 661 |
stderr_fd, stderr_fn = tempfile.mkstemp() |
| 662 |
with open( # pylint: disable=unspecified-encoding |
| 663 |
stdout_fn, "r" |
| 664 |
) as fake_stdout_reader, os.fdopen( |
| 665 |
stdout_fd, "w" |
| 666 |
) as fake_stdout_writer, open( # pylint: disable=unspecified-encoding |
| 667 |
stderr_fn, "r" |
| 668 |
) as fake_stderr_reader, os.fdopen( |
| 669 |
stderr_fd, "w" |
| 670 |
) as fake_stderr_writer: |
| 671 |
# Backup original standard streams and redirect to fake targets |
| 672 |
real_stdout = sys.stdout |
| 673 |
real_stderr = sys.stderr |
| 674 |
sys.stdout = fake_stdout_writer |
| 675 |
sys.stderr = fake_stderr_writer |
| 676 |
|
| 677 |
# Run command |
| 678 |
ret_code, ret_out, ret_err = _subprocess_run_duplicate_streams( |
| 679 |
cmd, 10 |
| 680 |
) |
| 681 |
|
| 682 |
# Rewind fake standard streams |
| 683 |
fake_stdout_reader.seek(0) |
| 684 |
fake_stderr_reader.seek(0) |
| 685 |
|
| 686 |
# Assert that what was printed and what was returned is correct |
| 687 |
self.assertTrue(ret_out == fake_stdout_reader.read() == "foo") |
| 688 |
self.assertTrue(ret_err == fake_stderr_reader.read() == "bar") |
| 689 |
# Also assert the return value |
| 690 |
self.assertEqual(ret_code, 0) |
| 691 |
|
| 692 |
# Restore original streams |
| 693 |
sys.stdout = real_stdout |
| 694 |
sys.stderr = real_stderr |
| 695 |
|
| 696 |
# Remove fake standard streams |
| 697 |
os.remove(stdout_fn) |
| 698 |
os.remove(stderr_fn) |
| 699 |
|
| 700 |
def test_run_duplicate_streams_return_value(self): |
| 701 |
"""Test return code.""" |
| 702 |
cmd = [sys.executable, "-c", "import sys; sys.exit(100)"] |
| 703 |
ret_code, _, _ = _subprocess_run_duplicate_streams(cmd, 10) |
| 704 |
self.assertEqual(ret_code, 100) |
| 705 |
|
| 706 |
def test_run_duplicate_streams_timeout(self): |
| 707 |
"""Test timeout.""" |
| 708 |
cmd = [sys.executable, "-c", "while True: pass"] |
| 709 |
with self.assertRaises(subprocess.TimeoutExpired): |
| 710 |
_subprocess_run_duplicate_streams(cmd, timeout=-1) |
| 711 |
|
| 712 |
|
| 713 |
class TestInTotoRun(unittest.TestCase, TmpDirMixin): |
| 714 |
""" " |
| 715 |
Tests runlib.in_toto_run() with different arguments |
| 716 |
|
| 717 |
Calls in_toto_run library funtion inside of a temporary directory that |
| 718 |
contains a test artifact and a test keypair |
| 719 |
|
| 720 |
If the function does not fail it will dump a test step link metadata file |
| 721 |
to the temp dir which is removed after every test. |
| 722 |
|
| 723 |
""" |
| 724 |
|
| 725 |
@classmethod |
| 726 |
def setUpClass(self): |
| 727 |
"""Create and change into temporary directory, generate key pair and dummy |
| 728 |
material, read key pair.""" |
| 729 |
self.set_up_test_dir() |
| 730 |
|
| 731 |
self.step_name = "test_step" |
| 732 |
self.key_path = "test_key" |
| 733 |
generate_and_write_unencrypted_rsa_keypair(self.key_path) |
| 734 |
self.key = import_rsa_privatekey_from_file(self.key_path) |
| 735 |
self.key_pub = import_rsa_publickey_from_file(self.key_path + ".pub") |
| 736 |
|
| 737 |
self.test_artifact = "test_artifact" |
| 738 |
Path(self.test_artifact).touch() |
| 739 |
|
| 740 |
@classmethod |
| 741 |
def tearDownClass(self): |
| 742 |
self.tear_down_test_dir() |
| 743 |
|
| 744 |
def tearDown(self): |
| 745 |
"""Remove link file if it was created.""" |
| 746 |
try: |
| 747 |
os.remove( |
| 748 |
FILENAME_FORMAT.format( |
| 749 |
step_name=self.step_name, keyid=self.key["keyid"] |
| 750 |
) |
| 751 |
) |
| 752 |
except OSError: |
| 753 |
pass |
| 754 |
|
| 755 |
def test_in_toto_run_verify_signature(self): |
| 756 |
"""Successfully run, verify signed metadata.""" |
| 757 |
link = in_toto_run( |
| •758 |
self.step_name, None, None, ["python3", "--version"], True, self.key |
| 759 |
) |
| 760 |
link.verify_signature(self.key) |
| 761 |
|
| 762 |
def test_in_toto_run_no_signature(self): |
| 763 |
"""Successfully run, verify empty signature field.""" |
| •764 |
link = in_toto_run(self.step_name, None, None, ["python3", "--version"]) |
| 765 |
self.assertFalse(len(link.signatures)) |
| 766 |
|
| 767 |
def test_in_toto_run_with_byproduct(self): |
| 768 |
"""Successfully run, verify recorded byproduct.""" |
| 769 |
link = in_toto_run( |
| 770 |
self.step_name, |
| 771 |
None, |
| 772 |
None, |
| •773 |
["python3", "--version"], |
| 774 |
record_streams=True, |
| 775 |
) |
| 776 |
|
| 777 |
# this or clause may seem weird, but given that python 2 prints its version |
| 778 |
# to stderr while python3 prints it to stdout we check on both (or add a |
| 779 |
# more verbose if clause) |
| 780 |
stderr_contents = link.signed.byproducts.get("stderr") |
| 781 |
stdout_contents = link.signed.byproducts.get("stdout") |
| 782 |
self.assertTrue( |
| 783 |
"Python" in stderr_contents or "Python" in stdout_contents, |
| 784 |
msg="\nSTDERR:\n{}\nSTDOUT:\n{}".format( |
| 785 |
stderr_contents, stdout_contents |
| 786 |
), |
| 787 |
) |
| 788 |
|
| 789 |
def test_in_toto_run_without_byproduct(self): |
| 790 |
"""Successfully run, verify byproduct is not recorded.""" |
| 791 |
link = in_toto_run( |
| 792 |
self.step_name, |
| 793 |
None, |
| 794 |
None, |
| •795 |
["python3", "--version"], |
| 796 |
record_streams=False, |
| 797 |
) |
| 798 |
self.assertFalse(len(link.signed.byproducts.get("stdout"))) |
| 799 |
|
| 800 |
def test_in_toto_run_compare_dumped_with_returned_link(self): |
| 801 |
"""Successfully run, compare dumped link is equal to returned link.""" |
| 802 |
link = in_toto_run( |
| 803 |
self.step_name, |
| 804 |
[self.test_artifact], |
| 805 |
[self.test_artifact], |
| •806 |
["python3", "--version"], |
| 807 |
True, |
| 808 |
self.key, |
| 809 |
) |
| 810 |
link_dump = Metablock.load( |
| 811 |
FILENAME_FORMAT.format( |
| 812 |
step_name=self.step_name, keyid=self.key["keyid"] |
| 813 |
) |
| 814 |
) |
| 815 |
self.assertEqual(repr(link), repr(link_dump)) |
| 816 |
|
| 817 |
def test_in_toto_run_with_metadata_directory(self): |
| 818 |
"""Successfully run with metadata directory, |
| 819 |
compare dumped link is equal to returned link""" |
| 820 |
tmp_dir = os.path.realpath(tempfile.mkdtemp(dir=os.getcwd())) |
| 821 |
link = in_toto_run( |
| 822 |
self.step_name, |
| 823 |
[self.test_artifact], |
| 824 |
[self.test_artifact], |
| •825 |
["python3", "--version"], |
| 826 |
True, |
| 827 |
self.key, |
| 828 |
metadata_directory=tmp_dir, |
| 829 |
) |
| 830 |
file_path = os.path.join( |
| 831 |
tmp_dir, |
| 832 |
FILENAME_FORMAT.format( |
| 833 |
step_name=self.step_name, keyid=self.key["keyid"] |
| 834 |
), |
| 835 |
) |
| 836 |
link_dump = Metablock.load(file_path) |
| 837 |
self.assertEqual(repr(link), repr(link_dump)) |
| 838 |
|
| 839 |
def test_in_toto_run_compare_with_and_without_metadata_directory(self): |
| 840 |
"""Successfully run with and without metadata directory, |
| 841 |
compare the signed is equal""" |
| 842 |
tmp_dir = os.path.realpath(tempfile.mkdtemp(dir=os.getcwd())) |
| 843 |
in_toto_run( |
| 844 |
self.step_name, |
| 845 |
[self.test_artifact], |
| 846 |
[self.test_artifact], |
| •847 |
["python3", "--version"], |
| 848 |
True, |
| 849 |
self.key, |
| 850 |
metadata_directory=tmp_dir, |
| 851 |
) |
| 852 |
file_path = os.path.join( |
| 853 |
tmp_dir, |
| 854 |
FILENAME_FORMAT.format( |
| 855 |
step_name=self.step_name, keyid=self.key["keyid"] |
| 856 |
), |
| 857 |
) |
| 858 |
link_dump_with_md = Metablock.load(file_path) |
| 859 |
|
| 860 |
in_toto_run( |
| 861 |
self.step_name, |
| 862 |
[self.test_artifact], |
| 863 |
[self.test_artifact], |
| •864 |
["python3", "--version"], |
| 865 |
True, |
| 866 |
self.key, |
| 867 |
) |
| 868 |
link_dump_without_md = Metablock.load( |
| 869 |
FILENAME_FORMAT.format( |
| 870 |
step_name=self.step_name, keyid=self.key["keyid"] |
| 871 |
) |
| 872 |
) |
| 873 |
self.assertEqual( |
| 874 |
repr(link_dump_with_md.signed), repr(link_dump_without_md.signed) |
| 875 |
) |
| 876 |
|
| 877 |
def test_in_toto_run_verify_recorded_artifacts(self): |
| 878 |
"""Successfully run, verify properly recorded artifacts.""" |
| 879 |
link = in_toto_run( |
| 880 |
self.step_name, |
| 881 |
[self.test_artifact], |
| 882 |
[self.test_artifact], |
| •883 |
["python3", "--version"], |
| 884 |
) |
| 885 |
self.assertEqual( |
| 886 |
list(link.signed.materials.keys()), |
| 887 |
list(link.signed.products.keys()), |
| 888 |
[self.test_artifact], |
| 889 |
) |
| 890 |
|
| 891 |
def test_in_toto_run_verify_workdir(self): |
| 892 |
"""Successfully run, verify cwd.""" |
| 893 |
link = in_toto_run( |
| 894 |
self.step_name, |
| 895 |
[], |
| 896 |
[], |
| •897 |
["python3", "--version"], |
| 898 |
record_environment=True, |
| 899 |
) |
| 900 |
self.assertEqual( |
| 901 |
link.signed.environment["workdir"], os.getcwd().replace("\\", "/") |
| 902 |
) |
| 903 |
|
| 904 |
def test_normalize_line_endings(self): |
| 905 |
"""Test cross-platform line ending normalization.""" |
| 906 |
paths = [] |
| 907 |
try: |
| 908 |
# Create three artifacts with same content but different line endings |
| 909 |
for line_ending in [b"\n", b"\r", b"\r\n"]: |
| 910 |
fd, path = tempfile.mkstemp() |
| 911 |
paths.append(path) |
| 912 |
os.write(fd, b"hello" + line_ending + b"toto") |
| 913 |
os.close(fd) |
| 914 |
|
| 915 |
# Call in_toto_run and record artifacts as materials and products |
| 916 |
# with line ending normalization on |
| 917 |
link = in_toto_run( |
| 918 |
self.step_name, |
| 919 |
paths, |
| 920 |
paths, |
| •921 |
["python3", "--version"], |
| 922 |
normalize_line_endings=True, |
| 923 |
).signed |
| 924 |
|
| 925 |
# Check that all three hashes in materials and products are equal |
| 926 |
for artifact_dict in [link.materials, link.products]: |
| 927 |
hash_dicts = list(artifact_dict.values()) |
| 928 |
self.assertTrue(hash_dicts[1:] == hash_dicts[:-1]) |
| 929 |
|
| 930 |
# Clean up |
| 931 |
finally: |
| 932 |
for path in paths: |
| 933 |
os.remove(path) |
| 934 |
|
| 935 |
def test_in_toto_bad_signing_key_format(self): |
| 936 |
"""Fail run, passed key is not properly formatted.""" |
| 937 |
with self.assertRaises(securesystemslib.exceptions.FormatError): |
| 938 |
in_toto_run( |
| 939 |
self.step_name, |
| 940 |
None, |
| 941 |
None, |
| •942 |
["python3", "--version"], |
| 943 |
True, |
| 944 |
"this-is-not-a-key", |
| 945 |
) |
| 946 |
|
| 947 |
def test_in_toto_wrong_key(self): |
| 948 |
"""Fail run, passed key is a public key.""" |
| 949 |
with self.assertRaises(securesystemslib.exceptions.FormatError): |
| 950 |
in_toto_run( |
| 951 |
self.step_name, |
| 952 |
None, |
| 953 |
None, |
| •954 |
["python3", "--version"], |
| 955 |
True, |
| 956 |
self.key_pub, |
| 957 |
) |
| 958 |
|
| 959 |
def test_nonexistent_directory(self): |
| 960 |
"""Fail run, passed metadata_directory not exist.""" |
| 961 |
with self.assertRaises(FileNotFoundError): |
| 962 |
in_toto_run( |
| 963 |
self.step_name, |
| 964 |
None, |
| 965 |
None, |
| •966 |
["python3", "--version"], |
| 967 |
True, |
| 968 |
self.key, |
| 969 |
metadata_directory="nonexistentDir", |
| 970 |
) |
| 971 |
|
| 972 |
def test_not_a_directory(self): |
| 973 |
"""Fail run, passed metadata_directory is not a directory.""" |
| 974 |
fd, path = tempfile.mkstemp() |
| 975 |
os.write(fd, b"hello in-toto") |
| 976 |
os.close(fd) |
| 977 |
# Windows will raise FileNotFoundError instead of NotADirectoryError |
| 978 |
with self.assertRaises((NotADirectoryError, FileNotFoundError)): |
| 979 |
in_toto_run( |
| 980 |
self.step_name, |
| 981 |
None, |
| 982 |
None, |
| •983 |
["python3", "--version"], |
| 984 |
True, |
| 985 |
self.key, |
| 986 |
metadata_directory=path, |
| 987 |
) |
| 988 |
os.remove(path) |
| 989 |
|
| 990 |
@unittest.skipIf(os.name == "nt", "chmod doesn't work properly on Windows") |
| 991 |
def test_in_toto_read_only_metadata_directory(self): |
| 992 |
"""Fail run, passed metadata directory is read only""" |
| 993 |
tmp_dir = os.path.realpath(tempfile.mkdtemp()) |
| 994 |
# make the directory read only |
| 995 |
os.chmod(tmp_dir, stat.S_IREAD) |
| 996 |
with self.assertRaises(PermissionError): |
| 997 |
in_toto_run( |
| 998 |
self.step_name, |
| 999 |
None, |
| 1000 |
None, |
| •1001 |
["python3", "--version"], |
| 1002 |
True, |
| 1003 |
self.key, |
| 1004 |
metadata_directory=tmp_dir, |
| 1005 |
) |
| 1006 |
os.rmdir(tmp_dir) |
| 1007 |
|
| 1008 |
def test_in_toto_for_dsse(self): |
| 1009 |
"""Test metadata generation using dsse.""" |
| 1010 |
|
| 1011 |
link_metadata = in_toto_run( |
| 1012 |
self.step_name, |
| 1013 |
None, |
| 1014 |
None, |
| •1015 |
["python3", "--version"], |
| 1016 |
True, |
| 1017 |
self.key, |
| 1018 |
use_dsse=True, |
| 1019 |
) |
| 1020 |
self.assertIsInstance(link_metadata, Envelope) |
| 1021 |
link_metadata.verify_signature(self.key) |
| 1022 |
|
| 1023 |
|
| 1024 |
class TestInTotoRecordStart(unittest.TestCase, TmpDirMixin): |
| 1025 |
""" "Test in_toto_record_start(step_name, key, material_list).""" |
| 1026 |
|
| 1027 |
@classmethod |
| 1028 |
def setUpClass(self): |
| 1029 |
"""Create and change into temporary directory, generate key pair and dummy |
| 1030 |
material, read key pair.""" |
| 1031 |
self.set_up_test_dir() |
| 1032 |
|
| 1033 |
self.key_path = "test_key" |
| 1034 |
generate_and_write_unencrypted_rsa_keypair(self.key_path) |
| 1035 |
self.key = import_rsa_privatekey_from_file(self.key_path) |
| 1036 |
|
| 1037 |
self.step_name = "test_step" |
| 1038 |
self.link_name_unfinished = UNFINISHED_FILENAME_FORMAT.format( |
| 1039 |
step_name=self.step_name, keyid=self.key["keyid"] |
| 1040 |
) |
| 1041 |
|
| 1042 |
self.test_material = "test_material" |
| 1043 |
Path(self.test_material).touch() |
| 1044 |
|
| 1045 |
@classmethod |
| 1046 |
def tearDownClass(self): |
| 1047 |
self.tear_down_test_dir() |
| 1048 |
|
| 1049 |
def test_UNFINISHED_FILENAME_FORMAT(self): |
| 1050 |
"""Test if the unfinished filname format.""" |
| 1051 |
self.assertTrue( |
| 1052 |
self.link_name_unfinished |
| 1053 |
== ".{}.{:.8}.link-unfinished".format( |
| 1054 |
self.step_name, self.key["keyid"] |
| 1055 |
) |
| 1056 |
) |
| 1057 |
|
| 1058 |
def test_create_unfinished_metadata_with_expected_material(self): |
| 1059 |
"""Test record start creates metadata with expected material.""" |
| 1060 |
in_toto_record_start(self.step_name, [self.test_material], self.key) |
| 1061 |
link = Metablock.load(self.link_name_unfinished) |
| 1062 |
self.assertEqual( |
| 1063 |
list(link.signed.materials.keys()), [self.test_material] |
| 1064 |
) |
| 1065 |
os.remove(self.link_name_unfinished) |
| 1066 |
|
| 1067 |
def test_create_unfinished_metadata_verify_signature(self): |
| 1068 |
"""Test record start creates metadata with expected signature.""" |
| 1069 |
in_toto_record_start(self.step_name, [self.test_material], self.key) |
| 1070 |
link = Metablock.load(self.link_name_unfinished) |
| 1071 |
link.verify_signature(self.key) |
| 1072 |
os.remove(self.link_name_unfinished) |
| 1073 |
|
| 1074 |
def test_no_key_arguments(self): |
| 1075 |
"""Test record start without passing one required key argument.""" |
| 1076 |
with self.assertRaises(ValueError): |
| 1077 |
in_toto_record_start( |
| 1078 |
self.step_name, |
| 1079 |
[], |
| 1080 |
signing_key=None, |
| 1081 |
gpg_keyid=None, |
| 1082 |
gpg_use_default=False, |
| 1083 |
) |
| 1084 |
|
| 1085 |
def test_create_unfinished_metadata_using_dsse(self): |
| 1086 |
"""Test record start creates metadata using dsse.""" |
| 1087 |
in_toto_record_start( |
| 1088 |
self.step_name, [self.test_material], self.key, use_dsse=True |
| 1089 |
) |
| 1090 |
link_metadata = Envelope.load(self.link_name_unfinished) |
| 1091 |
link_metadata.verify_signature(self.key) |
| 1092 |
os.remove(self.link_name_unfinished) |
| 1093 |
|
| 1094 |
|
| 1095 |
class TestInTotoRecordStop(unittest.TestCase, TmpDirMixin): |
| 1096 |
""" "Test in_toto_record_stop(step_name, key, product_list).""" |
| 1097 |
|
| 1098 |
@classmethod |
| 1099 |
def setUpClass(self): |
| 1100 |
"""Create and change into temporary directory, generate two key pairs |
| 1101 |
and dummy product.""" |
| 1102 |
self.set_up_test_dir() |
| 1103 |
|
| 1104 |
self.key_path = "test-key" |
| 1105 |
self.key_path2 = "test-key2" |
| 1106 |
generate_and_write_unencrypted_rsa_keypair(self.key_path) |
| 1107 |
generate_and_write_unencrypted_rsa_keypair(self.key_path2) |
| 1108 |
self.key = import_rsa_privatekey_from_file(self.key_path) |
| 1109 |
self.key2 = import_rsa_privatekey_from_file(self.key_path2) |
| 1110 |
|
| 1111 |
self.step_name = "test-step" |
| 1112 |
self.link_name = "{}.{:.8}.link".format( |
| 1113 |
self.step_name, self.key["keyid"] |
| 1114 |
) |
| 1115 |
self.link_name_unfinished = UNFINISHED_FILENAME_FORMAT.format( |
| 1116 |
step_name=self.step_name, keyid=self.key["keyid"] |
| 1117 |
) |
| 1118 |
|
| 1119 |
self.test_product = "test_product" |
| 1120 |
Path(self.test_product).touch() |
| 1121 |
|
| 1122 |
@classmethod |
| 1123 |
def tearDownClass(self): |
| 1124 |
self.tear_down_test_dir() |
| 1125 |
|
| 1126 |
def test_create_metadata_with_expected_product(self): |
| 1127 |
"""Test record stop records expected product.""" |
| 1128 |
in_toto_record_start(self.step_name, [], self.key) |
| 1129 |
in_toto_record_stop(self.step_name, [self.test_product], self.key) |
| 1130 |
link = Metablock.load(self.link_name) |
| 1131 |
self.assertEqual(list(link.signed.products.keys()), [self.test_product]) |
| 1132 |
os.remove(self.link_name) |
| 1133 |
|
| 1134 |
def test_compare_metadata_with_and_without_metadata_directory(self): |
| 1135 |
"""Test record stop with and without metadata directory, |
| 1136 |
compare the expected product""" |
| 1137 |
tmp_dir = os.path.realpath(tempfile.mkdtemp(dir=os.getcwd())) |
| 1138 |
in_toto_record_start(self.step_name, [], self.key) |
| 1139 |
in_toto_record_stop( |
| 1140 |
self.step_name, |
| 1141 |
[self.test_product], |
| 1142 |
self.key, |
| 1143 |
metadata_directory=tmp_dir, |
| 1144 |
) |
| 1145 |
link_path = os.path.join(tmp_dir, self.link_name) |
| 1146 |
link_with_md = Metablock.load(link_path) |
| 1147 |
|
| 1148 |
in_toto_record_start(self.step_name, [], self.key) |
| 1149 |
in_toto_record_stop(self.step_name, [self.test_product], self.key) |
| 1150 |
link_without_md = Metablock.load(self.link_name) |
| 1151 |
self.assertEqual(link_with_md.signed, link_without_md.signed) |
| 1152 |
os.remove(link_path) |
| 1153 |
os.remove(self.link_name) |
| 1154 |
|
| 1155 |
def test_create_metadata_with_expected_cwd(self): |
| 1156 |
"""Test record start/stop run, verify cwd.""" |
| 1157 |
in_toto_record_start( |
| 1158 |
self.step_name, [], self.key, record_environment=True |
| 1159 |
) |
| 1160 |
in_toto_record_stop(self.step_name, [self.test_product], self.key) |
| 1161 |
link = Metablock.load(self.link_name) |
| 1162 |
self.assertEqual( |
| 1163 |
link.signed.environment["workdir"], os.getcwd().replace("\\", "/") |
| 1164 |
) |
| 1165 |
os.remove(self.link_name) |
| 1166 |
|
| 1167 |
def test_create_metadata_verify_signature(self): |
| 1168 |
"""Test record start creates metadata with expected signature.""" |
| 1169 |
in_toto_record_start(self.step_name, [], self.key) |
| 1170 |
in_toto_record_stop(self.step_name, [], self.key) |
| 1171 |
link = Metablock.load(self.link_name) |
| 1172 |
link.verify_signature(self.key) |
| 1173 |
os.remove(self.link_name) |
| 1174 |
|
| 1175 |
def test_replace_unfinished_metadata(self): |
| 1176 |
"""Test record stop removes unfinished file and creates link file.""" |
| 1177 |
in_toto_record_start(self.step_name, [], self.key) |
| 1178 |
in_toto_record_stop(self.step_name, [], self.key) |
| 1179 |
with self.assertRaises(IOError): |
| 1180 |
# pylint: disable-next=consider-using-with |
| 1181 |
open(self.link_name_unfinished, "r", encoding="utf8") |
| 1182 |
self.assertTrue(os.path.isfile(self.link_name)) |
| 1183 |
os.remove(self.link_name) |
| 1184 |
|
| 1185 |
def test_missing_unfinished_file(self): |
| 1186 |
"""Test record stop exits on missing unfinished file, no link recorded.""" |
| 1187 |
with self.assertRaises(IOError): |
| 1188 |
in_toto_record_stop(self.step_name, [], self.key) |
| 1189 |
with self.assertRaises(IOError): |
| 1190 |
# pylint: disable-next=consider-using-with |
| 1191 |
open(self.link_name, "r", encoding="utf8") |
| 1192 |
|
| 1193 |
def test_wrong_signature_in_unfinished_metadata(self): |
| 1194 |
"""Test record stop exits on wrong signature, no link recorded.""" |
| 1195 |
in_toto_record_start(self.step_name, [], self.key) |
| 1196 |
link_name = UNFINISHED_FILENAME_FORMAT.format( |
| 1197 |
step_name=self.step_name, keyid=self.key["keyid"] |
| 1198 |
) |
| 1199 |
changed_link_name = UNFINISHED_FILENAME_FORMAT.format( |
| 1200 |
step_name=self.step_name, keyid=self.key2["keyid"] |
| 1201 |
) |
| 1202 |
os.rename(link_name, changed_link_name) |
| 1203 |
with self.assertRaises(SignatureVerificationError): |
| 1204 |
in_toto_record_stop(self.step_name, [], self.key2) |
| 1205 |
with self.assertRaises(IOError): |
| 1206 |
# pylint: disable-next=consider-using-with |
| 1207 |
open(self.link_name, "r", encoding="utf8") |
| 1208 |
os.rename(changed_link_name, link_name) |
| 1209 |
os.remove(self.link_name_unfinished) |
| 1210 |
|
| 1211 |
def test_no_key_arguments(self): |
| 1212 |
"""Test record stop without passing one required key argument.""" |
| 1213 |
with self.assertRaises(ValueError): |
| 1214 |
in_toto_record_stop( |
| 1215 |
self.step_name, |
| 1216 |
[], |
| 1217 |
signing_key=None, |
| 1218 |
gpg_keyid=None, |
| 1219 |
gpg_use_default=False, |
| 1220 |
) |
| 1221 |
|
| 1222 |
def test_normalize_line_endings(self): |
| 1223 |
"""Test cross-platform line ending normalization.""" |
| 1224 |
paths = [] |
| 1225 |
try: |
| 1226 |
# Create three artifacts with same content but different line endings |
| 1227 |
for line_ending in [b"\n", b"\r", b"\r\n"]: |
| 1228 |
fd, path = tempfile.mkstemp() |
| 1229 |
paths.append(path) |
| 1230 |
os.write(fd, b"hello" + line_ending + b"toto") |
| 1231 |
os.close(fd) |
| 1232 |
|
| 1233 |
# Call in_toto_record start and stop and record artifacts as |
| 1234 |
# materials and products with line ending normalization on |
| 1235 |
in_toto_record_start( |
| 1236 |
self.step_name, paths, self.key, normalize_line_endings=True |
| 1237 |
) |
| 1238 |
in_toto_record_stop( |
| 1239 |
self.step_name, paths, self.key, normalize_line_endings=True |
| 1240 |
) |
| 1241 |
link = Metablock.load(self.link_name).signed |
| 1242 |
|
| 1243 |
# Check that all three hashes in materials and products are equal |
| 1244 |
for artifact_dict in [link.materials, link.products]: |
| 1245 |
hash_dicts = list(artifact_dict.values()) |
| 1246 |
self.assertTrue(hash_dicts[1:] == hash_dicts[:-1]) |
| 1247 |
|
| 1248 |
# Clean up |
| 1249 |
finally: |
| 1250 |
for path in paths: |
| 1251 |
os.remove(path) |
| 1252 |
|
| 1253 |
def test_nonexistent_directory(self): |
| 1254 |
"""Test record stop with nonexistent metadata directory""" |
| 1255 |
with self.assertRaises(FileNotFoundError): |
| 1256 |
in_toto_record_start(self.step_name, [], self.key) |
| 1257 |
in_toto_record_stop( |
| 1258 |
self.step_name, |
| 1259 |
[], |
| 1260 |
self.key, |
| 1261 |
metadata_directory="nonexistentDir", |
| 1262 |
) |
| 1263 |
|
| 1264 |
def test_not_a_directory(self): |
| 1265 |
"""Test record stop, passed metadata directory is not a dir""" |
| 1266 |
fd, path = tempfile.mkstemp() |
| 1267 |
os.write(fd, b"hello in-toto") |
| 1268 |
os.close(fd) |
| 1269 |
# Windows will raise FileNotFoundError instead of NotADirectoryError |
| 1270 |
with self.assertRaises((NotADirectoryError, FileNotFoundError)): |
| 1271 |
in_toto_record_start(self.step_name, [], self.key) |
| 1272 |
in_toto_record_stop( |
| 1273 |
self.step_name, [], self.key, metadata_directory=path |
| 1274 |
) |
| 1275 |
os.remove(path) |
| 1276 |
|
| 1277 |
@unittest.skipIf(os.name == "nt", "chmod doesn't work properly on Windows") |
| 1278 |
def test_read_only_metadata_directory(self): |
| 1279 |
"""Test record stop with read only metadata directory""" |
| 1280 |
tmp_dir = os.path.realpath(tempfile.mkdtemp()) |
| 1281 |
# make the directory read only |
| 1282 |
os.chmod(tmp_dir, stat.S_IREAD) |
| 1283 |
with self.assertRaises(PermissionError): |
| 1284 |
in_toto_record_start(self.step_name, [], self.key) |
| 1285 |
in_toto_record_stop( |
| 1286 |
self.step_name, [], self.key, metadata_directory=tmp_dir |
| 1287 |
) |
| 1288 |
os.rmdir(tmp_dir) |
| 1289 |
|
| 1290 |
def test_created_metadata_using_dsse(self): |
| 1291 |
"""Test record stop records created metadata with dsse.""" |
| 1292 |
in_toto_record_start(self.step_name, [], self.key, use_dsse=True) |
| 1293 |
in_toto_record_stop(self.step_name, [self.test_product], self.key) |
| 1294 |
|
| 1295 |
link_metadata = Envelope.load(self.link_name) |
| 1296 |
link_metadata.verify_signature(self.key) |
| 1297 |
|
| 1298 |
link = link_metadata.get_payload() |
| 1299 |
self.assertEqual(list(link.products.keys()), [self.test_product]) |
| 1300 |
os.remove(self.link_name) |
| 1301 |
|
| 1302 |
def test_create_metadata_with_command_byproducts_environment(self): |
| 1303 |
"""Test record stop records expected product.""" |
| 1304 |
command = ["cp", "src", "dest"] |
| 1305 |
byproducts = { |
| 1306 |
"stdout": "success", |
| 1307 |
"stderr": "errors", |
| 1308 |
"return-value": 0, |
| 1309 |
} |
| 1310 |
environment = { |
| 1311 |
"variables": "ENV_NAME=ENV_VALUE", |
| 1312 |
"filesystem": "<filesystem info>", |
| 1313 |
"workdir": "./", |
| 1314 |
} |
| 1315 |
|
| 1316 |
in_toto_record_start( |
| 1317 |
self.step_name, [], self.key, record_environment=True |
| 1318 |
) |
| 1319 |
in_toto_record_stop( |
| 1320 |
self.step_name, |
| 1321 |
[self.test_product], |
| 1322 |
self.key, |
| 1323 |
command=command, |
| 1324 |
byproducts=byproducts, |
| 1325 |
environment=environment, |
| 1326 |
) |
| 1327 |
link = Metablock.load(self.link_name) |
| 1328 |
self.assertEqual(link.signed.command, command) |
| 1329 |
self.assertDictEqual(link.signed.byproducts, byproducts) |
| 1330 |
self.assertDictEqual(link.signed.environment, environment) |
| 1331 |
os.remove(self.link_name) |
| 1332 |
|
| 1333 |
|
| 1334 |
class TestInTotoMatchProducts(TmpDirMixin, unittest.TestCase): |
| 1335 |
"""Basic tests for in_toto_match_products. |
| 1336 |
|
| 1337 |
More comprehensive tests for `record_artifacts_as_dict` args exist above. |
| 1338 |
""" |
| 1339 |
|
| 1340 |
@classmethod |
| 1341 |
def setUpClass(cls): |
| 1342 |
# Create link with some products and some local artifacts in tmp dir: |
| 1343 |
# - 'foo' is only in products |
| 1344 |
# - 'quux' is not in products |
| 1345 |
# - 'baz' is in both, with different hashes |
| 1346 |
# - 'bar' is in both, with matching hashes |
| 1347 |
cls.set_up_test_dir() # teardown is called implicitly |
| 1348 |
|
| 1349 |
cls.link = Link( |
| 1350 |
products={ |
| 1351 |
"foo": { |
| 1352 |
"sha256": "8a51c03f1ff77c2b8e76da512070c23c5e69813d5c61732b3025199e5f0c14d5" |
| 1353 |
}, |
| 1354 |
"bar": { |
| 1355 |
"sha256": "bb97edb3507a35b119539120526d00da595f14575da261cd856389ecd89d3186" |
| 1356 |
}, |
| 1357 |
"baz": { |
| 1358 |
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" |
| 1359 |
}, |
| 1360 |
} |
| 1361 |
) |
| 1362 |
Path("bar").touch() |
| 1363 |
Path("baz").touch() |
| 1364 |
Path("quux").touch() |
| 1365 |
|
| 1366 |
def test_check(self): |
| 1367 |
"""Match local artifacts with link products for different kwargs.""" |
| 1368 |
# Test data: |
| 1369 |
# [ |
| 1370 |
# ( |
| 1371 |
# <passed kwargs>, |
| 1372 |
# <expected return values (only in products, not in products, differ)> |
| 1373 |
# ), |
| 1374 |
# ... |
| 1375 |
# ] |
| 1376 |
test_data = [ |
| 1377 |
({}, ({"foo"}, {"quux"}, {"bar"})), |
| 1378 |
( |
| 1379 |
{"exclude_patterns": ["ba*"]}, |
| 1380 |
({"foo", "bar", "baz"}, {"quux"}, set()), |
| 1381 |
), |
| 1382 |
({"paths": ["baz"]}, ({"foo", "bar"}, set(), set())), |
| 1383 |
( |
| 1384 |
{ |
| 1385 |
"paths": [str(Path("baz").absolute())], |
| 1386 |
"lstrip_paths": [ |
| 1387 |
# NOTE: normalize lstrip path to match normalized artifact path |
| 1388 |
# (see in-toto/in-toto#565) |
| 1389 |
f"{Path('baz').absolute().parent}/".replace("\\", "/") |
| 1390 |
], |
| 1391 |
}, |
| 1392 |
({"foo", "bar"}, set(), set()), |
| 1393 |
), |
| 1394 |
] |
| 1395 |
|
| 1396 |
for kwargs, expected_return_value in test_data: |
| 1397 |
self.assertTupleEqual( |
| 1398 |
in_toto_match_products(self.link, **kwargs), |
| 1399 |
expected_return_value, |
| 1400 |
f"unexpected result for **kwargs: {kwargs})", |
| 1401 |
) |
| 1402 |
|
| 1403 |
|
| 1404 |
if __name__ == "__main__": |
| 1405 |
unittest.main() |