|
| 1 | +# This file is part of django-ca (https://github.com/mathiasertl/django-ca). |
| 2 | +# |
| 3 | +# django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU General |
| 4 | +# Public License as published by the Free Software Foundation, either version 3 of the License, or (at your |
| 5 | +# option) any later version. |
| 6 | +# |
| 7 | +# django-ca is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the |
| 8 | +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
| 9 | +# for more details. |
| 10 | +# |
| 11 | +# You should have received a copy of the GNU General Public License along with django-ca. If not, see |
| 12 | +# <http://www.gnu.org/licenses/>. |
| 13 | + |
| 14 | +# pylint: disable=redefined-outer-name # because of fixtures |
| 15 | +# pylint: disable=invalid-name # for model loading |
| 16 | + |
| 17 | +"""Test 0051 database migration.""" |
| 18 | + |
| 19 | +import logging |
| 20 | +import shutil |
| 21 | +from datetime import timedelta |
| 22 | +from pathlib import Path |
| 23 | +from typing import Any, Callable, Optional |
| 24 | + |
| 25 | +from django_test_migrations.migrator import Migrator |
| 26 | + |
| 27 | +from cryptography import x509 |
| 28 | +from cryptography.hazmat.primitives.serialization import Encoding |
| 29 | + |
| 30 | +from django.db.migrations.state import ProjectState |
| 31 | +from django.utils import timezone |
| 32 | + |
| 33 | +import pytest |
| 34 | +from _pytest.logging import LogCaptureFixture |
| 35 | +from pytest_django.fixtures import SettingsWrapper |
| 36 | + |
| 37 | +from django_ca.tests.base.constants import CERT_DATA, FIXTURES_DIR |
| 38 | + |
| 39 | + |
| 40 | +@pytest.fixture(scope="session") |
| 41 | +def ocsp_pem() -> str: |
| 42 | + """Fixture for a PEM certificate.""" |
| 43 | + with open(FIXTURES_DIR / "profile-ocsp.pub", "rb") as stream: |
| 44 | + public_key_data = stream.read() |
| 45 | + public_key = x509.load_der_x509_certificate(public_key_data) |
| 46 | + public_key_data = public_key.public_bytes(Encoding.PEM) |
| 47 | + return public_key_data.decode() |
| 48 | + |
| 49 | + |
| 50 | +def setup(migrator: Migrator, setup: Optional[Callable[[ProjectState], None]] = None) -> ProjectState: |
| 51 | + """Set up a CA with a CRL Number for the given scope.""" |
| 52 | + old_state = migrator.apply_initial_migration(("django_ca", "0049_remove_certificateauthority_crl_number")) |
| 53 | + now = timezone.now() |
| 54 | + |
| 55 | + cert: x509.Certificate = CERT_DATA["root"]["pub"]["parsed"] |
| 56 | + CertificateAuthority = old_state.apps.get_model("django_ca", "CertificateAuthority") |
| 57 | + ca = CertificateAuthority.objects.create( |
| 58 | + pub=cert, |
| 59 | + cn="", |
| 60 | + serial="123", |
| 61 | + not_before=now - timedelta(days=1), |
| 62 | + not_after=now + timedelta(days=1), |
| 63 | + ) |
| 64 | + |
| 65 | + if setup is not None: |
| 66 | + setup(ca) |
| 67 | + |
| 68 | + return migrator.apply_tested_migration(("django_ca", "0051_auto_20241201_2038")) |
| 69 | + |
| 70 | + |
| 71 | +@pytest.mark.usefixtures("tmpcadir") |
| 72 | +def test_normal_migration( |
| 73 | + caplog: LogCaptureFixture, migrator: Migrator, tmpcadir: Path, ocsp_pem: str |
| 74 | +) -> None: |
| 75 | + """Test running the migration with an empty cache.""" |
| 76 | + ocsp_dest = tmpcadir / "ocsp" |
| 77 | + ocsp_dest.mkdir(exist_ok=True, parents=True) |
| 78 | + |
| 79 | + def setup_ocsp_keys(ca: Any) -> None: |
| 80 | + shutil.copy(FIXTURES_DIR / "profile-ocsp.key", ocsp_dest / f"{ca.serial}.key") |
| 81 | + shutil.copy(FIXTURES_DIR / "profile-ocsp.pub", ocsp_dest / f"{ca.serial}.pem") |
| 82 | + |
| 83 | + state = setup(migrator, setup=setup_ocsp_keys) |
| 84 | + |
| 85 | + CertificateAuthority = state.apps.get_model("django_ca", "CertificateAuthority") |
| 86 | + ca = CertificateAuthority.objects.get(serial="123") |
| 87 | + |
| 88 | + assert ca.ocsp_key_backend_options == { |
| 89 | + "certificate": {"pem": ocsp_pem}, |
| 90 | + "private_key": {"path": "ocsp/123.key"}, |
| 91 | + } |
| 92 | + assert caplog.record_tuples == [] |
| 93 | + |
| 94 | + |
| 95 | +@pytest.mark.usefixtures("tmpcadir") |
| 96 | +def test_with_pem_public_key( |
| 97 | + caplog: LogCaptureFixture, migrator: Migrator, tmpcadir: Path, ocsp_pem: str |
| 98 | +) -> None: |
| 99 | + """Test running the migration with a PEM public key.""" |
| 100 | + ocsp_dest = tmpcadir / "ocsp" |
| 101 | + ocsp_dest.mkdir(exist_ok=True, parents=True) |
| 102 | + |
| 103 | + def setup_ocsp_keys(ca: Any) -> None: |
| 104 | + shutil.copy(FIXTURES_DIR / "profile-ocsp.key", ocsp_dest / f"{ca.serial}.key") |
| 105 | + with open(ocsp_dest / f"{ca.serial}.pem", "w", encoding="ascii") as stream: |
| 106 | + stream.write(ocsp_pem) |
| 107 | + |
| 108 | + state = setup(migrator, setup=setup_ocsp_keys) |
| 109 | + |
| 110 | + CertificateAuthority = state.apps.get_model("django_ca", "CertificateAuthority") |
| 111 | + ca = CertificateAuthority.objects.get(serial="123") |
| 112 | + assert caplog.record_tuples == [] |
| 113 | + assert ca.ocsp_key_backend_options == { |
| 114 | + "certificate": {"pem": ocsp_pem}, |
| 115 | + "private_key": {"path": "ocsp/123.key"}, |
| 116 | + } |
| 117 | + |
| 118 | + |
| 119 | +@pytest.mark.usefixtures("tmpcadir") |
| 120 | +def test_ocsp_keys_dont_exist(caplog: LogCaptureFixture, migrator: Migrator) -> None: |
| 121 | + """Test running the migration where no OCSP key was generated.""" |
| 122 | + state = setup(migrator) |
| 123 | + CertificateAuthority = state.apps.get_model("django_ca", "CertificateAuthority") |
| 124 | + ca = CertificateAuthority.objects.get(serial="123") |
| 125 | + assert ca.ocsp_key_backend_options == {"certificate": {}, "private_key": {}} |
| 126 | + assert caplog.record_tuples == [ |
| 127 | + ( |
| 128 | + "django_ca.migrations.0051_auto_20241201_2038", |
| 129 | + logging.WARNING, |
| 130 | + "Private or public key not found. Regenerate OCSP keys manually.", |
| 131 | + ) |
| 132 | + ] |
| 133 | + |
| 134 | + |
| 135 | +@pytest.mark.usefixtures("tmpcadir") |
| 136 | +def test_with_bogus_public_key(caplog: LogCaptureFixture, migrator: Migrator, tmpcadir: Path) -> None: |
| 137 | + """Test running the migration with a bogus public key.""" |
| 138 | + ocsp_dest = tmpcadir / "ocsp" |
| 139 | + ocsp_dest.mkdir(exist_ok=True, parents=True) |
| 140 | + |
| 141 | + def setup_ocsp_keys(ca: Any) -> None: |
| 142 | + shutil.copy(FIXTURES_DIR / "profile-ocsp.key", ocsp_dest / f"{ca.serial}.key") |
| 143 | + with open(ocsp_dest / f"{ca.serial}.pem", "w", encoding="ascii") as stream: |
| 144 | + stream.write("foobar") |
| 145 | + |
| 146 | + state = setup(migrator, setup=setup_ocsp_keys) |
| 147 | + |
| 148 | + CertificateAuthority = state.apps.get_model("django_ca", "CertificateAuthority") |
| 149 | + ca = CertificateAuthority.objects.get(serial="123") |
| 150 | + assert caplog.record_tuples == [ |
| 151 | + ( |
| 152 | + "django_ca.migrations.0051_auto_20241201_2038", |
| 153 | + logging.WARNING, |
| 154 | + "ocsp/123.pem: Cannot encode certificate. Regenerate OCSP keys manually.", |
| 155 | + ) |
| 156 | + ] |
| 157 | + assert ca.ocsp_key_backend_options == {"certificate": {}, "private_key": {}} |
| 158 | + |
| 159 | + |
| 160 | +@pytest.mark.usefixtures("tmpcadir") |
| 161 | +def test_with_invalid_storage_alias( |
| 162 | + caplog: LogCaptureFixture, migrator: Migrator, tmpcadir: Path, settings: SettingsWrapper |
| 163 | +) -> None: |
| 164 | + """Test running the migration with an improperly configured ocsp alias.""" |
| 165 | + ocsp_dest = tmpcadir / "ocsp" |
| 166 | + ocsp_dest.mkdir(exist_ok=True, parents=True) |
| 167 | + |
| 168 | + settings.CA_OCSP_KEY_BACKENDS = { |
| 169 | + "default": { |
| 170 | + "BACKEND": "django_ca.key_backends.storages.StoragesOCSPBackend", |
| 171 | + "OPTIONS": {"storage_alias": "foobar"}, |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + state = setup(migrator) |
| 176 | + |
| 177 | + CertificateAuthority = state.apps.get_model("django_ca", "CertificateAuthority") |
| 178 | + ca = CertificateAuthority.objects.get(serial="123") |
| 179 | + assert "Cannot load OCSP key storage backend." in caplog.text |
| 180 | + assert ca.ocsp_key_backend_options == {"certificate": {}, "private_key": {}} |
0 commit comments