Skip to content

Commit d0254fa

Browse files
committed
Support embedded public key
1 parent 3fd64a0 commit d0254fa

2 files changed

Lines changed: 176 additions & 17 deletions

File tree

‎pulp_python/app/provenance.py‎

Lines changed: 65 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,16 @@
88
from cryptography.hazmat.primitives.asymmetric import padding as crypto_padding
99
from cryptography.x509 import load_der_x509_certificate
1010
from django.conf import settings
11-
from pydantic import BaseModel, ConfigDict, Field
11+
from pydantic import Base64Bytes, BaseModel, ConfigDict, Field, model_validator
1212
from pydantic.alias_generators import to_snake
1313
from pypi_attestations import Attestation as _UpstreamAttestation
1414
from pypi_attestations import (
1515
Distribution,
1616
Envelope, # noqa - needed in module namespace for Pydantic model rebuild
1717
Publisher,
1818
VerificationError,
19-
VerificationMaterial,
2019
)
20+
from pypi_attestations import VerificationMaterial as _UpstreamVerificationMaterial
2121
from sigstore.dsse import Envelope as DSSEEnvelope
2222
from sigstore.dsse import _pae
2323

@@ -58,6 +58,29 @@ def _as_policy(self):
5858
ExtendedPublisher = Annotated[_ExtendedPublisherUnion, Field(union_mode="left_to_right")]
5959

6060

