import importlib.util from pathlib import Path from datetime import datetime,timedelta,timezone from unittest.mock import patch import pytest from cryptography import x509 from cryptography.hazmat.primitives import hashes,serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.x509.oid import NameOID spec=importlib.util.spec_from_file_location('metadata',Path(__file__).parents[1]/'tools/public-tls-metadata.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) @pytest.fixture def cert(tmp_path): key=rsa.generate_private_key(public_exponent=65537,key_size=2048);name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'synthetic.invalid')]);now=datetime.now(timezone.utc) cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()).serial_number(1).not_valid_before(now-timedelta(minutes=1)).not_valid_after(now+timedelta(hours=1)).add_extension(x509.SubjectAlternativeName([x509.DNSName('synthetic.invalid')]),critical=False).sign(key,hashes.SHA256())) p=tmp_path/'public.pem';p.write_bytes(cert.public_bytes(serialization.Encoding.PEM));return p def test_public_only_metadata_and_hashes(cert): result=m.describe(cert,cert) assert result['leaf_dns_sans']==['synthetic.invalid'];assert result['network_contacted'] is False assert '-----BEGIN' not in str(result) def test_mixed_or_private_pem_is_refused(cert): cert.write_bytes(cert.read_bytes()+b'\n-----BEGIN PRIVATE KEY-----\nsynthetic\n-----END PRIVATE KEY-----') with pytest.raises(ValueError):m.public_bundle(cert) def test_oversize_is_refused_before_read(cert): with patch.object(m,'LIMIT',1),patch.object(m.os,'open') as opened: with pytest.raises(ValueError):m.public_bundle(cert) opened.assert_not_called() def test_symlink_refused(cert): link=cert.with_name('link.pem');link.symlink_to(cert) with pytest.raises(ValueError):m.public_bundle(link)