pulp-python 3.37.1__py3-none-any.whl → 3.38.0__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.
@@ -12,7 +12,7 @@ class PulpPythonPluginAppConfig(PulpPluginAppConfig):
12
12
 
13
13
  name = "pulp_python.app"
14
14
  label = "python"
15
- version = "3.37.1"
15
+ version = "3.38.0"
16
16
  python_package_name = "pulp-python"
17
17
  domain_compatible = True
18
18
 
@@ -1,12 +1,28 @@
1
+ import json
1
2
  from typing import Annotated, Literal, Union, get_args
2
3
 
3
- from pydantic import BaseModel, ConfigDict, Field
4
+ from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
5
+ from cryptography.hazmat.primitives import hashes, serialization
6
+ from cryptography.hazmat.primitives.asymmetric import padding as crypto_padding
7
+ from cryptography.hazmat.primitives.asymmetric import rsa
8
+ from cryptography.x509 import load_der_x509_certificate
9
+ from django.conf import settings
10
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
4
11
  from pydantic.alias_generators import to_snake
12
+ from pypi_attestations import Attestation as _UpstreamAttestation
5
13
  from pypi_attestations import (
6
- Attestation,
7
14
  Distribution,
15
+ Envelope, # noqa - needed in module namespace for Pydantic model rebuild
8
16
  Publisher,
17
+ VerificationError,
18
+ VerificationMaterial,
9
19
  )
20
+ from sigstore.dsse import Envelope as DSSEEnvelope
21
+ from sigstore.dsse import _pae
22
+
23
+ from pulpcore.plugin.util import get_domain
24
+
25
+ _verification_key_cache = {}
10
26
 
11
27
 
12
28
  class _PermissivePolicy:
@@ -32,6 +48,8 @@ class AnyPublisher(BaseModel):
32
48
  # Get the underlying Union type of the original Publisher
33
49
  # Publisher is Annotated[Union[...], Field(discriminator="kind")]
34
50
  _OriginalPublisherTypes = get_args(Publisher.__origin__)
51
+ # Get the kinds of the original publisher types, they can only be proven by a Sigstore certificate
52
+ _TrustedPublisherKinds = {t.model_fields["kind"].default for t in _OriginalPublisherTypes}
35
53
  # Add AnyPublisher to the list of original publisher types
36
54
  _ExtendedPublisherTypes = (*_OriginalPublisherTypes, AnyPublisher)
37
55
  _ExtendedPublisherUnion = Union[_ExtendedPublisherTypes]
@@ -39,6 +57,21 @@ _ExtendedPublisherUnion = Union[_ExtendedPublisherTypes]
39
57
  ExtendedPublisher = Annotated[_ExtendedPublisherUnion, Field(union_mode="left_to_right")]
40
58
 
41
59
 
60
+ class Attestation(_UpstreamAttestation):
61
+ """
62
+ Attestation object as defined in PEP 740.
63
+
64
+ Inherits from the upstream pypi_attestations.Attestation to keep Sigstore
65
+ verification methods (to_bundle, verify), but makes verification_material
66
+ optional to support attestations signed with a custom key instead of Sigstore.
67
+ """
68
+
69
+ verification_material: VerificationMaterial | None = None
70
+ """
71
+ Cryptographic materials used to verify `message_signature`.
72
+ """
73
+
74
+
42
75
  class AttestationBundle(BaseModel):