61+
class VerificationMaterial(_UpstreamVerificationMaterial):
62+
"""Extended verification material that supports optional certificate and public key.
63+
64+
PEP 740 requires a certificate, but this extension allows attestations signed
65+
with a custom key where the certificate is absent. The public_key field is
66+
accepted as an extra field and only present in the output when provided.
67+
"""
68+
69+
model_config = ConfigDict(extra="allow")
70+
71+
certificate: Base64Bytes | None = None
72+
73+
@model_validator(mode="after")
74+
def _validate_fields(self):
75+
unexpected = set(self.model_extra or {}) - {"public_key"}
76+
if unexpected:
77+
raise ValueError(f"unexpected fields in verification_material: {unexpected}")
78+
public_key = getattr(self, "public_key", None)
79+
if self.certificate is not None and public_key is not None:
80+
raise ValueError("verification_material cannot contain both certificate and public_key")
81+
return self
82+
83+
6184
class Attestation(_UpstreamAttestation):
6285
"""
6386
Attestation object as defined in PEP 740.
@@ -110,6 +133,8 @@ def _has_valid_certificate(attestation):
110133
if vm is None:
111134
return False
112135
cert_bytes = vm.certificate
136+
if cert_bytes is None:
137+
return False
113138
load_der_x509_certificate(cert_bytes)
114139
return True
115140
except (ValueError, Exception):
@@ -180,14 +205,38 @@ def _verify_signature(attestation, public_key):
180205
raise VerificationError(f"signature verification failed: {e}")
181206

182207

208+
def _verify_embedded_key(attestation, server_key):
209+
"""Verify that the embedded public key matches the server-configured key."""
210+
vm = attestation.verification_material
211+
public_key = getattr(vm, "public_key", None) if vm else None
212+
if public_key is None:
213+
return
214+
try:
215+
embedded_key = serialization.load_pem_public_key(public_key.encode())
216+
except (ValueError, Exception) as e:
217+
raise VerificationError(f"invalid embedded public key: {e}")
218+
server_key_bytes = server_key.public_bytes(
219+
serialization.Encoding.PEM,
220+
serialization.PublicFormat.SubjectPublicKeyInfo,
221+
)
222+
embedded_key_bytes = embedded_key.public_bytes(
223+
serialization.Encoding.PEM,
224+
serialization.PublicFormat.SubjectPublicKeyInfo,
225+
)
226+
if server_key_bytes != embedded_key_bytes:
227+
raise VerificationError(
228+
"embedded public key does not match server-configured ATTESTATION_VERIFICATION_KEY"
229+
)
230+
231+
183232
def verify_provenance(filename, sha256, provenance, offline=True):
184233
"""Verify the provenance object is valid for the package.
185234
186-
Attestations with valid Sigstore certificates are verified through the
187-
standard Sigstore path. Attestations without certificates are verified
188-
against a custom public key configured via ATTESTATION_VERIFICATION_KEY.
189-
Currently, it supports RSA PKCS1v15 signatures and SLSA v0.2 provenance
190-
publisher enrichment.
235+
Each attestation is routed to one of two coexisting verification paths:
236+
1. Attestations with a valid Sigstore certificate follow the standard PEP 740 path.
237+
2. Attestations without a certificate are verified against the server-configured
238+
ATTESTATION_VERIFICATION_KEY using RSA PKCS1v15 signatures, with support for SLSA
239+
v0.2 publisher enrichment and optional embedded public key in verification_material.
191240
"""
192241
dist = Distribution(name=filename, digest=sha256)
193242
verification_key = _load_verification_key()
@@ -200,13 +249,14 @@ def verify_provenance(filename, sha256, provenance, offline=True):
200249
checkpoint = sig_bundle.log_entry._inner.inclusion_proof.checkpoint
201250
staging = "sigstage.dev" in checkpoint.envelope
202251
attestation.verify(policy, dist, staging=staging, offline=offline)
203-
else:
252+
elif verification_key:
204253
stmt = _verify_statement_subject(attestation, dist)
205254
_enrich_publisher_from_statement(stmt, publisher)
206-
if verification_key:
207-
_verify_signature(attestation, verification_key)
208-
else:
209-
raise VerificationError(
210-
"Attestation has no Sigstore certificate and no custom "
211-
"verification key is configured (ATTESTATION_VERIFICATION_KEY)"
212-
)
255+
_verify_signature(attestation, verification_key)
256+
_verify_embedded_key(attestation, verification_key)
257+
else:
258+
raise VerificationError(
259+
"Attestation has no Sigstore certificate and no custom "
260+
"verification key configured via ATTESTATION_VERIFICATION_KEY "
261+
"(embedded key in verification_material is optional)"
262+
)

‎pulp_python/tests/functional/api/test_slsa_attestations.py‎

Lines changed: 111 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,11 @@ def _b64(data: bytes) -> str:
6767
return base64.b64encode(data).decode()
6868

6969

70-
def _make_attestation(statement_bytes, signature_bytes):
70+
def _make_attestation(statement_bytes, signature_bytes, verification_material=None):
7171
"""Return a single PEP-740 Attestation dict (SLSA flavour)."""
7272
return {
7373
"version": 1,
74-
"verification_material": None,
74+
"verification_material": verification_material,
7575
"envelope": {
7676
"statement": _b64(statement_bytes),
7777
"signature": _b64(signature_bytes),
@@ -92,6 +92,21 @@ def _make_provenance(attestation):
9292
}
9393

9494

95+
def _read_public_key_pem():
96+
"""Read the test public key as a PEM string."""
97+
with open(TEST_PUBLIC_KEY_PATH) as f:
98+
return f.read()
99+
100+
101+
def _make_embedded_key_material(public_key_pem):
102+
"""Build a verification_material dict with an embedded public key."""
103+
return {
104+
"certificate": None,
105+
"public_key": public_key_pem,
106+
"transparency_entries": [{"log_index": 0}],
107+
}
108+
109+
95110
# ---------------------------------------------------------------------------
96111
# Fixtures
97112
# ---------------------------------------------------------------------------
@@ -245,3 +260,97 @@ def test_slsa_attestation_via_content_upload(
245260
assert publisher["builder_id"] == "https://konflux-ci.dev/calunga"
246261
assert publisher["build_type"] == "https://konflux-ci.dev/PythonWheelBuild@v1"
247262
assert publisher["kind"] == "konflux-ci.dev"
263+
264+
265+
def test_slsa_embedded_key_accepted(
266+
python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
267+
):
268+
"""An attestation with an embedded public key matching the server key is accepted."""
269+
content = python_content_factory()
270+
271+
stmt = _build_statement(content.filename, content.sha256)
272+
sig = _sign(stmt, test_private_key)
273+
vm = _make_embedded_key_material(_read_public_key_pem())
274+
att = _make_attestation(stmt, sig, verification_material=vm)
275+
prov = _make_provenance(att)
276+
277+
task = python_bindings.ContentProvenanceApi.create(
278+
package=content.pulp_href,
279+
file=_provenance_file(prov),
280+
verify=True,
281+
).task
282+
result = monitor_task(task)
283+
284+
prov_obj = python_bindings.ContentProvenanceApi.read(result.created_resources[-1])
285+
assert prov_obj.package == content.pulp_href
286+
stored_vm = prov_obj.provenance["attestation_bundles"][0]["attestations"][0][
287+
"verification_material"
288+
]
289+
assert stored_vm["public_key"] == _read_public_key_pem()
290+
291+
292+
def test_slsa_embedded_key_mismatch_rejected(
293+
python_bindings, python_content_factory, monitor_task, test_private_key, _provenance_file
294+
):
295+
"""An attestation with an embedded key that does not match the server key is rejected."""
296+
content = python_content_factory()
297+
298+
stmt = _build_statement(content.filename, content.sha256)
299+
sig = _sign(stmt, test_private_key)
300+
wrong_key = (
301+
"-----BEGIN PUBLIC KEY-----\n"
302+
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArvxtuKOCCHGNd6agbC4b\n"
303+
"zX9S7qMnMRdz9bxxzkPf9a4T75St3EcrNQYxLqzcDBfeiiLa1wXQoraqFSGkvqX+\n"
304+
"YDFmtYRgnXEujUwYqHQBYrKtrQHxrQ2J3V1e+PqhJ4HCQq/uRZdx6KJ5DOlpYuJM\n"
305+
"aL2m7IozNJJkgjQH1frmDfM5/GuPVbgwN0QDnC0oSzNJFKtdVMD3SPnQGMPQ9qxf\n"
306+
"DiTZOk1tO3VD/xXoNJ6Zgf0D5RvGyLAfLflgojKImHezgpdE6iQyZAVU2ShKMq3M\n"
307+
"K+XtX39/ajXHJ1FCLXlRFoNoHltWioyvkmXHbhb9OxGncB+x6idSjgp7AR5y15HN\n"
308+
"DwIDAQAB\n"
309+
"-----END PUBLIC KEY-----\n"
310+
)
311+
vm = _make_embedded_key_material(wrong_key)
312+
att = _make_attestation(stmt, sig, verification_material=vm)
313+
prov = _make_provenance(att)
314+
315+
task = python_bindings.ContentProvenanceApi.create(
316+
package=content.pulp_href,
317+
file=_provenance_file(prov),
318+
verify=True,
319+
).task
320+
with pytest.raises(PulpTaskError) as exc_info:
321+
monitor_task(task)
322+
err_msg = "embedded public key does not match server-configured ATTESTATION_VERIFICATION_KEY"
323+
assert err_msg in exc_info.value.task.error["description"]
324+
325+
326+
def test_slsa_certificate_and_public_key_rejected(
327+
python_bindings, python_content_factory, test_private_key
328+
):
329+
"""An attestation with both certificate and public_key is rejected."""
330+
content = python_content_factory()
331+
332+
stmt = _build_statement(content.filename, content.sha256)
333+
sig = _sign(stmt, test_private_key)
334+
att = {
335+
"version": 1,
336+
"verification_material": {
337+
"certificate": _b64(b"fake-cert"),
338+
"public_key": _read_public_key_pem(),
339+
"transparency_entries": [{"log_index": 0}],
340+
},
341+
"envelope": {
342+
"statement": _b64(stmt),
343+
"signature": _b64(sig),
344+
},
345+
}
346+
body = {
347+
"artifact": content.artifact,
348+
"relative_path": content.filename,
349+
"sha256": content.sha256,
350+
"attestations": json.dumps([att]),
351+
}
352+
with pytest.raises(python_bindings.ApiException) as exc_info:
353+
python_bindings.ContentPackagesApi.create(**body)
354+
err_msg = "verification_material cannot contain both certificate and public_key"
355+
assert err_msg in exc_info.value.body
356+
assert exc_info.value.status == 400

0 commit comments

Comments
 (0)