from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import ec

from aliro_harness.issuer.ca import create_self_signed_ca


def test_create_self_signed_ca_returns_p256_cert_and_key():
    cert, key = create_self_signed_ca(common_name="Test Credential Issuer CA")

    assert isinstance(cert, x509.Certificate)
    assert isinstance(key, ec.EllipticCurvePrivateKey)
    assert key.curve.name == "secp256r1"


def test_self_signed_ca_subject_and_issuer_match():
    cert, _ = create_self_signed_ca(common_name="Test Credential Issuer CA")

    assert cert.subject == cert.issuer
    cn = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value
    assert cn == "Test Credential Issuer CA"


def test_self_signed_ca_has_ca_basic_constraints():
    cert, _ = create_self_signed_ca(common_name="Test CA")

    bc = cert.extensions.get_extension_for_class(x509.BasicConstraints)
    assert bc.value.ca is True
    assert bc.critical is True


def test_self_signed_ca_signature_verifies_with_own_key():
    cert, key = create_self_signed_ca(common_name="Test CA")

    public_key = key.public_key()
    public_key.verify(
        cert.signature,
        cert.tbs_certificate_bytes,
        ec.ECDSA(cert.signature_hash_algorithm),
    )