43
76
  """
44
77
  AttestationBundle object as defined in PEP740.
@@ -58,14 +91,122 @@ class Provenance(BaseModel):
58
91
  attestation_bundles: list[AttestationBundle]
59
92
 
60
93
 
94
+ def _load_verification_key(domain_name):
95
+ """Load the attestation verification public key configured for the domain, with caching."""
96
+ keys = settings.ATTESTATION_VERIFICATION_KEYS
97
+ if not isinstance(keys, dict):
98
+ raise VerificationError(
99
+ "ATTESTATION_VERIFICATION_KEYS must map domain names to public key paths"
100
+ )
101
+ key_path = keys.get(domain_name)
102
+ if not key_path:
103
+ return None
104
+ if key_path not in _verification_key_cache:
105
+ try:
106
+ with open(key_path, "rb") as f:
107
+ key = serialization.load_pem_public_key(f.read())
108
+ except (OSError, ValueError, UnsupportedAlgorithm) as e:
109
+ raise VerificationError(
110
+ f"could not load the verification key for domain '{domain_name}' "
111
+ f"from {key_path}: {e}"
112
+ )
113
+ if not isinstance(key, rsa.RSAPublicKey):
114
+ raise VerificationError(
115
+ f"the verification key for domain '{domain_name}' in {key_path} "
116
+ "must be an RSA public key"
117
+ )
118
+ _verification_key_cache[key_path] = key
119
+ return _verification_key_cache[key_path]
120
+
121
+
122
+ def _has_certificate(attestation):
123
+ """Check whether the attestation carries a certificate, rejecting unparseable ones."""
124
+ vm = attestation.verification_material
125
+ if vm is None:
126
+ return False
127
+ try:
128
+ load_der_x509_certificate(vm.certificate)
129
+ except ValueError as e:
130
+ raise VerificationError(f"invalid X.509 certificate in verification_material: {e}")
131
+ return True
132
+
133
+
134
+ def _verify_statement_subject(attestation, dist):
135
+ """Validate that the in-toto statement subject matches the distribution."""
136
+ try:
137
+ stmt = json.loads(attestation.envelope.statement)
138
+ except (json.JSONDecodeError, UnicodeDecodeError) as e:
139
+ raise VerificationError(f"invalid statement: {e}")
140
+
141
+ try:
142
+ subjects = stmt.get("subject", [])
143
+ if len(subjects) != 1:
144
+ raise VerificationError("expected exactly one subject in statement")
145
+
146
+ subject = subjects[0]
147
+ name = subject.get("name", "")
148
+ if name != dist.name:
149
+ raise VerificationError(
150
+ f"subject does not match distribution name: {name} != {dist.name}"
151
+ )
152
+
153
+ digest = subject.get("digest", {}).get("sha256")
154
+ if digest != dist.digest:
155
+ raise VerificationError("subject does not match distribution digest")
156
+ except (AttributeError, TypeError) as e:
157
+ raise VerificationError(f"malformed statement: {e}")
158
+
159
+
160
+ def _verify_signature(attestation, public_key):
161
+ """Verify the attestation's RSA signature over the DSSE PAE bytes."""
162
+ statement_bytes = attestation.envelope.statement
163
+ signature_bytes = attestation.envelope.signature
164
+ pae = _pae(DSSEEnvelope._TYPE, statement_bytes)
165
+ try:
166
+ public_key.verify(
167
+ signature_bytes,
168
+ pae,
169
+ crypto_padding.PKCS1v15(),
170
+ hashes.SHA256(),
171
+ )
172
+ except InvalidSignature:
173
+ raise VerificationError("signature verification failed")
174
+
175
+
61
176
  def verify_provenance(filename, sha256, provenance, offline=True):
62
- """Verify the provenance object is valid for the package."""
63
- dist = Distribution(name=filename, digest=sha256)
177
+ """Verify the provenance object is valid for the package.
178
+
179
+ Each attestation is routed to one of two coexisting verification paths:
180
+ 1. Attestations with a valid Sigstore certificate follow the standard PEP 740 path.
181
+ 2. Attestations without a certificate are verified against the key configured for the
182
+ current domain in ATTESTATION_VERIFICATION_KEYS using RSA PKCS1v15 signatures.
183
+ Attestations with a certificate that can't be parsed are rejected.
184
+ """
185
+ try:
186
+ dist = Distribution(name=filename, digest=sha256)
187
+ except ValidationError as e:
188
+ raise VerificationError(f"invalid distribution filename {filename}: {e}")
64
189
  for bundle in provenance.attestation_bundles:
65
190
  publisher = bundle.publisher
66
191
  policy = publisher._as_policy()
67
192
  for attestation in bundle.attestations:
68
- sig_bundle = attestation.to_bundle()
69
- checkpoint = sig_bundle.log_entry._inner.inclusion_proof.checkpoint
70
- staging = "sigstage.dev" in checkpoint.envelope
71
- attestation.verify(policy, dist, staging=staging, offline=offline)
193
+ if _has_certificate(attestation):
194
+ sig_bundle = attestation.to_bundle()
195
+ checkpoint = sig_bundle.log_entry._inner.inclusion_proof.checkpoint
196
+ staging = "sigstage.dev" in checkpoint.envelope
197
+ attestation.verify(policy, dist, staging=staging, offline=offline)
198
+ else:
199
+ if publisher.kind in _TrustedPublisherKinds:
200
+ raise VerificationError(
201
+ f"publisher kind '{publisher.kind}' requires a Sigstore certificate"
202
+ )
203
+ domain_name = get_domain().name
204
+ verification_key = _load_verification_key(domain_name)
205
+ if verification_key:
206
+ _verify_statement_subject(attestation, dist)
207
+ _verify_signature(attestation, verification_key)
208
+ else:
209
+ raise VerificationError(
210
+ "attestation has no Sigstore certificate, and "
211
+ f"ATTESTATION_VERIFICATION_KEYS has no key for domain '{domain_name}'"
212
+ )
@@ -3,12 +3,19 @@ from gettext import gettext as _
3
3
 
4
4
  from django.db.utils import IntegrityError
5
5
  from pydantic import TypeAdapter, ValidationError
6
+ from pypi_attestations import AttestationError
6
7
  from rest_framework import serializers
7
8
 
8
9
  from pulpcore.plugin.models import Artifact
9
10
  from pulpcore.plugin.util import get_domain
10
11
 
11
- from pulp_python.app.provenance import Attestation
12
+ from pulp_python.app.provenance import (
13
+ AnyPublisher,
14
+ Attestation,
15
+ AttestationBundle,
16
+ Provenance,
17
+ verify_provenance,
18
+ )
12
19
  from pulp_python.app.utils import DIST_EXTENSIONS, SUPPORTED_METADATA_VERSIONS
13
20
 
