Repository navigation
Expand file tree
/
Copy path_record.py
More file actions
68 lines (54 loc) · 2.26 KB
/
Copy path_record.py
File metadata and controls
68 lines (54 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Turn RECORD rows into the hashed files an SBOM lists, with CycloneDX algorithm names and hex digests."""
from __future__ import annotations
__lazy_modules__ = [
"base64",
"binascii",
"installer.records",
"itertools",
"python_sbom",
f"{__spec__.parent}._inputs", # ty: ignore[missing-union-attribute] # imported modules have a spec
]
import base64
import binascii
from itertools import starmap
from types import MappingProxyType
from typing import TYPE_CHECKING, Final
from installer.records import RecordEntry
from python_sbom import SbomError
from ._inputs import RecordRow
if TYPE_CHECKING:
from collections.abc import Iterable
# the algorithms a wheel RECORD may name, as CycloneDX spells them
_ALGORITHMS: Final[MappingProxyType[str, str]] = MappingProxyType({
"md5": "MD5",
"sha1": "SHA-1",
"sha256": "SHA-256",
"sha384": "SHA-384",
"sha512": "SHA-512",
})
def record_rows(rows: Iterable[tuple[str, str, str]], where: str) -> list[RecordRow]:
# the rows with a digest, as the SBOM lists them: RECORD's own row has none, nor has a file an installer left
# unhashed; installer's InvalidRecordEntry passes to the caller, which knows what a malformed row means there
found: Final[list[RecordRow]] = []
for entry in starmap(RecordEntry.from_elements, rows):
if entry.hash_ is None:
continue
algorithm, digest = _decode_digest(str(entry.hash_), f"{where}: RECORD row for {entry.path}")
found.append(RecordRow(path=entry.path, algorithm=algorithm, digest=digest, size=str(entry.size)))
return found
def _decode_digest(digest: str, where: str) -> tuple[str, str]:
# installer checks RECORD digests as urlsafe base64 under any hashlib name, while CycloneDX takes hex under its own
# names for a few algorithms
name, _, encoded = digest.partition("=")
if (algorithm := _ALGORITHMS.get(name)) is None:
msg = f"{where}: unknown hash algorithm {name!r}"
raise SbomError(msg)
try:
raw = base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))
except binascii.Error as error:
msg = f"{where}: digest {encoded!r} is not urlsafe base64"
raise SbomError(msg) from error
return algorithm, raw.hex()
__all__ = [
"record_rows",
]