teef 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
teef/__init__.py ADDED
@@ -0,0 +1,84 @@
1
+ """Build, verify and read TEEF (TPRM Evidence Exchange Format) packages."""
2
+
3
+ __version__ = "0.1.1"
4
+
5
+ SCHEMA_VERSION = "0.1.0"
6
+ """The TEEF schema version this package reads and writes."""
7
+
8
+ from .catalog import RULES, rule_title # noqa: E402
9
+ from .context import Context, Limits # noqa: E402
10
+ from .errors import PackageValidationError # noqa: E402
11
+ from .findings import Finding, Severity # noqa: E402
12
+ from .jose import SignatureInfo # noqa: E402
13
+ from .models import ( # noqa: E402
14
+ AssuranceReport,
15
+ Certification,
16
+ CoveragePeriod,
17
+ Evidence,
18
+ EvidenceContent,
19
+ EvidenceKind,
20
+ EvidenceRef,
21
+ ExternalContent,
22
+ FileContent,
23
+ InlineContent,
24
+ LastAudit,
25
+ Manifest,
26
+ Mapping,
27
+ Organization,
28
+ Questionnaire,
29
+ RelatedEvidenceRef,
30
+ ReportException,
31
+ Response,
32
+ ResponseStatus,
33
+ StatementOfApplicability,
34
+ Subject,
35
+ SubjectScope,
36
+ SubserviceOrganization,
37
+ )
38
+ from .package import Package # noqa: E402
39
+ from .reader import ReadResult, read # noqa: E402
40
+ from .report import render_html # noqa: E402
41
+ from .rules import check_package # noqa: E402
42
+ from .sources import EncryptionInfo # noqa: E402
43
+
44
+ __all__ = [
45
+ "RULES",
46
+ "SCHEMA_VERSION",
47
+ "Context",
48
+ "EncryptionInfo",
49
+ "Limits",
50
+ "ReadResult",
51
+ "SignatureInfo",
52
+ "read",
53
+ "render_html",
54
+ "rule_title",
55
+ "AssuranceReport",
56
+ "Certification",
57
+ "CoveragePeriod",
58
+ "Evidence",
59
+ "EvidenceContent",
60
+ "EvidenceKind",
61
+ "EvidenceRef",
62
+ "ExternalContent",
63
+ "FileContent",
64
+ "Finding",
65
+ "InlineContent",
66
+ "LastAudit",
67
+ "Manifest",
68
+ "Mapping",
69
+ "Organization",
70
+ "Package",
71
+ "PackageValidationError",
72
+ "Questionnaire",
73
+ "RelatedEvidenceRef",
74
+ "ReportException",
75
+ "Response",
76
+ "ResponseStatus",
77
+ "Severity",
78
+ "StatementOfApplicability",
79
+ "Subject",
80
+ "SubjectScope",
81
+ "SubserviceOrganization",
82
+ "__version__",
83
+ "check_package",
84
+ ]
teef/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
teef/catalog.py ADDED
@@ -0,0 +1,128 @@
1
+ """Rule IDs and titles from the TEEF 0.1.0 rule index.
2
+
3
+ Copied from the rule index in the specification's ``docs/architecture.md``. A test
4
+ compares this table with the specification, so it cannot drift.
5
+ """
6
+
7
+ RULES: dict[str, str] = {
8
+ "TEEF-PKG-01": "Reject a package that breaks a content requirement",
9
+ "TEEF-PKG-02": "Manifest is UTF-8 JSON without a byte order mark",
10
+ "TEEF-PKG-03": "Manifest has no duplicate member names",
11
+ "TEEF-PKG-04": "A single-file package is a ZIP with the manifest at its root",
12
+ "TEEF-PKG-05": "ZIP entries use the manifest's relative paths",
13
+ "TEEF-PKG-06": "`generatedAt` is RFC 3339 UTC with `Z`",
14
+ "TEEF-PKG-07": "A package contains questionnaires, evidence, or both",
15
+ "TEEF-SIG-01": "Assemble the ZIP before encryption",
16
+ "TEEF-SIG-02": "Encrypt as a compact JWE for one recipient",
17
+ "TEEF-SIG-03": "JWE protected header values",
18
+ "TEEF-SIG-04": "Decrypt and authenticate before opening the ZIP",
19
+ "TEEF-SIG-05": "Validate the decrypted package",
20
+ "TEEF-SCHEMA-01": "Validate the manifest against the schema with format assertions",
21
+ "TEEF-SCHEMA-02": "Report an unsupported schema version",
22
+ "TEEF-ID-01": "Assign a new package ID per snapshot and never reuse it",
23
+ "TEEF-ID-02": "Treat a reused package ID as an integrity error",
24
+ "TEEF-REF-01": "`supersedes` names an earlier package of the same publisher and subject",
25
+ "TEEF-SCOPE-01": "Supply the service for service-specific exchanges",
26
+ "TEEF-ANS-01": "Use the buyer's questionnaire URI",
27
+ "TEEF-ANS-02": "Do not read an omitted question as a status",
28
+ "TEEF-SCOPE-02": "A subject scope has at least one field",
29
+ "TEEF-SCOPE-03": "List every country of operation, support, or processing",
30
+ "TEEF-SCOPE-04": "Check the subject scope against own knowledge",
31
+ "TEEF-SCOPE-05": "Do not treat the subject scope as verified",
32
+ "TEEF-SCOPE-06": "Surface a subject organisation the evidence does not cover",
33
+ "TEEF-SCOPE-07": "Compare organisations by identifier",
34
+ "TEEF-SCOPE-08": "Show both names when an identifier is missing",
35
+ "TEEF-SCOPE-09": "Surface subject countries the evidence does not list",
36
+ "TEEF-ANS-03": "`answered` carries an answer",
37
+ "TEEF-ANS-04": "`reference` carries evidence references",
38
+ "TEEF-ANS-05": "`reference` carries no answer",
39
+ "TEEF-ANS-06": "`unknown`, `notApplicable`, and `withheld` carry no answer or references",
40
+ "TEEF-ANS-07": "Preserve `false` and `0`",
41
+ "TEEF-ANS-08": "Match questionnaire URI, version, and question ID before applying",
42
+ "TEEF-ANS-09": "Interpret choice codes and units with the definition",
43
+ "TEEF-ANS-10": "Reproduce the question text as received",
44
+ "TEEF-MAP-01": "Do not assume an unqualified mapping is equivalent",
45
+ "TEEF-MAP-02": "Reuse mapped answers only with review or policy for equivalent mappings",
46
+ "TEEF-EV-01": "File digests are lowercase hex SHA-256 of the exact bytes",
47
+ "TEEF-URI-01": "External references use HTTPS",
48
+ "TEEF-URI-02": "External URIs carry no credentials",
49
+ "TEEF-EV-02": "Do not assume an undigested external target is unchanged",
50
+ "TEEF-EV-03": "Supply issuer and scope where known",
51
+ "TEEF-EV-04": "Do not infer omitted metadata",
52
+ "TEEF-EV-05": "Follow the metadata guidance per kind",
53
+ "TEEF-REF-02": "A bridge letter references a bridged report in the package",
54
+ "TEEF-EV-06": "A bridge letter names a bridged report outside the package",
55
+ "TEEF-EV-07": "An insurance certificate's scope states the cover type",
56
+ "TEEF-EV-08": "Prefer a specific kind over `other`",
57
+ "TEEF-EV-09": "An `other` item's title describes it",
58
+ "TEEF-REF-03": "`bridges` appears only on a bridge letter",
59
+ "TEEF-REF-04": "`bridges` references an assurance report",
60
+ "TEEF-REF-05": "No self-reference in related evidence",
61
+ "TEEF-DATE-01": "A bridge letter's coverage starts the day after the report's",
62
+ "TEEF-DATE-02": "Surface a bridge letter gap or overlap",
63
+ "TEEF-AR-01": "Only assurance reports carry assurance report details",
64
+ "TEEF-AR-02": "A type 1 report covers a single date",
65
+ "TEEF-AR-03": "A type 2 report covers more than one date",
66
+ "TEEF-AR-04": "Copy report details without reinterpretation",
67
+ "TEEF-AR-05": "Report organisations and countries stay within the system boundary",
68
+ "TEEF-AR-06": "Do not list countries of carved-out subservice organisations only",
69
+ "TEEF-AR-07": "Surface an opinion other than unmodified",
70
+ "TEEF-AR-08": "Surface reported exceptions",
71
+ "TEEF-AR-09": "Surface carved-out subservice organisations",
72
+ "TEEF-AR-10": "Surface complementary user entity controls",
73
+ "TEEF-AR-11": "Encrypt or omit confidential report details",
74
+ "TEEF-CERT-01": "A certificate carries certificate details",
75
+ "TEEF-CERT-02": "Only certificates carry certificate details",
76
+ "TEEF-CERT-03": "A certificate has no common `scope`",
77
+ "TEEF-CERT-04": "A Statement of Applicability has a version or date",
78
+ "TEEF-CERT-05": "Copy certificate details without reinterpretation",
79
+ "TEEF-CERT-06": "Supply the certificate number when one exists",
80
+ "TEEF-CERT-07": "Surface a certificate without a number",
81
+ "TEEF-CERT-08": "Certificate organisations and countries stay within the certified scope",
82
+ "TEEF-CERT-09": "Surface a certificate without an accreditation body",
83
+ "TEEF-CERT-10": "Surface a last audit more than 12 months old",
84
+ "TEEF-CERT-11": "Check the certificate register where policy allows",
85
+ "TEEF-ID-03": "Reject duplicate identifiers and file paths",
86
+ "TEEF-REF-06": "Reject unresolved evidence references",
87
+ "TEEF-REF-07": "Reject a package that supersedes itself",
88
+ "TEEF-REF-08": "Reject a superseded package with a different publisher or subject",
89
+ "TEEF-DATE-03": "Reject inverted validity or coverage ranges",
90
+ "TEEF-DATE-04": "Do not reject solely for expiry or missing scope",
91
+ "TEEF-DATE-05": "Surface evidence expired at generation or at intake",
92
+ "TEEF-EV-10": "Surface evidence without a stated scope",
93
+ "TEEF-ANS-11": "Check answer types against the definition",
94
+ "TEEF-ANS-12": "Surface an unknown questionnaire or version",
95
+ "TEEF-ANS-13": "Do not apply answers to an unknown questionnaire automatically",
96
+ "TEEF-ANS-14": "Surface question text that differs from the definition",
97
+ "TEEF-EV-11": "Reject missing files and digest mismatches",
98
+ "TEEF-ARC-01": "Reject undeclared files",
99
+ "TEEF-ARC-02": "Reject absolute paths and path traversal",
100
+ "TEEF-ARC-03": "Reject reserved device filenames",
101
+ "TEEF-ARC-04": "Reject symbolic and hard links",
102
+ "TEEF-ARC-05": "Reject duplicate entries",
103
+ "TEEF-ARC-06": "Reject case-insensitive collisions",
104
+ "TEEF-ARC-07": "Enforce archive size, entry count, and expanded size limits",
105
+ "TEEF-ARC-08": "Apply file inspection policy",
106
+ "TEEF-URI-03": "Treat package content as untrusted",
107
+ "TEEF-URI-04": "Do not dereference external references during validation",
108
+ "TEEF-URI-05": "Follow network policy for later retrieval",
109
+ "TEEF-URI-06": "Flag external URIs that appear to carry credentials",
110
+ "TEEF-DIST-01": "Disclose only permitted material",
111
+ "TEEF-DIST-02": "Use access-controlled references for restricted material",
112
+ "TEEF-DIST-03": "Apply distribution and retention policy",
113
+ "TEEF-DIST-04": "Retain the snapshot and verification result",
114
+ "TEEF-SIG-06": "Detached JWS over the exact manifest bytes",
115
+ "TEEF-SIG-07": "JWS header values",
116
+ "TEEF-SIG-08": "Resolve the signing key through trusted configuration",
117
+ "TEEF-SIG-09": "RFC 3161 token over the exact manifest bytes",
118
+ "TEEF-SIG-10": "Verify the timestamp token",
119
+ "TEEF-SIG-11": "Separate signing and encryption keys",
120
+ "TEEF-SIG-12": "Reject invalid proofs",
121
+ "TEEF-SIG-13": "Reject a package missing a required proof",
122
+ "TEEF-SIG-14": "Archive material for later verification",
123
+ }
124
+
125
+
126
+ def rule_title(rule_id: str) -> str:
127
+ """Return the rule's title from the rule index, or the ID itself when unknown."""
128
+ return RULES.get(rule_id, rule_id)
teef/cli.py ADDED
@@ -0,0 +1,466 @@
1
+ """The ``teef`` command line: ``verify``, ``sign``, ``encrypt`` and ``decrypt``."""
2
+
3
+ import argparse
4
+ import contextlib
5
+ import json
6
+ import os
7
+ import sys
8
+ import zipfile
9
+ from datetime import date
10
+ from pathlib import Path
11
+ from typing import Any, NoReturn
12
+
13
+ from joserfc.errors import JoseError
14
+ from joserfc.jwk import RSAKey
15
+
16
+ from .catalog import rule_title
17
+ from .context import Context, Limits
18
+ from .findings import Finding
19
+ from .jose import (
20
+ decrypt_failure,
21
+ decrypt_package,
22
+ encrypt_package,
23
+ jwe_header,
24
+ jwe_header_problem,
25
+ sign_manifest,
26
+ strip_jwe,
27
+ )
28
+ from .keys import KeyFileError, load_key_set, load_private_key, load_public_key
29
+ from .parsing import parse_manifest
30
+ from .reader import ReadResult, encryption_text, read, signature_text
31
+ from .report import render_html
32
+ from .serialize import zip_bytes
33
+
34
+ EXIT_VALID, EXIT_INVALID, EXIT_USAGE = 0, 1, 2
35
+
36
+
37
+ class UsageError(Exception):
38
+ """A problem with the command line or its input files, not with the package."""
39
+
40
+
41
+ class _Parser(argparse.ArgumentParser):
42
+ def error(self, message: str) -> NoReturn:
43
+ raise UsageError(message)
44
+
45
+
46
+ def _date(value: str) -> date:
47
+ try:
48
+ return date.fromisoformat(value)
49
+ except ValueError:
50
+ raise argparse.ArgumentTypeError(f"invalid date {value!r}, expected YYYY-MM-DD") from None
51
+
52
+
53
+ def _positive_int(value: str) -> int:
54
+ try:
55
+ number = int(value)
56
+ except ValueError:
57
+ number = 0
58
+ if number < 1:
59
+ raise argparse.ArgumentTypeError(f"expected a positive whole number, got {value!r}")
60
+ return number
61
+
62
+
63
+ def build_parser() -> argparse.ArgumentParser:
64
+ parser = _Parser(prog="teef", description="Work with TEEF evidence exchange packages.")
65
+ commands = parser.add_subparsers(dest="command", required=True, parser_class=_Parser)
66
+ verify = commands.add_parser(
67
+ "verify",
68
+ help="check a received package and list its findings",
69
+ description="Check a package given as a folder, a ZIP archive, or a manifest.json.",
70
+ )
71
+ verify.add_argument("path", type=Path, help="package folder, ZIP archive, or manifest.json")
72
+ verify.add_argument(
73
+ "--basedir",
74
+ type=Path,
75
+ metavar="DIR",
76
+ help="when PATH is a manifest file, read the package files from DIR",
77
+ )
78
+ verify.add_argument(
79
+ "--previous",
80
+ action="append",
81
+ type=Path,
82
+ default=[],
83
+ metavar="MANIFEST",
84
+ help="manifest of a package already received (repeatable)",
85
+ )
86
+ verify.add_argument(
87
+ "--intake-date",
88
+ type=_date,
89
+ metavar="YYYY-MM-DD",
90
+ help="date the package is taken in for review (default: its generation date)",
91
+ )
92
+ verify.add_argument(
93
+ "--known-questionnaire",
94
+ action="append",
95
+ nargs=2,
96
+ metavar=("URI", "VERSION"),
97
+ help="a questionnaire and version you know (repeatable); unknown ones are then reported",
98
+ )
99
+ defaults = Limits()
100
+ verify.add_argument(
101
+ "--max-archive-bytes", type=_positive_int, default=defaults.max_archive_bytes, metavar="N"
102
+ )
103
+ verify.add_argument(
104
+ "--max-entries", type=_positive_int, default=defaults.max_entries, metavar="N"
105
+ )
106
+ verify.add_argument(
107
+ "--max-expanded-bytes", type=_positive_int, default=defaults.max_expanded_bytes, metavar="N"
108
+ )
109
+ verify.add_argument(
110
+ "--trusted-keys",
111
+ type=Path,
112
+ metavar="JWKS",
113
+ help="JWK Set of the publisher keys you trust; the signature is then verified",
114
+ )
115
+ verify.add_argument(
116
+ "--require-signature",
117
+ action="store_true",
118
+ help="report a package without a verified signature as an error (needs --trusted-keys)",
119
+ )
120
+ verify.add_argument(
121
+ "--decryption-key", type=Path, metavar="PEM", help="your private key, to open a JWE"
122
+ )
123
+ verify.add_argument(
124
+ "--decryption-key-id", metavar="KID", help="key ID of --decryption-key (required with it)"
125
+ )
126
+ _password_option(verify, "--decryption-key")
127
+ verify.add_argument("--json", action="store_true", help="print the result as JSON")
128
+ verify.add_argument(
129
+ "--html",
130
+ type=Path,
131
+ metavar="FILE",
132
+ help="also write the HTML review report to FILE (replaces an existing file)",
133
+ )
134
+ _add_sig_commands(commands)
135
+ return parser
136
+
137
+
138
+ def _password_option(parser: argparse.ArgumentParser, key_option: str) -> None:
139
+ parser.add_argument(
140
+ "--key-password-env",
141
+ metavar="NAME",
142
+ help=f"name of the environment variable holding the password of {key_option}",
143
+ )
144
+
145
+
146
+ def _add_sig_commands(commands: Any) -> None:
147
+ sign = commands.add_parser(
148
+ "sign",
149
+ help="add a detached signature (manifest.jws) to a package",
150
+ description="Sign a package folder in place, or a ZIP archive into a new ZIP (-o).",
151
+ )
152
+ sign.add_argument("path", type=Path, help="package folder or ZIP archive")
153
+ sign.add_argument("--key", type=Path, required=True, metavar="PEM", help="private key (PEM)")
154
+ sign.add_argument("--kid", required=True, metavar="KID", help="key ID to put in the signature")
155
+ sign.add_argument("-o", "--output", type=Path, metavar="OUT", help="new ZIP (required for ZIP)")
156
+ sign.add_argument("--force", action="store_true", help="replace an existing signature or file")
157
+ _password_option(sign, "--key")
158
+
159
+ encrypt = commands.add_parser(
160
+ "encrypt",
161
+ help="encrypt a ZIP package for a recipient",
162
+ description="Encrypt a package ZIP as a JWE for the recipient's public key.",
163
+ )
164
+ encrypt.add_argument("path", type=Path, help="package ZIP archive")
165
+ encrypt.add_argument(
166
+ "--recipient-key", type=Path, required=True, metavar="FILE", help="public key (PEM or JWK)"
167
+ )
168
+ encrypt.add_argument("--kid", metavar="KID", help="key ID of a PEM key (a JWK has its own)")
169
+ encrypt.add_argument("-o", "--output", type=Path, required=True, metavar="OUT.jwe")
170
+ encrypt.add_argument("--force", action="store_true", help="replace an existing output file")
171
+
172
+ decrypt = commands.add_parser(
173
+ "decrypt",
174
+ help="decrypt an encrypted package to a ZIP",
175
+ description="Decrypt a JWE package with your private key.",
176
+ )
177
+ decrypt.add_argument("path", type=Path, help="encrypted package (JWE)")
178
+ decrypt.add_argument("--key", type=Path, required=True, metavar="PEM", help="private key (PEM)")
179
+ decrypt.add_argument("--kid", required=True, metavar="KID", help="key ID of the key")
180
+ decrypt.add_argument("-o", "--output", type=Path, required=True, metavar="OUT.zip")
181
+ decrypt.add_argument("--force", action="store_true", help="replace an existing output file")
182
+ _password_option(decrypt, "--key")
183
+
184
+
185
+ def _load_previous(path: Path) -> dict[str, Any]:
186
+ try:
187
+ data = path.read_bytes()
188
+ except OSError as error:
189
+ raise UsageError(f"cannot read previous package {path}: {error.strerror}") from None
190
+ manifest, findings = parse_manifest(data)
191
+ if manifest is None:
192
+ raise UsageError(f"previous package {path} is not a valid manifest: {findings[0].message}")
193
+ return manifest
194
+
195
+
196
+ def _password(name: str | None) -> bytes | None:
197
+ if name is None:
198
+ return None
199
+ value = os.environ.get(name)
200
+ if value is None:
201
+ raise UsageError(f"environment variable {name} (--key-password-env) is not set")
202
+ return value.encode()
203
+
204
+
205
+ def _private_key(path: Path, kid: str, password_env: str | None) -> RSAKey:
206
+ try:
207
+ return load_private_key(path, kid=kid, password=_password(password_env))
208
+ except KeyFileError as error:
209
+ raise UsageError(str(error)) from None
210
+
211
+
212
+ def _context(args: argparse.Namespace) -> Context:
213
+ known = args.known_questionnaire
214
+ if args.decryption_key is not None and args.decryption_key_id is None:
215
+ raise UsageError("--decryption-key requires --decryption-key-id")
216
+ decryption_key = None
217
+ if args.decryption_key is not None:
218
+ decryption_key = _private_key(
219
+ args.decryption_key, args.decryption_key_id, args.key_password_env
220
+ )
221
+ if args.require_signature and args.trusted_keys is None:
222
+ raise UsageError("--require-signature needs --trusted-keys to verify the signature")
223
+ trusted = None
224
+ if args.trusted_keys is not None:
225
+ try:
226
+ trusted = load_key_set(args.trusted_keys)
227
+ except KeyFileError as error:
228
+ raise UsageError(str(error)) from None
229
+ return Context(
230
+ trusted_keys=trusted,
231
+ decryption_key=decryption_key,
232
+ require_signature=args.require_signature,
233
+ previous_packages=tuple(_load_previous(p) for p in args.previous),
234
+ intake_date=args.intake_date,
235
+ known_questionnaires=frozenset((uri, version) for uri, version in known) if known else None,
236
+ limits=Limits(
237
+ max_archive_bytes=args.max_archive_bytes,
238
+ max_entries=args.max_entries,
239
+ max_expanded_bytes=args.max_expanded_bytes,
240
+ ),
241
+ )
242
+
243
+
244
+ def _finding_lines(finding: Finding, width: int) -> list[str]:
245
+ indent = " " * (width + 4)
246
+ lines = [
247
+ f" {finding.rule_id:<{width}} {rule_title(finding.rule_id)}",
248
+ f"{indent}{finding.message}",
249
+ ]
250
+ if finding.location:
251
+ lines.append(f"{indent}at {finding.location}")
252
+ return lines
253
+
254
+
255
+ def _count(n: int, noun: str) -> str:
256
+ return f"{n} {noun}" + ("" if n == 1 else "s")
257
+
258
+
259
+ def _sig_lines(result: ReadResult) -> list[str]:
260
+ lines = [f"Signature: {signature_text(result)}"]
261
+ encryption = encryption_text(result)
262
+ if encryption is not None:
263
+ lines.append(encryption)
264
+ return lines
265
+
266
+
267
+ def format_text(result: ReadResult) -> str:
268
+ """Return the findings as a report for a reviewer."""
269
+ lines = [f"{'VALID' if result.valid else 'INVALID'} {result.source}"]
270
+ if not result.findings:
271
+ lines += _sig_lines(result)
272
+ lines += ["", "No findings."]
273
+ return "\n".join(lines) + "\n"
274
+ lines.append(
275
+ f"{_count(len(result.errors), 'error')}, {_count(len(result.warnings), 'warning')}"
276
+ )
277
+ lines += _sig_lines(result)
278
+ width = max(len(f.rule_id) for f in result.findings)
279
+ for heading, group in (("Errors", result.errors), ("Warnings", result.warnings)):
280
+ if group:
281
+ lines += ["", heading]
282
+ for finding in group:
283
+ lines += _finding_lines(finding, width)
284
+ return "\n".join(lines) + "\n"
285
+
286
+
287
+ def _finding_json(finding: Finding) -> dict[str, Any]:
288
+ return {
289
+ "ruleId": finding.rule_id,
290
+ "title": rule_title(finding.rule_id),
291
+ "message": finding.message,
292
+ "location": finding.location,
293
+ }
294
+
295
+
296
+ def to_json(result: ReadResult) -> dict[str, Any]:
297
+ """Return the result in the stable JSON shape used by ``--json``."""
298
+ return {
299
+ "source": str(result.source),
300
+ "result": "valid" if result.valid else "invalid",
301
+ "packageId": result.manifest.package_id if result.manifest else None,
302
+ "errors": [_finding_json(f) for f in result.errors],
303
+ "warnings": [_finding_json(f) for f in result.warnings],
304
+ "signature": (
305
+ {"kid": result.signature.kid, "status": result.signature.status}
306
+ if result.signature
307
+ else None
308
+ ),
309
+ "encryption": {"kid": result.encryption.kid} if result.encryption else None,
310
+ }
311
+
312
+
313
+ def _verify(args: argparse.Namespace) -> int:
314
+ context = _context(args)
315
+ try:
316
+ result = read(args.path, context, base_dir=args.basedir)
317
+ except FileNotFoundError as error:
318
+ raise UsageError(str(error)) from None
319
+ except ValueError as error:
320
+ raise UsageError(f"--basedir {str(error).removeprefix('base_dir ')}") from None
321
+ except OSError as error:
322
+ raise UsageError(f"cannot read {error.filename or args.path}: {error.strerror}") from None
323
+ if args.json:
324
+ sys.stdout.write(json.dumps(to_json(result), indent=2, ensure_ascii=False) + "\n")
325
+ else:
326
+ sys.stdout.write(format_text(result))
327
+ if args.html is not None:
328
+ sys.stdout.flush()
329
+ try:
330
+ args.html.write_text(render_html(result), encoding="utf-8")
331
+ except OSError as error:
332
+ raise UsageError(f"cannot write {args.html}: {error.strerror}") from None
333
+ return EXIT_VALID if result.valid else EXIT_INVALID
334
+
335
+
336
+ def _read_input(path: Path, what: str) -> bytes:
337
+ try:
338
+ return path.read_bytes()
339
+ except OSError as error:
340
+ raise UsageError(f"cannot read {what} {path}: {error.strerror}") from None
341
+
342
+
343
+ def _read_checked(path: Path) -> ReadResult:
344
+ try:
345
+ result = read(path, Context())
346
+ except FileNotFoundError as error:
347
+ raise UsageError(str(error)) from None
348
+ except OSError as error:
349
+ raise UsageError(f"cannot read {error.filename or path}: {error.strerror}") from None
350
+ if result.errors:
351
+ first = result.errors[0]
352
+ raise UsageError(
353
+ f"{path} has {_count(len(result.errors), 'error')} "
354
+ f"(first: {first.rule_id} {first.message}); run 'teef verify' and fix them first"
355
+ )
356
+ return result
357
+
358
+
359
+ def _write_new(path: Path, data: bytes, force: bool) -> None:
360
+ try:
361
+ with path.open("wb" if force else "xb") as handle:
362
+ handle.write(data)
363
+ except FileExistsError:
364
+ raise UsageError(f"{path} exists; use --force to replace it") from None
365
+ except OSError as error:
366
+ raise UsageError(f"cannot write {path}: {error.strerror}") from None
367
+
368
+
369
+ def _refuse_existing(path: Path, force: bool) -> None:
370
+ if path.exists() and not force:
371
+ raise UsageError(f"{path} exists; use --force to replace it")
372
+
373
+
374
+ def _refuse_jwe(path: Path, advice: str) -> None:
375
+ if path.is_file() and jwe_header(strip_jwe(_read_input(path, "package"))) is not None:
376
+ raise UsageError(f"{path} is an encrypted package; {advice}")
377
+
378
+
379
+ def _sign(args: argparse.Namespace) -> int:
380
+ path: Path = args.path
381
+ if path.is_file() and not zipfile.is_zipfile(path):
382
+ _refuse_jwe(path, "decrypt it first")
383
+ raise UsageError(f"{path} is not a package folder or ZIP archive")
384
+ in_place = path.is_dir()
385
+ if not in_place and args.output is None:
386
+ raise UsageError("signing a ZIP archive needs -o OUT for the new ZIP")
387
+ if in_place and args.output is not None:
388
+ raise UsageError("-o applies to ZIP archives only; a folder is signed in place")
389
+ key = _private_key(args.key, args.kid, args.key_password_env)
390
+ result = _read_checked(path)
391
+ manifest_bytes = result.manifest_bytes
392
+ if manifest_bytes is None:
393
+ raise UsageError(f"{path} has no readable manifest")
394
+ if in_place:
395
+ target = path / "manifest.jws"
396
+ _refuse_existing(target, args.force)
397
+ else:
398
+ target = args.output
399
+ _refuse_existing(target, args.force)
400
+ if "manifest.jws" in result.files and not args.force:
401
+ raise UsageError(f"{path} already has a manifest.jws; use --force to replace it")
402
+ try:
403
+ jws = sign_manifest(manifest_bytes, key)
404
+ except (JoseError, ValueError) as error:
405
+ raise UsageError(f"cannot sign with key {args.kid}: {type(error).__name__}") from None
406
+ if in_place:
407
+ _write_new(target, jws, force=True)
408
+ else:
409
+ files = dict(result.files)
410
+ files["manifest.jws"] = jws
411
+ _write_new(target, zip_bytes(manifest_bytes, files), args.force)
412
+ return EXIT_VALID
413
+
414
+
415
+ def _encrypt(args: argparse.Namespace) -> int:
416
+ path: Path = args.path
417
+ if not path.is_file():
418
+ raise UsageError(f"{path} is not a ZIP archive")
419
+ _refuse_jwe(path, "it is already encrypted")
420
+ if not zipfile.is_zipfile(path):
421
+ raise UsageError(f"{path} is not a ZIP archive")
422
+ try:
423
+ key = load_public_key(args.recipient_key, kid=args.kid)
424
+ except KeyFileError as error:
425
+ raise UsageError(str(error)) from None
426
+ _refuse_existing(args.output, args.force)
427
+ _read_checked(path)
428
+ try:
429
+ data = encrypt_package(_read_input(path, "package"), key)
430
+ except (JoseError, ValueError) as error:
431
+ raise UsageError(f"cannot encrypt for key {key.kid}: {type(error).__name__}") from None
432
+ _write_new(args.output, data, args.force)
433
+ return EXIT_VALID
434
+
435
+
436
+ def _decrypt(args: argparse.Namespace) -> int:
437
+ data = strip_jwe(_read_input(args.path, "package"))
438
+ header = jwe_header(data)
439
+ if header is None:
440
+ raise UsageError(f"{args.path} is not an encrypted package (compact JWE)")
441
+ problem = jwe_header_problem(header)
442
+ if problem is not None:
443
+ raise UsageError(f"{args.path} cannot be decrypted: {problem}")
444
+ key = _private_key(args.key, args.kid, args.key_password_env)
445
+ _refuse_existing(args.output, args.force)
446
+ try:
447
+ plain = decrypt_package(data, key)
448
+ except (JoseError, ValueError) as error:
449
+ raise UsageError(decrypt_failure(header, key, error)) from None
450
+ _write_new(args.output, plain, args.force)
451
+ return EXIT_VALID
452
+
453
+
454
+ def main(argv: list[str] | None = None) -> int:
455
+ """Run the command line and return its exit code."""
456
+ reconfigure = getattr(sys.stdout, "reconfigure", None)
457
+ if reconfigure is not None:
458
+ with contextlib.suppress(ValueError, OSError):
459
+ reconfigure(errors="replace")
460
+ try:
461
+ args = build_parser().parse_args(argv)
462
+ handlers = {"verify": _verify, "sign": _sign, "encrypt": _encrypt, "decrypt": _decrypt}
463
+ return handlers[args.command](args)
464
+ except UsageError as error:
465
+ sys.stderr.write(f"teef: error: {error}\n")
466
+ return EXIT_USAGE