14
21
  log = logging.getLogger(__name__)
@@ -110,6 +117,7 @@ class PackageUploadSerializer(serializers.Serializer):
110
117
  }
111
118
  )
112
119
 
120
+ sha256 = data.get("sha256_digest")
113
121
  if attestations := data.get("attestations"):
114
122
  try:
115
123
  attestations = TypeAdapter(list[Attestation]).validate_python(attestations)
@@ -117,8 +125,17 @@ class PackageUploadSerializer(serializers.Serializer):
117
125
  raise serializers.ValidationError(
118
126
  {"attestations": _("The uploaded attestations are not valid: {}").format(e)}
119
127
  )
128
+ if attestations and sha256:
129
+ publisher = AnyPublisher(kind="Pulp User")
130
+ att_bundle = AttestationBundle(publisher=publisher, attestations=attestations)
131
+ provenance = Provenance(attestation_bundles=[att_bundle])
132
+ try:
133
+ verify_provenance(file.name, sha256, provenance, offline=True)
134
+ except AttestationError as e:
135
+ raise serializers.ValidationError(
136
+ {"attestations": _("Attestations failed verification: {}").format(e)}
137
+ )
120
138
 
121
- sha256 = data.get("sha256_digest")
122
139
  digests = {"sha256": sha256} if sha256 else None
123
140
  artifact = Artifact.init_and_validate(file, expected_digests=digests)
124
141
  try:
@@ -4,6 +4,8 @@ PYTHON_GROUP_UPLOADS = False
4
4
  PYPI_API_HOSTNAME = "https://" + socket.getfqdn()
5
5
  PYPI_PATH_PREFIX = "/pypi/"
6
6
 
7
+ ATTESTATION_VERIFICATION_KEYS = {}
8
+
7
9
  DRF_ACCESS_POLICY = {
8
10
  "dynaconf_merge_unique": True,
9
11
  "reusable_conditions": ["pulp_python.app.global_access_conditions"],
pulp_python/app/utils.py CHANGED
@@ -666,12 +666,12 @@ class PackageIncludeFilter:
666
666
  self._filter_excludes = self._parse_packages(self.remote.excludes)
667
667
 
668
668
  def _parse_packages(self, packages):
669
+ """Group requirements by project and whether they specify a version range."""
669
670
  config = defaultdict(lambda: defaultdict(list))
670
671
  for value in packages:
671
672
  requirement = Requirement(value)
672
673
  requirement.name = canonicalize_name(requirement.name)
673
674
  if requirement.specifier:
674
- requirement.specifier.prereleases = True
675
675
  config["range"][requirement.name].append(requirement)
676
676
  else:
677
677
  config["full"][requirement.name].append(requirement)
@@ -706,7 +706,7 @@ class PackageIncludeFilter:
706
706
  include_range = self._filter_includes.get("range", {})
707
707
  if project_name in include_range:
708
708
  for req in include_range[project_name]:
709
- if version in req.specifier:
709
+ if req.specifier.contains(version, prereleases=True):
710
710
  break
711
711
  else:
712
712
  return False
@@ -714,7 +714,7 @@ class PackageIncludeFilter:
714
714
  exclude_range = self._filter_excludes.get("range", {})
715
715
  if project_name in exclude_range:
716
716
  for req in exclude_range[project_name]:
717
- if version in req.specifier:
717
+ if req.specifier.contains(version, prereleases=True):
718
718
  return False
719
719
 
720
720
  return True
@@ -0,0 +1,365 @@
1
+ """Functional tests for verifying attestations signed with a server-configured key.
2
+
3
+ These tests exercise the attestation / provenance upload paths with
4
+ attestations that carry an RSA signature instead of a Sigstore certificate.
5
+
6
+ A static test keypair is shipped in .ci/assets/keys/ and the matching
7
+ public key is configured for the default domain in PULP_ATTESTATION_VERIFICATION_KEYS so that
8
+ signature verification is fully exercised end-to-end.
9
+ """
10
+
11
+ import base64
12
+ import hashlib
13
+ import json
14
+ import os
15
+
16
+ import pytest
17
+ from cryptography.hazmat.primitives import hashes, serialization
18
+ from cryptography.hazmat.primitives.asymmetric import padding as crypto_padding
19
+ from cryptography.hazmat.primitives.asymmetric import rsa
20
+
21
+ from pulpcore.tests.functional.utils import PulpTaskError
22
+
23
+ from pulp_python.tests.functional.constants import PYTHON_EGG_FILENAME, PYTHON_URL
24
+
25
+ DSSE_PAYLOAD_TYPE = "application/vnd.in-toto+json"
26
+
27
+ TEST_PRIVATE_KEY_PATH = "/etc/pki/attestation/test-key-private.pem"
28
+ TEST_PUBLIC_KEY_PATH = "/etc/pki/attestation/test-key.pem"
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Helpers
33
+ # ---------------------------------------------------------------------------
34
+
35
+
36
+ def _build_statement(filename, sha256):
37
+ """Build a minimal in-toto statement with an SLSA v1 provenance predicate."""
38
+ return json.dumps(
39
+ {
40
+ "_type": "https://in-toto.io/Statement/v1",
41
+ "predicateType": "https://slsa.dev/provenance/v1",
42
+ "subject": [{"name": filename, "digest": {"sha256": sha256}}],
43
+ "predicate": {
44
+ "buildDefinition": {"buildType": "https://konflux-ci.dev/PythonWheelBuild@v1"},
45
+ "runDetails": {"builder": {"id": "https://konflux-ci.dev/calunga"}},
46
+ },
47
+ }
48
+ ).encode()
49
+
50
+
51
+ def _pae(payload_type, payload):
52
+ """Compute the DSSE Pre-Authentication Encoding."""
53
+ return b"DSSEv1 %d %b %d %b" % (
54
+ len(payload_type),
55
+ payload_type.encode(),
56
+ len(payload),
57
+ payload,
58
+ )
59
+
60
+
61
+ def _sign(statement_bytes, private_key):
62
+ pae = _pae(DSSE_PAYLOAD_TYPE, statement_bytes)
63
+ return private_key.sign(
64
+ pae,
65
+ crypto_padding.PKCS1v15(),
66
+ hashes.SHA256(),
67
+ )
68
+
69
+
70
+ def _b64(data: bytes) -> str:
71
+ return base64.b64encode(data).decode()
72
+
73
+
74
+ def _make_attestation(statement_bytes, signature_bytes):
75
+ """Return a single key-signed Attestation dict without verification material."""
76
+ return {
77
+ "version": 1,
78
+ "verification_material": None,
79
+ "envelope": {
80
+ "statement": _b64(statement_bytes),
81
+ "signature": _b64(signature_bytes),
82
+ },
83
+ }
84
+
85
+
86
+ def _make_provenance(attestation):
87
+ """Wrap an attestation into a full PEP-740 Provenance object."""
88
+ return {
89
+ "version": 1,
90
+ "attestation_bundles": [
91
+ {
92
+ "publisher": {"kind": "Konflux", "builder": "calunga"},
93
+ "attestations": [attestation],
94
+ }
95
+ ],
96
+ }
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Fixtures
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ @pytest.fixture(scope="session")
105
+ def test_private_key(pulp_settings):
106
+ """Load the static test attestation signing key from .ci/assets/keys/."""
107
+ if not os.path.exists(TEST_PRIVATE_KEY_PATH):
108
+ pytest.skip(
109
+ f"Test attestation private key not found at {TEST_PRIVATE_KEY_PATH} (not running in CI container?)"
110
+ )
111
+ if pulp_settings.ATTESTATION_VERIFICATION_KEYS.get("default") != TEST_PUBLIC_KEY_PATH:
112
+ pytest.fail(
113
+ f"ATTESTATION_VERIFICATION_KEYS does not map the default domain to {TEST_PUBLIC_KEY_PATH}"
114
+ )
115
+ with open(TEST_PRIVATE_KEY_PATH, "rb") as f:
116
+ return serialization.load_pem_private_key(f.read(), password=None)
117
+
118
+
119
+ @pytest.fixture()
120
+ def _provenance_file(tmp_path):
121
+ """Return a helper that writes a provenance dict to a temp file."""
122
+
123
+ def _write(provenance_dict):
124
+ path = tmp_path / "provenance.json"
125
+ path.write_text(json.dumps(provenance_dict))
126
+ return str(path)
127
+
128
+ return _write
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Tests
133
+ # ---------------------------------------------------------------------------
134
+
135
+
136
+ def test_key_signed_provenance_stored(
137
+ python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
138
+ ):
139
+ """A key-signed provenance is accepted and stored when verify=True."""
140
+ content = python_content_factory()
141
+
142
+ stmt = _build_statement(content.filename, content.sha256)
143
+ sig = _sign(stmt, test_private_key)
144
+ att = _make_attestation(stmt, sig)
145
+ prov = _make_provenance(att)
146
+
147
+ task = python_bindings.ContentProvenanceApi.create(
148
+ package=content.pulp_href,
149
+ file=_provenance_file(prov),
150
+ verify=True,
151
+ ).task
152
+ result = monitor_task(task)
153
+
154
+ prov_obj = python_bindings.ContentProvenanceApi.read(result.created_resources[-1])
155
+ assert prov_obj.package == content.pulp_href
156
+ stored_att = prov_obj.provenance["attestation_bundles"][0]["attestations"][0]
157
+ assert stored_att["envelope"]["statement"] == _b64(stmt)
158
+ publisher = prov_obj.provenance["attestation_bundles"][0]["publisher"]
159
+ assert publisher["builder"] == "calunga"
160
+ assert publisher["kind"] == "Konflux"
161
+
162
+
163
+ def test_key_signed_wrong_subject_name_rejected(
164
+ python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
165
+ ):
166
+ """Verification rejects a key-signed attestation whose subject name does not match."""
167
+ content = python_content_factory()
168
+
169
+ wrong_name = "wrong-package-0.1.tar.gz"
170
+ stmt = _build_statement(wrong_name, content.sha256)
171
+ sig = _sign(stmt, test_private_key)
172
+ att = _make_attestation(stmt, sig)
173
+ prov = _make_provenance(att)
174
+
175
+ task = python_bindings.ContentProvenanceApi.create(
176
+ package=content.pulp_href,
177
+ file=_provenance_file(prov),
178
+ verify=True,
179
+ ).task
180
+ with pytest.raises(PulpTaskError) as exc_info:
181
+ monitor_task(task)
182
+ assert "subject does not match distribution name" in exc_info.value.task.error["description"]
183
+
184
+
185
+ def test_key_signed_wrong_digest_rejected(
186
+ python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
187
+ ):
188
+ """Verification rejects a key-signed attestation whose digest does not match."""
189
+ content = python_content_factory()
190
+
191
+ bad_digest = "0" * 64
192
+ stmt = _build_statement(content.filename, bad_digest)
193
+ sig = _sign(stmt, test_private_key)
194
+ att = _make_attestation(stmt, sig)
195
+ prov = _make_provenance(att)
196
+
197
+ task = python_bindings.ContentProvenanceApi.create(
198
+ package=content.pulp_href,
199
+ file=_provenance_file(prov),
200
+ verify=True,
201
+ ).task
202
+ with pytest.raises(PulpTaskError) as exc_info:
203
+ monitor_task(task)
204
+ assert "subject does not match distribution digest" in exc_info.value.task.error["description"]
205
+
206
+
207
+ def test_key_signed_bad_signature_rejected(
208
+ python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
209
+ ):
210
+ """A key-signed attestation with a valid subject but tampered signature is rejected."""
211
+ content = python_content_factory()
212
+
213
+ stmt = _build_statement(content.filename, content.sha256)
214
+ sig = _sign(stmt, test_private_key)
215
+ tampered_sig = bytes([b ^ 0xFF for b in sig[:32]]) + sig[32:]
216
+ att = _make_attestation(stmt, tampered_sig)
217
+ prov = _make_provenance(att)
218
+
219
+ task = python_bindings.ContentProvenanceApi.create(
220
+ package=content.pulp_href,
221
+ file=_provenance_file(prov),
222
+ verify=True,
223
+ ).task
224
+ with pytest.raises(PulpTaskError) as exc_info:
225
+ monitor_task(task)
226
+ assert "signature verification failed" in exc_info.value.task.error["description"]
227
+
228
+
229
+ def test_key_signed_attestation_via_content_upload(
230
+ python_bindings, python_content_factory, monitor_task, test_private_key
231
+ ):
232
+ """Key-signed attestations can be uploaded alongside a package via the content API."""
233
+ content = python_content_factory()
234
+
235
+ stmt = _build_statement(content.filename, content.sha256)
236
+ sig = _sign(stmt, test_private_key)
237
+ att = _make_attestation(stmt, sig)
238
+
239
+ body = {
240
+ "artifact": content.artifact,
241
+ "relative_path": content.filename,
242
+ "sha256": content.sha256,
243
+ "attestations": json.dumps([att]),
244
+ }
245
+ task = python_bindings.ContentPackagesApi.create(**body).task
246
+ result = monitor_task(task)
247
+
248
+ assert len(result.created_resources) == 2
249
+ prov_obj = python_bindings.ContentProvenanceApi.read(result.created_resources[1])
250
+ publisher = prov_obj.provenance["attestation_bundles"][0]["publisher"]
251
+ assert publisher["kind"] == "Pulp User"
252
+
253
+
254
+ def test_invalid_certificate_not_verified_with_key(
255
+ python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
256
+ ):
257
+ """An attestation with an unparseable certificate is rejected, not verified with the key."""
258
+ content = python_content_factory()
259
+
260
+ stmt = _build_statement(content.filename, content.sha256)
261
+ att = _make_attestation(stmt, _sign(stmt, test_private_key))
262
+ att["verification_material"] = {
263
+ "certificate": _b64(b"not-a-certificate"),
264
+ "transparency_entries": [{"log_index": 0}],
265
+ }
266
+ prov = _make_provenance(att)
267
+
268
+ task = python_bindings.ContentProvenanceApi.create(
269
+ package=content.pulp_href,
270
+ file=_provenance_file(prov),
271
+ verify=True,
272
+ ).task
273
+ with pytest.raises(PulpTaskError) as exc_info:
274
+ monitor_task(task)
275
+ assert "invalid X.509 certificate" in exc_info.value.task.error["description"]
276
+
277
+
278
+ def test_key_signed_attestation_with_other_key_rejected(
279
+ python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
280
+ ):
281
+ """An attestation signed with a key other than the domain's configured key is rejected."""
282
+ content = python_content_factory()
283
+ other_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
284
+
285
+ stmt = _build_statement(content.filename, content.sha256)
286
+ att = _make_attestation(stmt, _sign(stmt, other_key))
287
+ prov = _make_provenance(att)
288
+
289
+ task = python_bindings.ContentProvenanceApi.create(
290
+ package=content.pulp_href,
291
+ file=_provenance_file(prov),
292
+ verify=True,
293
+ ).task
294
+ with pytest.raises(PulpTaskError) as exc_info:
295
+ monitor_task(task)
296
+ assert "signature verification failed" in exc_info.value.task.error["description"]
297
+
298
+
299
+ def test_key_signed_attestation_rejected_in_domain_without_key(
300
+ python_bindings, domain_factory, download_python_file, monitor_task, test_private_key
301
+ ):
302
+ """A key configured for the default domain is not trusted in another domain."""
303
+ domain = domain_factory()
304
+ python_file = download_python_file(PYTHON_EGG_FILENAME, PYTHON_URL)
305
+ with open(python_file, "rb") as f:
306
+ sha256 = hashlib.sha256(f.read()).hexdigest()
307
+
308
+ stmt = _build_statement(PYTHON_EGG_FILENAME, sha256)
309
+ att = _make_attestation(stmt, _sign(stmt, test_private_key))
310
+ body = {
311
+ "file": python_file,
312
+ "relative_path": PYTHON_EGG_FILENAME,
313
+ "attestations": json.dumps([att]),
314
+ }
315
+ task = python_bindings.ContentPackagesApi.create(**body, pulp_domain=domain.name).task
316
+ with pytest.raises(PulpTaskError) as exc_info:
317
+ monitor_task(task)
318
+ err_msg = f"ATTESTATION_VERIFICATION_KEYS has no key for domain '{domain.name}'"
319
+ assert err_msg in exc_info.value.task.error["description"]
320
+
321
+
322
+ def test_key_signed_attestation_with_trusted_publisher_rejected(
323
+ python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
324
+ ):
325
+ """A key-signed attestation cannot claim a Trusted Publisher, which needs a certificate."""
326
+ content = python_content_factory()
327
+
328
+ stmt = _build_statement(content.filename, content.sha256)
329
+ att = _make_attestation(stmt, _sign(stmt, test_private_key))
330
+ prov = _make_provenance(att)
331
+ prov["attestation_bundles"][0]["publisher"] = {
332
+ "kind": "GitHub",
333
+ "repository": "pypa/sampleproject",
334
+ "workflow": "release.yml",
335
+ }
336
+
337
+ task = python_bindings.ContentProvenanceApi.create(
338
+ package=content.pulp_href,
339
+ file=_provenance_file(prov),
340
+ verify=True,
341
+ ).task
342
+ with pytest.raises(PulpTaskError) as exc_info:
343
+ monitor_task(task)
344
+ err_msg = "publisher kind 'GitHub' requires a Sigstore certificate"
345
+ assert err_msg in exc_info.value.task.error["description"]
346
+
347
+
348
+ def test_key_signed_malformed_subject_rejected(
349
+ python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
350
+ ):
351
+ """A key-signed attestation with a malformed subject is rejected, not crashed on."""
352
+ content = python_content_factory()
353
+
354
+ stmt = json.dumps({"_type": "https://in-toto.io/Statement/v1", "subject": None}).encode()
355
+ att = _make_attestation(stmt, _sign(stmt, test_private_key))
356
+ prov = _make_provenance(att)
357
+
358
+ task = python_bindings.ContentProvenanceApi.create(
359
+ package=content.pulp_href,
360
+ file=_provenance_file(prov),
361
+ verify=True,
362
+ ).task
363
+ with pytest.raises(PulpTaskError) as exc_info:
364
+ monitor_task(task)
365
+ assert "malformed statement" in exc_info.value.task.error["description"]
@@ -0,0 +1,56 @@
1
+ import pytest
2
+
3
+ from pulp_python.app.utils import write_simple_detail, write_simple_index
4
+
5
+ XSS_VECTORS = [
6
+ ('<script>alert("xss")</script>', "&lt;script&gt;"),
7
+ ("<img src=x onerror=alert(1)>", "&lt;img"),
8
+ ('" onclick="alert(1)"', "&#34;"),
9
+ ("a&b", "a&amp;b"),
10
+ ]
11
+
12
+
13
+ def test_index_renders_valid_names():
14
+ """Test that valid package names render correctly in the simple index page."""
15
+ page = write_simple_index(["aprojectname", "under_score", "da-sh", "ungefährlich"])
16
+ assert "aprojectname" in page
17
+ assert "under-score" in page
18
+ assert "da-sh" in page
19
+ assert "ungefährlich" in page
20
+
21
+
22
+ @pytest.mark.parametrize("name,escaped", XSS_VECTORS)
23
+ def test_index_escapes_html(name, escaped):
24
+ """Test that autoescape neutralizes HTML injection in the simple index page."""
25
+ page = write_simple_index([name])
26
+ assert name not in page
27
+ assert escaped in page
28
+
29
+
30
+ @pytest.mark.parametrize("name,escaped", XSS_VECTORS)
31
+ def test_detail_escapes_html(name, escaped):
32
+ """Test that autoescape neutralizes HTML injection in the simple detail page."""
33
+ page = write_simple_detail(name, [])
34
+ assert name not in page
35
+ assert escaped in page
36
+
37
+
38
+ def test_detail_escapes_package_fields():
39
+ """Test that autoescape neutralizes HTML injection in package metadata fields."""
40
+ packages = [
41
+ {
42
+ "filename": "<img src=x onerror=alert(1)>",
43
+ "url": 'http://evil.com/"><script>alert(1)</script>',
44
+ "sha256": "abc123",
45
+ "requires_python": None,
46
+ "yanked": False,
47
+ "yanked_reason": "",
48
+ "metadata_sha256": None,
49
+ "provenance": None,
50
+ }
51
+ ]
52
+ page = write_simple_detail("safe-name", packages)
53
+ assert "<img src=x onerror=alert(1)>" not in page
54
+ assert "&lt;img src=x onerror=alert(1)&gt;" in page
55
+ assert 'http://evil.com/"><script>alert(1)</script>' not in page
56
+ assert "http://evil.com/&#34;&gt;&lt;script&gt;alert(1)&lt;/script&gt;" in page
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pulp-python
3
- Version: 3.37.1
3
+ Version: 3.38.0
4
4
  Summary: pulp-python plugin for the Pulp Project
5
5
  Author-email: Pulp Team <pulp-list@redhat.com>
6
6
  Project-URL: Homepage, https://pulpproject.org
@@ -1,18 +1,18 @@
1
1
  pulp_python/__init__.py,sha256=GIuTLoBTc-07dSLJUh8xrZPRz8x-jJ61pfR0J1IjnzI,65
2
2
  pulp_python/pytest_plugin.py,sha256=8Ko-O87JGPC79h8-Ecw2gJLxa6q1Ng8wD6WxbinOnVs,8573
3
- pulp_python/app/__init__.py,sha256=NyosXHMuA4a61fv4YZWIAJwuuIv9NZ09vI0RhlKWxOg,2552
3
+ pulp_python/app/__init__.py,sha256=4VUOKYwbx_efiTTA_5tFRU3IDf1dubc5MQGMYj3vGr8,2552
4
4
  pulp_python/app/cache.py,sha256=Zl2nb4uKyPYp5a3FBrdRZ_-cXfofNMQmIRaQ6dUZZ1g,1037
5
5
  pulp_python/app/exceptions.py,sha256=mPNcWyuzF0XeOPybm-G6oDKtRqvfj4jyp41iaYqcqkA,1314
6
6
  pulp_python/app/global_access_conditions.py,sha256=MZJtyoVsr-4hRaty6mKDqh3caOHd5UKJjEWLV2crOLs,1080
7
7
  pulp_python/app/modelresource.py,sha256=4SFAdqk6lozi_cZz4uqDIqhqPAZF-7l5jJwPn-xGZFs,1249
8
8
  pulp_python/app/models.py,sha256=EJApErZw2LznTtxRQTEq7X9OcOOhzoDgxl1jMfuOEn4,21116
9
9
  pulp_python/app/osv.py,sha256=-JIJBtVjEn-KE2qcmVuWCMAhWEGve_uNNxKjccmQwFw,1406
10
- pulp_python/app/provenance.py,sha256=iyhkuNahHiTDK0Djrd4-PlgErA5SJVI0uQOIPj46tEI,2352
10
+ pulp_python/app/provenance.py,sha256=tOJD4gbPsEkyPaNW7-R6p1YIEGU_SUpVxwxEAWIvQnc,8248
11
11
  pulp_python/app/replica.py,sha256=qiWRP7tM_v4yP_XLIQfumfGolru-Jt6ZA0KVb-9g2cA,1882
12
12
  pulp_python/app/serializers.py,sha256=RKWnTq8uuC_Y9RlPljvqfnYaMYk7dw1PLn3IQe7SGQg,35343
13
- pulp_python/app/settings.py,sha256=Cyc_p6U0HQjKpyrRL6JFrK3R7RMQJ9MAgNMJCfzPEiA,255
13
+ pulp_python/app/settings.py,sha256=1tFHJPcoz_YWZ4tXj6qahERzaxOtkTz_YEE9fB0if14,291
14
14
  pulp_python/app/urls.py,sha256=szPHGWrxaWwMZ0QEsftAyFwisEMFfusfDS4lcYEt4nU,2064
15
- pulp_python/app/utils.py,sha256=rQdKK1jXNwMcHIa4uUpwV4FZoxBi-kbeaJHmBotHp3U,28593
15
+ pulp_python/app/utils.py,sha256=6687eWsPp4xXTrcOPaD2nGDdvEf1P9J97y3HwD97Ams,28672
16
16
  pulp_python/app/viewsets.py,sha256=hFgp-tNM9N3doty1pX-hndZgHarLDtOISqRW5KuAVgA,36154
17
17
  pulp_python/app/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
18
  pulp_python/app/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -46,7 +46,7 @@ pulp_python/app/migrations/0025_pythonremote_vulnerabilities.py,sha256=IinhUzV3P
46
46
  pulp_python/app/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
47
47
  pulp_python/app/pypi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
48
48
  pulp_python/app/pypi/feeds.py,sha256=bzc_VWJmnNC-GkdC2iWYIQVL-K5hUEa19f5WYidaNS0,9864
49
- pulp_python/app/pypi/serializers.py,sha256=MgHHprb9xIorjfn0byXpuzRjRuxd9bmKcQpF4vvYFzY,5732
49
+ pulp_python/app/pypi/serializers.py,sha256=NDFogWCK5K-fQ02mXMfWqFl32fWbm-8HSjX21lcUNV4,6457
50
50
  pulp_python/app/pypi/views.py,sha256=tKGDlsbjv4ni1cFXxOgqqDbeJJBou03MAcvzzarPp2Y,27435
51
51
  pulp_python/app/tasks/__init__.py,sha256=tfVSAlgIDvKGgmimCBmSVJXOyLRUGRU6UuqqE6sxWnQ,361
52
52
  pulp_python/app/tasks/publish.py,sha256=zrAZCs7sAs11oZ0RdvYSQBEgnOkucYisEnFK1XjvWzY,4541
@@ -74,6 +74,7 @@ pulp_python/tests/functional/api/test_domains.py,sha256=JtgQq1HwIm2rLCy3ZEq9voBL
74
74
  pulp_python/tests/functional/api/test_download_content.py,sha256=L_Q1TFg98Oe-i4iM9vsc1utnzCeHSNn4BE4a15VAk38,4939
75
75
  pulp_python/tests/functional/api/test_export_import.py,sha256=rHns9wdaeP-vtfW_qoGHU9EVuJ4YuWE0-rjl_8otAgU,4530
76
76
  pulp_python/tests/functional/api/test_full_mirror.py,sha256=v0nSlGKGSycFqZM4opCTHVtbmCfo_Y5y3k_6Rm7eBF8,12058
77
+ pulp_python/tests/functional/api/test_key_signed_attestations.py,sha256=zOX3QDDd_Mi7i9k2jxH1HpOcp8IXSYLlHyA5cvEhJyM,13373
77
78
  pulp_python/tests/functional/api/test_pypi_apis.py,sha256=UZ87mFEQYm7WWKBQQYYFVxtfRTi7prH6hEKoeqwQvPc,13757
78
79
  pulp_python/tests/functional/api/test_pypi_feeds.py,sha256=nK0MbpqIlPDQtfZeWyqDc8mKN9qJeWLRQeo0S5wo5GY,9475
79
80
  pulp_python/tests/functional/api/test_pypi_json_vulnerabilities.py,sha256=uSH2-EflYir85rzG4fjp43x1vw-CBinA5sJ4irzI4I8,5836
@@ -89,10 +90,11 @@ pulp_python/tests/functional/api/test_yank.py,sha256=qyZbAJ6bJO-4LPkVfVxKuWFjypJ
89
90
  pulp_python/tests/unit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
90
91
  pulp_python/tests/unit/test_feeds.py,sha256=EKrBBHPfrfUozckWcG9zJQSGJuU2uToofZzfC6oKT64,1400
91
92
  pulp_python/tests/unit/test_models.py,sha256=TBI0yKsrdbnJSPeBFfxSqhXK7zaNvR6qg5JehGH3Pds,229
93
+ pulp_python/tests/unit/test_simple_templates.py,sha256=ldiX2qJF-LUNkzb8WN2y2EOsgtgIelcFGfKdeGTfEmQ,1989
92
94
  pulp_python/tests/unit/test_vulnerabilities.py,sha256=mdAbc2scATqWLwnVnLTdOCF76wiFWqcPp_xORUY6drY,2590
93
- pulp_python-3.37.1.dist-info/licenses/LICENSE,sha256=2ylvL381vKOhdO-w6zkrOxe9lLNBhRQpo9_0EbHC_HM,18046
94
- pulp_python-3.37.1.dist-info/METADATA,sha256=TvZtZX0mt2avFbIo2Vfqgoj6hVwy-r2DLwOmN2iQZ5o,1693
95
- pulp_python-3.37.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
96
- pulp_python-3.37.1.dist-info/entry_points.txt,sha256=HvqLEXjw_dS5jqAwnE5JiRZFE6f-y5SRtitKLPml2To,115
97
- pulp_python-3.37.1.dist-info/top_level.txt,sha256=X0hXgXc_bpbiKqVrkt8jD5_QEiQviKbHDwveQcOcJjo,12
98
- pulp_python-3.37.1.dist-info/RECORD,,
95
+ pulp_python-3.38.0.dist-info/licenses/LICENSE,sha256=2ylvL381vKOhdO-w6zkrOxe9lLNBhRQpo9_0EbHC_HM,18046
96
+ pulp_python-3.38.0.dist-info/METADATA,sha256=6KRYnXfaJ4_TgXeZjEpVYwoDaInElApFNdEmo2CJlSo,1693
97
+ pulp_python-3.38.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
98
+ pulp_python-3.38.0.dist-info/entry_points.txt,sha256=HvqLEXjw_dS5jqAwnE5JiRZFE6f-y5SRtitKLPml2To,115
99
+ pulp_python-3.38.0.dist-info/top_level.txt,sha256=X0hXgXc_bpbiKqVrkt8jD5_QEiQviKbHDwveQcOcJjo,12
100
+ pulp_python-3.38.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5