feat: add certificate management with expiration reminders

Add a Certificate model alongside software licenses with type, common
name, SANs, issuer, serial number, fingerprint, validity period, auto
renewal, certificate file and storage locations. Certificates can be
assigned to software products, installations, devices, virtual machines
and tenants.

Extract the expiration reminder settings and logic into a shared
ExpirationNotificationModel base and a generic notification job, so
certificates get the same default/custom reminders, NetBox notifications
and optional SMTP emails as licenses (separate event type, log model and
email permission).

Includes UI views, filters, table, bulk import/edit, REST API endpoint,
migration 0015, German translations, tests and README/CHANGELOG updates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-21 14:02:53 +02:00
1 parent 32d62f26b2
commit 02d965a77b
22 files changed
+1547 -102

No files matched your search

+3
View File
@@ -12,6 +12,9 @@
### Added
* Certificate management with type, common name, SANs, issuer, serial number, fingerprint and validity period
* Optional certificate assignment to software products, installations, devices, virtual machines and tenants
* Daily certificate expiration notifications with the same reminder and email options as licenses
* Optional tenant group and tenant assignments for software licenses
* German translation for navigation, forms, tables, detail views, choices, and validation messages
* Optional lifetime or recurring renewal interval for licenses
+55 -4
View File
@@ -1,6 +1,7 @@
# NetBox SLM
NetBox SLM erweitert NetBox um die Verwaltung von Softwareprodukten, Versionen, Installationen und Lizenzen.
NetBox SLM erweitert NetBox um die Verwaltung von Softwareprodukten, Versionen, Installationen, Lizenzen und
Zertifikaten.
Lizenzen können optional einer NetBox-Mandantengruppe und einem Mandanten zugeordnet werden.
Diese Variante ist für **NetBox 4.6.5** vorgesehen.
@@ -20,6 +21,9 @@ Benutzer ausgewählten Sprache.
- Zusätzliche eigene Vorwarnzeit in Tagen, Wochen oder Monaten
- NetBox-Benachrichtigungen und optionaler E-Mail-Versand über die NetBox-SMTP-Konfiguration
- Lizenzen Mandantengruppen und Mandanten zuordnen
- Zertifikate mit Common Name, SANs, Aussteller, Seriennummer, Fingerabdruck und Gültigkeitszeitraum verwalten
- Zertifikate Softwareprodukten, Installationen, Geräten, virtuellen Maschinen und Mandanten zuordnen
- Zertifikatsdateien und Ablageorte hinterlegen (keine privaten Schlüssel)
- Bedienung über die NetBox-Oberfläche und REST-API
- Filter, Bulk-Import und Bulk-Bearbeitung
@@ -70,7 +74,8 @@ Für diese Variante muss dort mindestens Version `1.12.0` stehen.
## Ablaufbenachrichtigungen
Für Lizenzen mit Ablaufdatum sind Benachrichtigungen standardmäßig aktiviert. Die Standardtermine liegen einen
Für Lizenzen und Zertifikate mit Ablaufdatum sind Benachrichtigungen standardmäßig aktiviert. Beide Objekttypen
verwenden dieselben Einstellungen; die folgenden Abschnitte gelten daher für Zertifikate entsprechend. Die Standardtermine liegen einen
Monat und eine Woche vor dem Ablaufdatum. Pro Lizenz kann zusätzlich eine eigene Vorwarnzeit festgelegt oder die
Standardtermine deaktiviert werden.
@@ -83,10 +88,11 @@ das Plugin auch eine E-Mail an die im Benutzerkonto hinterlegte Adresse. Dafür
konfiguriert sein.
Die Aktivierung des E-Mail-Versands darf nur durch Administratoren oder Benutzer mit der Berechtigung
`netbox_slm.manage_softwarelicense_email_notifications` geändert werden. Die eigentlichen SMTP-Zugangsdaten werden
`netbox_slm.manage_softwarelicense_email_notifications` (Lizenzen) bzw.
`netbox_slm.manage_certificate_email_notifications` (Zertifikate) geändert werden. Die eigentlichen SMTP-Zugangsdaten werden
ausschließlich in der NetBox-Serverkonfiguration gepflegt und sind im Plugin nicht einsehbar.
Die Prüfung läuft einmal täglich als NetBox-Systemjob. Sobald der erste konfigurierte Erinnerungstermin erreicht ist,
Die Prüfung läuft einmal täglich als NetBox-Systemjob (je ein Job für Lizenzen und Zertifikate). Sobald der erste konfigurierte Erinnerungstermin erreicht ist,
werden die Abonnenten bei jedem Joblauf erneut informiert: immer über NetBox und bei aktivierter E-Mail-Option
zusätzlich per SMTP. Dies wird bis einschließlich des Ablaufdatums wiederholt. Der NetBox-RQ-Worker muss dafür mit
Scheduler-Unterstützung laufen; dies ist bei der regulären NetBox-Installation mit `rqworker` standardmäßig der Fall.
@@ -158,3 +164,48 @@ Die Anpassungen in diesem Fork werden unter
Das Projekt steht unter der [Apache License 2.0](LICENSE). Die Hinweise auf die ursprünglichen Urheber bleiben
erhalten.
## Certificates (English)
In addition to software licenses, NetBox SLM manages certificates (menu **Licences → Certificates**).
### Fields
- Name, description and type (TLS server, TLS client, certificate authority, code signing, S/MIME email, other)
- Common name, subject alternative names (one DNS name or IP address per line), issuer, serial number and SHA-256
fingerprint
- Validity period (valid from / valid until) and an automatic renewal flag
- Certificate file, stored location (with optional URL) and provider portal URL
- Optional assignment to a software product, installation, device, virtual machine, tenant group and tenant
> **Note:** Private keys are intentionally not stored. Keep them in a dedicated secret store and reference that
> location through the stored location fields if needed.
### Expiration notifications
Certificates use the same reminder settings as licenses:
- Reminders are enabled by default one month and one week before the expiration date.
- An additional custom interval in days, weeks or months can be configured, and the default intervals can be disabled.
- Users opt in by opening a certificate and choosing **Subscribe**. Without subscribers no message is sent.
- A NetBox notification is always created. If **Email notifications** is enabled on the certificate, an email is sent
as well via the SMTP settings configured in NetBox.
- Changing the email option requires the permission `netbox_slm.manage_certificate_email_notifications`
(licenses use `netbox_slm.manage_softwarelicense_email_notifications`).
- The check runs once a day as the NetBox system job **Certificate Expiration Notifications**. Once the first reminder
date is reached, subscribers are notified on every run up to and including the expiration date.
### REST API
Certificates are available at `/api/plugins/slm/certificates/` and support filtering, e.g. by `type`, `common_name`,
`issuer`, `device_id`, `virtualmachine_id`, `tenant_id`, `expiration_date__lte` and `expiration_date__gte`.
### Upgrading
The feature adds the migration `0015_certificate`. After upgrading the plugin run:
```bash
cd /opt/netbox/netbox
/opt/netbox/venv/bin/python manage.py migrate
sudo systemctl restart netbox netbox-rq
```
+3 -2
View File
@@ -17,7 +17,7 @@ limitations under the License.
from netbox.plugins import PluginConfig
from django.utils.translation import gettext, gettext_lazy as _
__version__ = "1.13.0"
__version__ = "1.14.0"
class SLMConfig(PluginConfig):
@@ -40,9 +40,10 @@ class SLMConfig(PluginConfig):
super().ready()
from netbox.events import EVENT_TYPE_KIND_WARNING, EventType
from netbox_slm.events import LICENSE_EXPIRING
from netbox_slm.events import CERTIFICATE_EXPIRING, LICENSE_EXPIRING
EventType(LICENSE_EXPIRING, gettext("License expiring"), kind=EVENT_TYPE_KIND_WARNING).register()
EventType(CERTIFICATE_EXPIRING, gettext("Certificate expiring"), kind=EVENT_TYPE_KIND_WARNING).register()
from netbox_slm import jobs # noqa: F401
+95 -1
View File
@@ -3,7 +3,13 @@ from rest_framework.serializers import SerializerMethodField, HyperlinkedIdentit
from django.utils.translation import gettext_lazy as _
from netbox.api.serializers import NetBoxModelSerializer
from netbox_slm.models import SoftwareProduct, SoftwareProductVersion, SoftwareProductInstallation, SoftwareLicense
from netbox_slm.models import (
Certificate,
SoftwareProduct,
SoftwareProductVersion,
SoftwareProductInstallation,
SoftwareLicense,
)
class SoftwareLicenseSerializer(NetBoxModelSerializer):
@@ -185,3 +191,91 @@ class SoftwareProductVersionSerializer(NetBoxModelSerializer):
def get_display(self, obj):
return f"{obj}"
class CertificateSerializer(NetBoxModelSerializer):
display = SerializerMethodField()
url = HyperlinkedIdentityField(view_name="plugins-api:netbox_slm-api:certificate-detail")
class Meta:
model = Certificate
fields = (
"id",
"display",
"url",
"name",
"description",
"type",
"common_name",
"subject_alternative_names",
"issuer",
"serial_number",
"fingerprint",
"start_date",
"expiration_date",
"auto_renewal",
"certificate_file",
"stored_location",
"stored_location_url",
"provider_portal_url",
"expiration_notifications_enabled",
"default_notification_intervals",
"custom_notification_interval",
"custom_notification_interval_unit",
"email_notifications",
"software_product",
"installation",
"device",
"virtualmachine",
"tenant_group",
"tenant",
"tags",
"comments",
"custom_field_data",
"created",
"last_updated",
)
brief_fields = ("id", "display", "url", "name", "description", "expiration_date")
def get_display(self, obj):
return f"{obj}"
def validate(self, attrs):
request = self.context.get("request")
if (
"email_notifications" in attrs
and request is not None
and not request.user.has_perm("netbox_slm.manage_certificate_email_notifications")
):
raise serializers.ValidationError(
{"email_notifications": _("You do not have permission to change email notifications.")}
)
tenant_group = attrs.get("tenant_group", getattr(self.instance, "tenant_group", None))
tenant = attrs.get("tenant", getattr(self.instance, "tenant", None))
if tenant_group and tenant and tenant.group_id != tenant_group.pk:
raise serializers.ValidationError(
{"tenant": _("The selected tenant does not belong to the selected tenant group.")}
)
start_date = attrs.get("start_date", getattr(self.instance, "start_date", None))
expiration_date = attrs.get("expiration_date", getattr(self.instance, "expiration_date", None))
if start_date and expiration_date and start_date > expiration_date:
raise serializers.ValidationError(
{"expiration_date": _("The expiration date must not be before the start date.")}
)
custom_interval = attrs.get(
"custom_notification_interval", getattr(self.instance, "custom_notification_interval", None)
)
custom_interval_unit = attrs.get(
"custom_notification_interval_unit",
getattr(self.instance, "custom_notification_interval_unit", ""),
)
if bool(custom_interval) != bool(custom_interval_unit):
raise serializers.ValidationError(
{
"custom_notification_interval": _(
"Custom notification interval and unit must be specified together."
)
}
)
return attrs
+2
View File
@@ -5,6 +5,7 @@ from netbox_slm.api.views import (
SoftwareProductVersionViewSet,
SoftwareProductInstallationViewSet,
SoftwareLicenseViewSet,
CertificateViewSet,
)
router = NetBoxRouter()
@@ -14,5 +15,6 @@ router.register("softwareproducts", SoftwareProductViewSet)
router.register("softwareproductversions", SoftwareProductVersionViewSet)
router.register("softwareproductinstallations", SoftwareProductInstallationViewSet)
router.register("softwarelicenses", SoftwareLicenseViewSet)
router.register("certificates", CertificateViewSet)
urlpatterns = router.urls
+9
View File
@@ -6,18 +6,21 @@ from netbox_slm.api.serializers import (
SoftwareProductVersionSerializer,
SoftwareProductInstallationSerializer,
SoftwareLicenseSerializer,
CertificateSerializer,
)
from netbox_slm.filtersets import (
SoftwareProductFilterSet,
SoftwareProductVersionFilterSet,
SoftwareProductInstallationFilterSet,
SoftwareLicenseFilterSet,
CertificateFilterSet,
)
from netbox_slm.models import (
SoftwareProduct,
SoftwareProductVersion,
SoftwareProductInstallation,
SoftwareLicense,
Certificate,
)
@@ -48,3 +51,9 @@ class SoftwareLicenseViewSet(NetBoxModelViewSet):
queryset = SoftwareLicense.objects.all().order_by("id")
serializer_class = SoftwareLicenseSerializer
filterset_class = SoftwareLicenseFilterSet
class CertificateViewSet(NetBoxModelViewSet):
queryset = Certificate.objects.all().order_by("id")
serializer_class = CertificateSerializer
filterset_class = CertificateFilterSet
+1
View File
@@ -1 +1,2 @@
LICENSE_EXPIRING = "netbox_slm_license_expiring"
CERTIFICATE_EXPIRING = "netbox_slm_certificate_expiring"
+49 -1
View File
@@ -1,6 +1,6 @@
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from django_filters import CharFilter, ModelMultipleChoiceFilter, MultipleChoiceFilter, NumberFilter
from django_filters import CharFilter, DateFilter, ModelMultipleChoiceFilter, MultipleChoiceFilter, NumberFilter
from dcim.models import Device, Manufacturer
from netbox.filtersets import NetBoxModelFilterSet
@@ -10,6 +10,8 @@ from netbox_slm.models import (
SoftwareProductInstallation,
SoftwareLicense,
SoftwareReleaseTypes,
Certificate,
CertificateTypes,
RenewalIntervalUnits,
)
from virtualization.models import Cluster, VirtualMachine
@@ -151,3 +153,49 @@ class SoftwareLicenseFilterSet(NetBoxModelFilterSet):
| Q(comments__icontains=value)
)
return queryset.filter(qs_filter)
class CertificateFilterSet(NetBoxModelFilterSet):
"""Filter capabilities for Certificate instances."""
name = CharFilter(lookup_expr="icontains")
description = CharFilter(lookup_expr="icontains")
type = MultipleChoiceFilter(choices=CertificateTypes.choices)
common_name = CharFilter(lookup_expr="icontains")
issuer = CharFilter(lookup_expr="icontains")
serial_number = CharFilter(lookup_expr="icontains")
expiration_date__lte = DateFilter(field_name="expiration_date", lookup_expr="lte")
expiration_date__gte = DateFilter(field_name="expiration_date", lookup_expr="gte")
software_product_id = ModelMultipleChoiceFilter(
queryset=SoftwareProduct.objects.all(),
label=_("Software Product"),
)
installation_id = ModelMultipleChoiceFilter(queryset=SoftwareProductInstallation.objects.all())
device_id = ModelMultipleChoiceFilter(queryset=Device.objects.all())
virtualmachine_id = ModelMultipleChoiceFilter(queryset=VirtualMachine.objects.all(), label=_("Virtual Machine"))
tenant_group_id = ModelMultipleChoiceFilter(queryset=TenantGroup.objects.all(), label=_("Tenant Group"))
tenant_id = ModelMultipleChoiceFilter(queryset=Tenant.objects.all(), label=_("Tenant"))
class Meta:
model = Certificate
fields = ("auto_renewal", "expiration_notifications_enabled", "email_notifications")
def search(self, queryset, name, value):
"""Perform the filtered search."""
if not value.strip():
return queryset
qs_filter = (
Q(name__icontains=value)
| Q(description__icontains=value)
| Q(common_name__icontains=value)
| Q(subject_alternative_names__icontains=value)
| Q(issuer__icontains=value)
| Q(serial_number__icontains=value)
| Q(fingerprint__icontains=value)
| Q(device__name__icontains=value)
| Q(virtualmachine__name__icontains=value)
| Q(tenant__name__icontains=value)
| Q(comments__icontains=value)
)
return queryset.filter(qs_filter)
+6
View File
@@ -22,3 +22,9 @@ from .software_product_version import (
SoftwareProductVersionBulkImportForm,
SoftwareProductVersionBulkEditForm,
)
from .certificate import (
CertificateForm,
CertificateFilterForm,
CertificateBulkImportForm,
CertificateBulkEditForm,
)
+301
View File
@@ -0,0 +1,301 @@
from django.forms import CharField, ChoiceField, DateField, IntegerField, MultipleChoiceField, Textarea
from django.utils.translation import gettext_lazy as _
from dcim.models import Device
from netbox.forms import NetBoxModelForm, NetBoxModelFilterSetForm, NetBoxModelImportForm, NetBoxModelBulkEditForm
from netbox_slm.models import (
Certificate,
CertificateTypes,
NotificationIntervalUnits,
SoftwareProduct,
SoftwareProductInstallation,
)
from tenancy.models import Tenant, TenantGroup
from utilities.forms import add_blank_choice
from utilities.forms.constants import BOOLEAN_WITH_BLANK_CHOICES
from utilities.forms.fields import (
CommentField,
DynamicModelChoiceField,
DynamicModelMultipleChoiceField,
LaxURLField,
TagFilterField,
)
from utilities.forms.rendering import FieldSet
from utilities.forms.widgets import DatePicker
from virtualization.models import VirtualMachine
class CertificateForm(NetBoxModelForm):
comments = CommentField()
fieldsets = (
FieldSet("name", "description", "type", name=_("Certificate")),
FieldSet("software_product", "installation", "device", "virtualmachine", name=_("Assignment")),
FieldSet("tenant_group", "tenant", name=_("Tenancy")),
FieldSet(
"common_name",
"subject_alternative_names",
"issuer",
"serial_number",
"fingerprint",
"start_date",
"expiration_date",
"auto_renewal",
name=_("Certificate Details"),
),
FieldSet(
"certificate_file",
"stored_location",
"stored_location_url",
"provider_portal_url",
name=_("Storage"),
),
FieldSet(
"expiration_notifications_enabled",
"default_notification_intervals",
"custom_notification_interval",
"custom_notification_interval_unit",
"email_notifications",
name=_("Expiration Notifications"),
),
FieldSet("tags", name=_("Tags")),
)
subject_alternative_names = CharField(
required=False,
widget=Textarea(attrs={"rows": 3}),
label=_("Subject alternative names"),
help_text=_("One DNS name or IP address per line"),
)
start_date = DateField(required=False, widget=DatePicker(), label=_("Valid from"))
expiration_date = DateField(required=False, widget=DatePicker(), label=_("Valid until"))
stored_location_url = LaxURLField(required=False, label=_("Stored location URL"))
provider_portal_url = LaxURLField(required=False, label=_("Provider portal URL"))
custom_notification_interval = IntegerField(required=False, min_value=1)
software_product = DynamicModelChoiceField(
queryset=SoftwareProduct.objects.all(),
required=False,
label=_("Software Product"),
)
installation = DynamicModelChoiceField(
queryset=SoftwareProductInstallation.objects.all(),
required=False,
query_params={"software_product_id": "$software_product"},
label=_("Installation"),
)
device = DynamicModelChoiceField(queryset=Device.objects.all(), required=False, label=_("Device"))
virtualmachine = DynamicModelChoiceField(
queryset=VirtualMachine.objects.all(), required=False, label=_("Virtual Machine")
)
tenant_group = DynamicModelChoiceField(
queryset=TenantGroup.objects.all(),
required=False,
label=_("Tenant Group"),
)
tenant = DynamicModelChoiceField(
queryset=Tenant.objects.all(),
required=False,
query_params={"group_id": "$tenant_group"},
label=_("Tenant"),
)
class Meta:
model = Certificate
fields = (
"name",
"description",
"type",
"common_name",
"subject_alternative_names",
"issuer",
"serial_number",
"fingerprint",
"start_date",
"expiration_date",
"auto_renewal",
"certificate_file",
"stored_location",
"stored_location_url",
"provider_portal_url",
"expiration_notifications_enabled",
"default_notification_intervals",
"custom_notification_interval",
"custom_notification_interval_unit",
"email_notifications",
"software_product",
"installation",
"device",
"virtualmachine",
"tenant_group",
"tenant",
"tags",
"comments",
)
class CertificateFilterForm(NetBoxModelFilterSetForm):
model = Certificate
fieldsets = (
FieldSet("q", "filter_id", "tag"),
FieldSet(
"name",
"type",
"common_name",
"issuer",
"serial_number",
"auto_renewal",
"expiration_notifications_enabled",
"email_notifications",
name=_("Attributes"),
),
FieldSet(
"software_product_id",
"installation_id",
"device_id",
"virtualmachine_id",
"tenant_group_id",
"tenant_id",
name=_("Assignment"),
),
)
selector_fields = ("q", "filter_id", "name")
tag = TagFilterField(model)
name = CharField(required=False)
type = MultipleChoiceField(required=False, choices=CertificateTypes.choices)
common_name = CharField(required=False)
issuer = CharField(required=False)
serial_number = CharField(required=False)
auto_renewal = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES)
expiration_notifications_enabled = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES)
email_notifications = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES)
software_product_id = DynamicModelMultipleChoiceField(
queryset=SoftwareProduct.objects.all(), required=False, label=_("Software Product")
)
installation_id = DynamicModelMultipleChoiceField(
queryset=SoftwareProductInstallation.objects.all(), required=False, label=_("Installation")
)
device_id = DynamicModelMultipleChoiceField(queryset=Device.objects.all(), required=False, label=_("Device"))
virtualmachine_id = DynamicModelMultipleChoiceField(
queryset=VirtualMachine.objects.all(), required=False, label=_("Virtual Machine")
)
tenant_group_id = DynamicModelMultipleChoiceField(
queryset=TenantGroup.objects.all(), required=False, label=_("Tenant Group")
)
tenant_id = DynamicModelMultipleChoiceField(
queryset=Tenant.objects.all(),
required=False,
query_params={"group_id": "$tenant_group_id"},
label=_("Tenant"),
)
class CertificateBulkImportForm(NetBoxModelImportForm):
class Meta:
model = Certificate
fields = (
"name",
"description",
"type",
"common_name",
"subject_alternative_names",
"issuer",
"serial_number",
"fingerprint",
"start_date",
"expiration_date",
"auto_renewal",
"stored_location",
"stored_location_url",
"provider_portal_url",
"expiration_notifications_enabled",
"default_notification_intervals",
"custom_notification_interval",
"custom_notification_interval_unit",
"email_notifications",
"software_product",
"installation",
"device",
"virtualmachine",
"tenant_group",
"tenant",
"tags",
)
class CertificateBulkEditForm(NetBoxModelBulkEditForm):
model = Certificate
fieldsets = (
FieldSet(
"type",
"issuer",
"start_date",
"expiration_date",
"auto_renewal",
"stored_location",
"stored_location_url",
"provider_portal_url",
"expiration_notifications_enabled",
"default_notification_intervals",
"custom_notification_interval",
"custom_notification_interval_unit",
"email_notifications",
"software_product",
"device",
"virtualmachine",
"tenant_group",
"tenant",
),
)
nullable_fields = (
"type",
"issuer",
"start_date",
"expiration_date",
"stored_location",
"stored_location_url",
"provider_portal_url",
"custom_notification_interval",
"custom_notification_interval_unit",
"software_product",
"device",
"virtualmachine",
"tenant_group",
"tenant",
)
tag = TagFilterField(model)
comments = CommentField()
type = ChoiceField(required=False, choices=add_blank_choice(CertificateTypes.choices))
issuer = CharField(required=False)
start_date = DateField(required=False, widget=DatePicker(), label=_("Valid from"))
expiration_date = DateField(required=False, widget=DatePicker(), label=_("Valid until"))
auto_renewal = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES)
stored_location = CharField(required=False)
stored_location_url = LaxURLField(required=False)
provider_portal_url = LaxURLField(required=False)
expiration_notifications_enabled = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES)
default_notification_intervals = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES)
custom_notification_interval = IntegerField(required=False, min_value=1)
custom_notification_interval_unit = ChoiceField(
required=False, choices=add_blank_choice(NotificationIntervalUnits.choices)
)
email_notifications = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES)
software_product = DynamicModelChoiceField(
queryset=SoftwareProduct.objects.all(), required=False, label=_("Software Product")
)
device = DynamicModelChoiceField(queryset=Device.objects.all(), required=False, label=_("Device"))
virtualmachine = DynamicModelChoiceField(
queryset=VirtualMachine.objects.all(), required=False, label=_("Virtual Machine")
)
tenant_group = DynamicModelChoiceField(queryset=TenantGroup.objects.all(), required=False, label=_("Tenant Group"))
tenant = DynamicModelChoiceField(
queryset=Tenant.objects.all(),
required=False,
query_params={"group_id": "$tenant_group"},
label=_("Tenant"),
)
+102 -43
View File
@@ -8,84 +8,143 @@ from core.choices import JobIntervalChoices
from extras.models import Notification
from netbox.jobs import JobRunner, system_job
from netbox_slm.events import LICENSE_EXPIRING
from netbox_slm.models import SoftwareLicense, SoftwareLicenseNotificationLog
from netbox_slm.events import CERTIFICATE_EXPIRING, LICENSE_EXPIRING
from netbox_slm.models import (
Certificate,
CertificateNotificationLog,
SoftwareLicense,
SoftwareLicenseNotificationLog,
)
@system_job(interval=JobIntervalChoices.INTERVAL_DAILY)
class LicenseExpirationNotificationJob(JobRunner):
class Meta:
name = "Software License Expiration Notifications"
class ExpirationNotificationJob(JobRunner):
"""Shared reminder logic; subclasses define the model, log model, event type and email text."""
model = None
log_model = None
log_object_field = None
event_type = None
def get_queryset(self, today):
return self.model.objects.filter(
expiration_notifications_enabled=True,
expiration_date__gte=today,
)
def get_email(self, obj):
raise NotImplementedError
def run(self, *args, **kwargs):
today = timezone.localdate()
licenses = SoftwareLicense.objects.filter(
expiration_notifications_enabled=True,
lifetime=False,
expiration_date__gte=today,
).prefetch_related("subscriptions__user")
objects = self.get_queryset(today).prefetch_related("subscriptions__user")
for license in licenses:
due_dates = [date for date in license.get_notification_dates() if date <= today]
for obj in objects:
due_dates = [date for date in obj.get_notification_dates() if date <= today]
if not due_dates:
continue
for subscription in license.subscriptions.all():
for subscription in obj.subscriptions.all():
user = subscription.user
if not user.is_active:
continue
# If notifications were enabled late, send only the most recent reminder instead of one per elapsed
# interval. Normally this still produces one reminder at each configured threshold.
self._notify(license, user, max(due_dates))
self._notify(obj, user, max(due_dates))
def _notify(self, license, user, notification_date):
log = SoftwareLicenseNotificationLog.objects.get_or_create(
license=license,
def _notify(self, obj, user, notification_date):
log = self.log_model.objects.get_or_create(
**{self.log_object_field: obj},
user=user,
expiration_date=license.expiration_date,
expiration_date=obj.expiration_date,
notification_date=notification_date,
)[0]
now = timezone.now()
name = self.model._meta.model_name
object_type = ContentType.objects.get_for_model(license)
object_type = ContentType.objects.get_for_model(obj)
Notification.objects.update_or_create(
object_type=object_type,
object_id=license.pk,
object_id=obj.pk,
user=user,
defaults={
"created": now,
"object_repr": Notification.get_object_repr(license),
"event_type": LICENSE_EXPIRING,
"object_repr": Notification.get_object_repr(obj),
"event_type": self.event_type,
"read": None,
},
)
log.netbox_sent_at = now
log.save(update_fields=("netbox_sent_at",))
self.logger.info(f"Created NetBox expiration notification for license {license.pk} and user {user}")
if license.email_notifications and user.email:
subject = _("License %(license)s expires on %(date)s") % {
"license": license,
"date": license.expiration_date,
}
body = _(
"The software license '%(license)s' for '%(product)s' expires on %(date)s."
) % {
"license": license,
"product": license.software_product,
"date": license.expiration_date,
}
if license.tenant:
body += "\n" + _("Tenant: %(tenant)s") % {"tenant": license.tenant}
if license.provider_portal_url:
body += "\n" + _("Provider portal: %(url)s") % {"url": license.provider_portal_url}
self.logger.info(f"Created NetBox expiration notification for {name} {obj.pk} and user {user}")
if obj.email_notifications and user.email:
subject, body = self.get_email(obj)
try:
from_email = settings.SERVER_EMAIL or settings.EMAIL_HOST_USER
send_mail(subject, body, from_email, [user.email], fail_silently=False)
except Exception:
self.logger.exception(f"Failed to send expiration email for license {license.pk} to user {user}")
self.logger.exception(f"Failed to send expiration email for {name} {obj.pk} to user {user}")
else:
log.email_sent_at = now
log.save(update_fields=("email_sent_at",))
self.logger.info(f"Sent expiration email for license {license.pk} to user {user}")
self.logger.info(f"Sent expiration email for {name} {obj.pk} to user {user}")
@system_job(interval=JobIntervalChoices.INTERVAL_DAILY)
class LicenseExpirationNotificationJob(ExpirationNotificationJob):
model = SoftwareLicense
log_model = SoftwareLicenseNotificationLog
log_object_field = "license"
event_type = LICENSE_EXPIRING
class Meta:
name = "Software License Expiration Notifications"
def get_queryset(self, today):
return super().get_queryset(today).filter(lifetime=False)
def get_email(self, license):
subject = _("License %(license)s expires on %(date)s") % {
"license": license,
"date": license.expiration_date,
}
body = _("The software license '%(license)s' for '%(product)s' expires on %(date)s.") % {
"license": license,
"product": license.software_product,
"date": license.expiration_date,
}
if license.tenant:
body += "\n" + _("Tenant: %(tenant)s") % {"tenant": license.tenant}
if license.provider_portal_url:
body += "\n" + _("Provider portal: %(url)s") % {"url": license.provider_portal_url}
return subject, body
@system_job(interval=JobIntervalChoices.INTERVAL_DAILY)
class CertificateExpirationNotificationJob(ExpirationNotificationJob):
model = Certificate
log_model = CertificateNotificationLog
log_object_field = "certificate"
event_type = CERTIFICATE_EXPIRING
class Meta:
name = "Certificate Expiration Notifications"
def get_email(self, certificate):
subject = _("Certificate %(certificate)s expires on %(date)s") % {
"certificate": certificate,
"date": certificate.expiration_date,
}
body = _("The certificate '%(certificate)s' expires on %(date)s.") % {
"certificate": certificate,
"date": certificate.expiration_date,
}
if certificate.common_name:
body += "\n" + _("Common name: %(name)s") % {"name": certificate.common_name}
if certificate.issuer:
body += "\n" + _("Issuer: %(issuer)s") % {"issuer": certificate.issuer}
if certificate.tenant:
body += "\n" + _("Tenant: %(tenant)s") % {"tenant": certificate.tenant}
if certificate.provider_portal_url:
body += "\n" + _("Provider portal: %(url)s") % {"url": certificate.provider_portal_url}
return subject, body
Binary file not shown.
+129
View File
@@ -417,3 +417,132 @@ msgstr "Sie haben keine Berechtigung, E-Mail-Benachrichtigungen zu ändern."
msgid "Only administrators or explicitly authorized users can change this setting."
msgstr "Nur Administratoren oder ausdrücklich berechtigte Benutzer können diese Einstellung ändern."
msgid "Certificate"
msgstr "Zertifikat"
msgid "Certificates"
msgstr "Zertifikate"
msgid "certificate"
msgstr "Zertifikat"
msgid "certificates"
msgstr "Zertifikate"
msgid "Certificate Details"
msgstr "Zertifikatsdetails"
msgid "Assignment"
msgstr "Zuordnung"
msgid "Storage"
msgstr "Ablage"
msgid "Attributes"
msgstr "Attribute"
msgid "TLS server"
msgstr "TLS-Server"
msgid "TLS client"
msgstr "TLS-Client"
msgid "Certificate authority"
msgstr "Zertifizierungsstelle"
msgid "Code signing"
msgstr "Codesignatur"
msgid "S/MIME email"
msgstr "S/MIME-E-Mail"
msgid "Other"
msgstr "Sonstiges"
msgid "common name"
msgstr "Common Name"
msgid "Common name"
msgstr "Common Name"
msgid "subject alternative names"
msgstr "alternative Namen (SAN)"
msgid "Subject alternative names"
msgstr "Alternative Namen (SAN)"
msgid "One DNS name or IP address per line"
msgstr "Ein DNS-Name oder eine IP-Adresse pro Zeile"
msgid "issuer"
msgstr "Aussteller"
msgid "Issuer"
msgstr "Aussteller"
msgid "serial number"
msgstr "Seriennummer"
msgid "Serial number"
msgstr "Seriennummer"
msgid "SHA-256 fingerprint"
msgstr "SHA-256-Fingerabdruck"
msgid "valid from"
msgstr "gültig ab"
msgid "Valid from"
msgstr "Gültig ab"
msgid "valid until"
msgstr "gültig bis"
msgid "Valid until"
msgstr "Gültig bis"
msgid "automatic renewal"
msgstr "automatische Erneuerung"
msgid "Automatic renewal"
msgstr "Automatische Erneuerung"
msgid "certificate file"
msgstr "Zertifikatsdatei"
msgid "Certificate file"
msgstr "Zertifikatsdatei"
msgid "Download certificate file"
msgstr "Zertifikatsdatei herunterladen"
msgid "Stored location URL"
msgstr "URL des Ablageorts"
msgid "Provider portal URL"
msgstr "URL des Anbieterportals"
msgid "Can manage certificate email notifications"
msgstr "Darf E-Mail-Benachrichtigungen für Zertifikate verwalten"
msgid "Certificate expiring"
msgstr "Zertifikat läuft ab"
msgid "The expiration date must not be before the start date."
msgstr "Das Ablaufdatum darf nicht vor dem Startdatum liegen."
msgid "No subscribers. Users can subscribe to this certificate using the Subscribe action."
msgstr "Keine Abonnenten. Benutzer können dieses Zertifikat über die Aktion „Abonnieren“ abonnieren."
msgid "Certificate %(certificate)s expires on %(date)s"
msgstr "Zertifikat %(certificate)s läuft am %(date)s ab"
msgid "The certificate '%(certificate)s' expires on %(date)s."
msgstr "Das Zertifikat „%(certificate)s“ läuft am %(date)s ab."
msgid "Common name: %(name)s"
msgstr "Common Name: %(name)s"
msgid "Issuer: %(issuer)s"
msgstr "Aussteller: %(issuer)s"
+181
View File
@@ -0,0 +1,181 @@
import django.core.validators
import django.db.models.deletion
import taggit.managers
from django.conf import settings
from django.db import migrations, models
import netbox_slm.models
import utilities.json
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("dcim", "0001_initial"),
("extras", "0001_initial"),
("tenancy", "0001_initial"),
("virtualization", "0001_initial"),
("netbox_slm", "0014_softwarelicense_email_notification_permission"),
]
operations = [
migrations.CreateModel(
name="Certificate",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
("created", models.DateTimeField(auto_now_add=True, null=True)),
("last_updated", models.DateTimeField(auto_now=True, null=True)),
(
"custom_field_data",
models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder),
),
("expiration_notifications_enabled", models.BooleanField(default=True)),
("default_notification_intervals", models.BooleanField(default=True)),
(
"custom_notification_interval",
models.PositiveIntegerField(
blank=True, null=True, validators=[django.core.validators.MinValueValidator(1)]
),
),
(
"custom_notification_interval_unit",
models.CharField(
blank=True,
choices=[("days", "Days"), ("weeks", "Weeks"), ("months", "Months")],
max_length=8,
),
),
("email_notifications", models.BooleanField(default=False)),
("name", models.CharField(max_length=128)),
("comments", models.TextField(blank=True)),
("description", models.CharField(blank=True, max_length=255)),
(
"type",
models.CharField(
blank=True,
choices=[
("server", "TLS server"),
("client", "TLS client"),
("ca", "Certificate authority"),
("code_signing", "Code signing"),
("email", "S/MIME email"),
("other", "Other"),
],
max_length=16,
),
),
("common_name", models.CharField(blank=True, max_length=255)),
("subject_alternative_names", models.TextField(blank=True)),
("issuer", models.CharField(blank=True, max_length=255)),
("serial_number", models.CharField(blank=True, max_length=128)),
("fingerprint", models.CharField(blank=True, max_length=128)),
("start_date", models.DateField(blank=True, null=True)),
("expiration_date", models.DateField(blank=True, null=True)),
("auto_renewal", models.BooleanField(default=False)),
(
"certificate_file",
models.FileField(blank=True, null=True, upload_to="netbox_slm/certificates/"),
),
("stored_location", models.CharField(blank=True, max_length=255)),
("stored_location_url", netbox_slm.models.LaxURLField(blank=True, max_length=1024, null=True)),
("provider_portal_url", netbox_slm.models.LaxURLField(blank=True, max_length=1024, null=True)),
(
"device",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="certificates",
to="dcim.device",
),
),
(
"installation",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="certificates",
to="netbox_slm.softwareproductinstallation",
),
),
(
"software_product",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
related_name="certificates",
to="netbox_slm.softwareproduct",
),
),
("tags", taggit.managers.TaggableManager(through="extras.TaggedItem", to="extras.Tag")),
(
"tenant",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
related_name="certificates",
to="tenancy.tenant",
),
),
(
"tenant_group",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
related_name="certificates",
to="tenancy.tenantgroup",
),
),
(
"virtualmachine",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="certificates",
to="virtualization.virtualmachine",
),
),
],
options={
"verbose_name": "certificate",
"verbose_name_plural": "certificates",
"permissions": [
("manage_certificate_email_notifications", "Can manage certificate email notifications")
],
},
),
migrations.CreateModel(
name="CertificateNotificationLog",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("expiration_date", models.DateField()),
("notification_date", models.DateField()),
("netbox_sent_at", models.DateTimeField(blank=True, null=True)),
("email_sent_at", models.DateTimeField(blank=True, null=True)),
(
"certificate",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="notification_logs",
to="netbox_slm.certificate",
),
),
(
"user",
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
],
),
migrations.AddConstraint(
model_name="certificatenotificationlog",
constraint=models.UniqueConstraint(
fields=("certificate", "user", "expiration_date", "notification_date"),
name="netbox_slm_certificate_notification_unique",
),
),
]
+198 -49
View File
@@ -68,6 +68,15 @@ class RenewalIntervalUnits(models.TextChoices):
YEARS = "years", _("Years")
class CertificateTypes(models.TextChoices):
SERVER = "server", _("TLS server")
CLIENT = "client", _("TLS client")
CA = "ca", _("Certificate authority")
CODE_SIGNING = "code_signing", _("Code signing")
EMAIL = "email", _("S/MIME email")
OTHER = "other", _("Other")
class NotificationIntervalUnits(models.TextChoices):
DAYS = "days", _("Days")
WEEKS = "weeks", _("Weeks")
@@ -177,6 +186,68 @@ class SoftwareProductInstallation(NetBoxModel):
return "cluster"
class ExpirationNotificationModel(models.Model):
"""Shared expiration reminder settings for objects with an expiration date."""
expiration_notifications_enabled = models.BooleanField(_("expiration notifications"), default=True)
default_notification_intervals = models.BooleanField(_("default notification intervals"), default=True)
custom_notification_interval = models.PositiveIntegerField(
_("custom notification interval"), null=True, blank=True, validators=[MinValueValidator(1)]
)
custom_notification_interval_unit = models.CharField(
_("custom notification interval unit"),
max_length=8,
choices=NotificationIntervalUnits.choices,
blank=True,
)
email_notifications = models.BooleanField(_("email notifications"), default=False)
class Meta:
abstract = True
def has_expiration(self):
return bool(self.expiration_date)
def clean_notification_settings(self):
if bool(self.custom_notification_interval) != bool(self.custom_notification_interval_unit):
raise ValidationError(
{
"custom_notification_interval": _(
"Custom notification interval and unit must be specified together."
)
}
)
@staticmethod
def _subtract_months(value, months):
month_index = value.year * 12 + value.month - 1 - months
year, zero_based_month = divmod(month_index, 12)
month = zero_based_month + 1
day = min(value.day, calendar.monthrange(year, month)[1])
return value.replace(year=year, month=month, day=day)
def get_notification_dates(self):
"""Return unique reminder dates for the current expiration date."""
if not self.expiration_notifications_enabled or not self.has_expiration():
return []
dates = set()
if self.default_notification_intervals:
dates.add(self._subtract_months(self.expiration_date, 1))
dates.add(self.expiration_date - timedelta(weeks=1))
if self.custom_notification_interval and self.custom_notification_interval_unit:
amount = self.custom_notification_interval
if self.custom_notification_interval_unit == NotificationIntervalUnits.MONTHS:
dates.add(self._subtract_months(self.expiration_date, amount))
elif self.custom_notification_interval_unit == NotificationIntervalUnits.WEEKS:
dates.add(self.expiration_date - timedelta(weeks=amount))
else:
dates.add(self.expiration_date - timedelta(days=amount))
return sorted(dates)
def spdx_license_names():
names = [(item[0], item[0]) for item in spdx_licensing.known_symbols.items() if not item[1].is_exception]
names.sort()
@@ -190,7 +261,7 @@ def validate_spdx_expression(value):
raise ValidationError(_("%(value)s is not a known SPDX license expression") % {"value": value})
class SoftwareLicense(NetBoxModel):
class SoftwareLicense(NetBoxModel, ExpirationNotificationModel):
name = models.CharField(_("name"), max_length=128)
comments = models.TextField(_("comments"), blank=True)
@@ -215,18 +286,6 @@ class SoftwareLicense(NetBoxModel):
license_file = models.FileField(_("license file"), upload_to="netbox_slm/licenses/", null=True, blank=True)
license_key = models.TextField(_("license key"), blank=True)
provider_portal_url = LaxURLField(_("provider portal URL"), max_length=1024, null=True, blank=True)
expiration_notifications_enabled = models.BooleanField(_("expiration notifications"), default=True)
default_notification_intervals = models.BooleanField(_("default notification intervals"), default=True)
custom_notification_interval = models.PositiveIntegerField(
_("custom notification interval"), null=True, blank=True, validators=[MinValueValidator(1)]
)
custom_notification_interval_unit = models.CharField(
_("custom notification interval unit"),
max_length=8,
choices=NotificationIntervalUnits.choices,
blank=True,
)
email_notifications = models.BooleanField(_("email notifications"), default=False)
software_product = models.ForeignKey(
to="netbox_slm.SoftwareProduct", verbose_name=_("software product"), on_delete=models.PROTECT
@@ -291,43 +350,10 @@ class SoftwareLicense(NetBoxModel):
raise ValidationError(
{"lifetime": _("A lifetime license cannot have a renewal interval or expiration date.")}
)
if bool(self.custom_notification_interval) != bool(self.custom_notification_interval_unit):
raise ValidationError(
{
"custom_notification_interval": _(
"Custom notification interval and unit must be specified together."
)
}
)
self.clean_notification_settings()
@staticmethod
def _subtract_months(value, months):
month_index = value.year * 12 + value.month - 1 - months
year, zero_based_month = divmod(month_index, 12)
month = zero_based_month + 1
day = min(value.day, calendar.monthrange(year, month)[1])
return value.replace(year=year, month=month, day=day)
def get_notification_dates(self):
"""Return unique reminder dates for the current expiration date."""
if not self.expiration_notifications_enabled or self.lifetime or not self.expiration_date:
return []
dates = set()
if self.default_notification_intervals:
dates.add(self._subtract_months(self.expiration_date, 1))
dates.add(self.expiration_date - timedelta(weeks=1))
if self.custom_notification_interval and self.custom_notification_interval_unit:
amount = self.custom_notification_interval
if self.custom_notification_interval_unit == NotificationIntervalUnits.MONTHS:
dates.add(self._subtract_months(self.expiration_date, amount))
elif self.custom_notification_interval_unit == NotificationIntervalUnits.WEEKS:
dates.add(self.expiration_date - timedelta(weeks=amount))
else:
dates.add(self.expiration_date - timedelta(days=amount))
return sorted(dates)
def has_expiration(self):
return not self.lifetime and bool(self.expiration_date)
@property
def stored_location_txt(self):
@@ -353,3 +379,126 @@ class SoftwareLicenseNotificationLog(models.Model):
name="netbox_slm_license_notification_unique",
)
]
class Certificate(NetBoxModel, ExpirationNotificationModel):
name = models.CharField(_("name"), max_length=128)
comments = models.TextField(_("comments"), blank=True)
description = models.CharField(_("description"), max_length=255, blank=True)
type = models.CharField(_("type"), max_length=16, choices=CertificateTypes.choices, blank=True)
common_name = models.CharField(_("common name"), max_length=255, blank=True)
subject_alternative_names = models.TextField(
_("subject alternative names"), blank=True, help_text=_("One DNS name or IP address per line")
)
issuer = models.CharField(_("issuer"), max_length=255, blank=True)
serial_number = models.CharField(_("serial number"), max_length=128, blank=True)
fingerprint = models.CharField(_("SHA-256 fingerprint"), max_length=128, blank=True)
start_date = models.DateField(_("valid from"), null=True, blank=True)
expiration_date = models.DateField(_("valid until"), null=True, blank=True)
auto_renewal = models.BooleanField(_("automatic renewal"), default=False)
certificate_file = models.FileField(
_("certificate file"), upload_to="netbox_slm/certificates/", null=True, blank=True
)
stored_location = models.CharField(_("stored location"), max_length=255, blank=True)
stored_location_url = LaxURLField(_("stored location URL"), max_length=1024, null=True, blank=True)
provider_portal_url = LaxURLField(_("provider portal URL"), max_length=1024, null=True, blank=True)
software_product = models.ForeignKey(
to="netbox_slm.SoftwareProduct",
verbose_name=_("software product"),
on_delete=models.PROTECT,
null=True,
blank=True,
related_name="certificates",
)
installation = models.ForeignKey(
to="netbox_slm.SoftwareProductInstallation",
verbose_name=_("installation"),
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="certificates",
)
device = models.ForeignKey(
to="dcim.Device",
verbose_name=_("device"),
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="certificates",
)
virtualmachine = models.ForeignKey(
to="virtualization.VirtualMachine",
verbose_name=_("virtual machine"),
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="certificates",
)
tenant_group = models.ForeignKey(
to="tenancy.TenantGroup",
verbose_name=_("tenant group"),
on_delete=models.PROTECT,
null=True,
blank=True,
related_name="certificates",
)
tenant = models.ForeignKey(
to="tenancy.Tenant",
verbose_name=_("tenant"),
on_delete=models.PROTECT,
null=True,
blank=True,
related_name="certificates",
)
objects = RestrictedQuerySet.as_manager()
class Meta:
verbose_name = _("certificate")
verbose_name_plural = _("certificates")
permissions = [
("manage_certificate_email_notifications", _("Can manage certificate email notifications")),
]
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("plugins:netbox_slm:certificate", kwargs={"pk": self.pk})
def clean(self):
super().clean()
if self.tenant_group and self.tenant and self.tenant.group_id != self.tenant_group_id:
raise ValidationError(
{"tenant": _("The selected tenant does not belong to the selected tenant group.")}
)
if self.start_date and self.expiration_date and self.start_date > self.expiration_date:
raise ValidationError({"expiration_date": _("The expiration date must not be before the start date.")})
self.clean_notification_settings()
@property
def stored_location_txt(self):
if self.stored_location_url and not self.stored_location:
return _("Link")
return self.stored_location
class CertificateNotificationLog(models.Model):
certificate = models.ForeignKey(
to="netbox_slm.Certificate", on_delete=models.CASCADE, related_name="notification_logs"
)
user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
expiration_date = models.DateField()
notification_date = models.DateField()
netbox_sent_at = models.DateTimeField(null=True, blank=True)
email_sent_at = models.DateTimeField(null=True, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=("certificate", "user", "expiration_date", "notification_date"),
name="netbox_slm_certificate_notification_unique",
)
]
+19
View File
@@ -79,6 +79,25 @@ slm_items = (
),
),
),
PluginMenuItem(
link="plugins:netbox_slm:certificate_list",
link_text=_("Certificates"),
permissions=["netbox_slm.view_certificate"],
buttons=(
PluginMenuButton(
"plugins:netbox_slm:certificate_add",
_("Add"),
"mdi mdi-plus-thick",
permissions=["netbox_slm.add_certificate"],
),
PluginMenuButton(
"plugins:netbox_slm:certificate_bulk_import",
_("Import"),
"mdi mdi-upload",
permissions=["netbox_slm.add_certificate"],
),
),
),
)
if get_plugin_config("netbox_slm", "top_level_menu"):
+69 -1
View File
@@ -3,7 +3,13 @@ from django.db.models import Count, F, Value
from django.utils.translation import gettext_lazy as _
from netbox.tables import NetBoxTable, ToggleColumn, columns
from netbox_slm.models import SoftwareProduct, SoftwareProductVersion, SoftwareProductInstallation, SoftwareLicense
from netbox_slm.models import (
Certificate,
SoftwareProduct,
SoftwareProductVersion,
SoftwareProductInstallation,
SoftwareLicense,
)
class SoftwareProductTable(NetBoxTable):
@@ -195,3 +201,65 @@ class SoftwareLicenseTable(NetBoxTable):
def render_installation(self, **kwargs):
return f"{kwargs['record'].installation.platform}"
class CertificateTable(NetBoxTable):
"""Table for displaying Certificate objects."""
pk = ToggleColumn()
name = tables.LinkColumn()
type = tables.Column()
stored_location = tables.Column(accessor="stored_location_txt", linkify=lambda record: record.stored_location_url)
software_product = tables.Column(accessor="software_product", verbose_name=_("Software Product"), linkify=True)
installation = tables.Column(accessor="installation", linkify=True)
device = tables.Column(accessor="device", linkify=True)
virtualmachine = tables.Column(accessor="virtualmachine", verbose_name=_("Virtual Machine"), linkify=True)
tenant_group = tables.Column(accessor="tenant_group", verbose_name=_("Tenant Group"), linkify=True)
tenant = tables.Column(accessor="tenant", linkify=True)
provider_portal_url = tables.Column(verbose_name=_("Provider Portal"), linkify=True)
tags = columns.TagColumn(url_name="plugins:netbox_slm:certificate_list")
class Meta(NetBoxTable.Meta):
model = Certificate
fields = (
"pk",
"name",
"description",
"type",
"common_name",
"issuer",
"serial_number",
"fingerprint",
"start_date",
"expiration_date",
"auto_renewal",
"stored_location",
"software_product",
"installation",
"device",
"virtualmachine",
"tenant_group",
"tenant",
"provider_portal_url",
"expiration_notifications_enabled",
"email_notifications",
"tags",
)
default_columns = (
"pk",
"name",
"type",
"common_name",
"issuer",
"device",
"virtualmachine",
"tenant",
"expiration_date",
"expiration_notifications_enabled",
"tags",
)
def render_installation(self, **kwargs):
return f"{kwargs['record'].installation.platform}"
@@ -0,0 +1,187 @@
{% extends 'generic/object.html' %}
{% load buttons %}
{% load static %}
{% load helpers %}
{% load plugins %}
{% load i18n %}
{% block content %}
<div class="row my-3">
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
{% trans "Certificate" %}
</h5>
<table class="table table-hover attr-table">
<tr>
<th scope="row">{% trans "Name" %}</th>
<td>{{ object.name }}</td>
</tr>
<tr>
<th scope="row">{% trans "Description" %}</th>
<td>{{ object.description|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Type" %}</th>
<td>{{ object.get_type_display|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Common name" %}</th>
<td>{{ object.common_name|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Subject alternative names" %}</th>
<td>{% if object.subject_alternative_names %}{{ object.subject_alternative_names|linebreaksbr }}{% else %}{{ None|placeholder }}{% endif %}</td>
</tr>
<tr>
<th scope="row">{% trans "Issuer" %}</th>
<td>{{ object.issuer|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Serial number" %}</th>
<td>{% if object.serial_number %}<code>{{ object.serial_number }}</code>{% else %}{{ None|placeholder }}{% endif %}</td>
</tr>
<tr>
<th scope="row">{% trans "SHA-256 fingerprint" %}</th>
<td>{% if object.fingerprint %}<code>{{ object.fingerprint }}</code>{% else %}{{ None|placeholder }}{% endif %}</td>
</tr>
<tr>
<th scope="row">{% trans "Valid from" %}</th>
<td>{{ object.start_date|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Valid until" %}</th>
<td>{{ object.expiration_date|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Automatic renewal" %}</th>
<td>{% if object.auto_renewal %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}</td>
</tr>
</table>
</div>
<div class="card">
<h5 class="card-header">
{% trans "Assignment" %}
</h5>
<table class="table table-hover attr-table">
<tr>
<th scope="row">{% trans "Software Product" %}</th>
<td>{{ object.software_product|linkify|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Installation" %}</th>
<td>{{ object.installation|linkify|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Device" %}</th>
<td>{{ object.device|linkify|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Virtual Machine" %}</th>
<td>{{ object.virtualmachine|linkify|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Tenant Group" %}</th>
<td>{{ object.tenant_group|linkify|placeholder }}</td>
</tr>
<tr>
<th scope="row">{% trans "Tenant" %}</th>
<td>{{ object.tenant|linkify|placeholder }}</td>
</tr>
</table>
</div>
{% include 'inc/panels/custom_fields.html' %}
{% include 'inc/panels/tags.html' %}
{% include 'inc/panels/comments.html' %}
{% plugin_left_page object %}
</div>
<div class="col col-md-6">
<div class="card">
<h5 class="card-header">
{% trans "Storage" %}
</h5>
<table class="table table-hover attr-table">
<tr>
<th scope="row">{% trans "Certificate file" %}</th>
<td>
{% if object.certificate_file %}
<a href="{{ object.certificate_file.url }}">{% trans "Download certificate file" %}</a>
{% else %}
{{ None|placeholder }}
{% endif %}
</td>
</tr>
<tr>
<th scope="row">{% trans "Stored location" %}</th>
{% if object.stored_location_url %}
<td><a href="{{ object.stored_location_url }}">{{ object.stored_location_txt }}</a></td>
{% else %}
<td>{{ object.stored_location_txt|placeholder }}</td>
{% endif %}
</tr>
<tr>
<th scope="row">{% trans "Provider Portal" %}</th>
<td>
{% if object.provider_portal_url %}
<a href="{{ object.provider_portal_url }}">{{ object.provider_portal_url }}</a>
{% else %}
{{ None|placeholder }}
{% endif %}
</td>
</tr>
</table>
</div>
<div class="card">
<h5 class="card-header">
{% trans "Expiration Notifications" %}
</h5>
<table class="table table-hover attr-table">
<tr>
<th scope="row">{% trans "Expiration notifications" %}</th>
<td>{% if object.expiration_notifications_enabled %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}</td>
</tr>
<tr>
<th scope="row">{% trans "Default notification intervals" %}</th>
<td>
{% if object.default_notification_intervals %}
{% trans "One month and one week before expiration" %}
{% else %}
{% trans "Disabled" %}
{% endif %}
</td>
</tr>
<tr>
<th scope="row">{% trans "Custom notification interval" %}</th>
<td>
{% if object.custom_notification_interval %}
{{ object.custom_notification_interval }} {{ object.get_custom_notification_interval_unit_display }}
{% else %}
{{ None|placeholder }}
{% endif %}
</td>
</tr>
<tr>
<th scope="row">{% trans "Email notifications" %}</th>
<td>{% if object.email_notifications %}{% trans "Enabled" %}{% else %}{% trans "Disabled" %}{% endif %}</td>
</tr>
<tr>
<th scope="row">{% trans "Notification recipients" %}</th>
<td>
{% for subscription in object.subscriptions.all %}
{{ subscription.user|linkify }}{% if not forloop.last %}, {% endif %}
{% empty %}
{% trans "No subscribers. Users can subscribe to this certificate using the Subscribe action." %}
{% endfor %}
</td>
</tr>
</table>
</div>
{% plugin_right_page object %}
</div>
</div>
<div class="row">
<div class="col col-md-12">
{% plugin_full_width_page object %}
</div>
</div>
{% endblock %}
+73 -1
View File
@@ -10,8 +10,10 @@ from django.utils.translation import gettext, override
from extras.models import Notification, Subscription
from netbox_slm.forms import SoftwareLicenseForm, SoftwareProductInstallationForm
from netbox_slm.jobs import LicenseExpirationNotificationJob
from netbox_slm.jobs import CertificateExpirationNotificationJob, LicenseExpirationNotificationJob
from netbox_slm.models import (
Certificate,
CertificateNotificationLog,
NotificationIntervalUnits,
RenewalIntervalUnits,
SoftwareLicense,
@@ -208,3 +210,73 @@ class ModelTestCase(SlmBaseTestCase):
with self.assertRaisesMessage(ValidationError, "does not belong to the selected tenant group"):
self.software_license.full_clean()
class CertificateTestCase(SlmBaseTestCase):
def test_certificate_absolute_url(self):
certificate = Certificate.objects.create(name="example.com")
self.assertEqual("example.com", str(certificate))
self.assertEqual(f"/plugins/slm/certificates/{certificate.pk}/", certificate.get_absolute_url())
def test_certificate_notification_dates(self):
certificate = Certificate(
name="expiring certificate",
expiration_date=date(2027, 3, 31),
custom_notification_interval=3,
custom_notification_interval_unit=NotificationIntervalUnits.DAYS,
)
self.assertEqual(
[date(2027, 2, 28), date(2027, 3, 24), date(2027, 3, 28)],
certificate.get_notification_dates(),
)
def test_certificate_rejects_expiration_before_start(self):
certificate = Certificate(
name="invalid certificate",
start_date=date(2027, 1, 1),
expiration_date=date(2026, 1, 1),
)
with self.assertRaisesMessage(ValidationError, "must not be before the start date"):
certificate.full_clean()
def test_certificate_requires_custom_interval_and_unit_together(self):
certificate = Certificate(name="invalid interval", custom_notification_interval=2)
with self.assertRaisesMessage(ValidationError, "must be specified together"):
certificate.full_clean()
@override_settings(SERVER_EMAIL="[email protected]", EMAIL_HOST_USER="smtp-user")
@patch("netbox_slm.jobs.send_mail")
def test_certificate_expiration_job_notifies_subscribers(self, send_mail):
user = get_user_model().objects.create_user(
username="certificate-recipient",
email="[email protected]",
)
certificate = Certificate.objects.create(
name="expiring.example.com",
common_name="expiring.example.com",
expiration_date=timezone.localdate() + timedelta(days=1),
default_notification_intervals=False,
custom_notification_interval=1,
custom_notification_interval_unit=NotificationIntervalUnits.DAYS,
email_notifications=True,
)
Subscription.objects.create(
user=user,
object_type=ContentType.objects.get_for_model(certificate),
object_id=certificate.pk,
)
runner = CertificateExpirationNotificationJob.__new__(CertificateExpirationNotificationJob)
runner.logger = Mock()
runner.run()
self.assertTrue(Notification.objects.filter(user=user, object_id=certificate.pk).exists())
self.assertEqual(
1, CertificateNotificationLog.objects.filter(user=user, certificate=certificate).count()
)
self.assertEqual(1, send_mail.call_count)
self.assertIn("expiring.example.com", send_mail.call_args.args[1])
def test_german_translation(self):
with override("de"):
self.assertEqual("Zertifikate", gettext("Certificates"))
+2
View File
@@ -12,4 +12,6 @@ urlpatterns = [
path("installations/<int:pk>/", include(get_model_urls("netbox_slm", "softwareproductinstallation"))),
path("licenses/", include(get_model_urls("netbox_slm", "softwarelicense", detail=False))),
path("licenses/<int:pk>/", include(get_model_urls("netbox_slm", "softwarelicense"))),
path("certificates/", include(get_model_urls("netbox_slm", "certificate", detail=False))),
path("certificates/<int:pk>/", include(get_model_urls("netbox_slm", "certificate"))),
]
+8
View File
@@ -30,3 +30,11 @@ from .software_product_version import (
SoftwareProductVersionBulkDeleteView,
SoftwareProductVersionBulkImportView,
)
from .certificate import (
CertificateListView,
CertificateView,
CertificateEditView,
CertificateDeleteView,
CertificateBulkDeleteView,
CertificateBulkImportView,
)
+55
View File
@@ -0,0 +1,55 @@
from netbox.views import generic
from netbox_slm import filtersets, forms, tables
from netbox_slm.models import Certificate
from netbox_slm.views.software_license import EmailNotificationPermissionMixin
from utilities.views import register_model_view
class CertificateEmailNotificationPermissionMixin(EmailNotificationPermissionMixin):
email_permission = "netbox_slm.manage_certificate_email_notifications"
@register_model_view(Certificate, "list", path="", detail=False)
class CertificateListView(generic.ObjectListView):
queryset = Certificate.objects.all()
filterset = filtersets.CertificateFilterSet
filterset_form = forms.CertificateFilterForm
table = tables.CertificateTable
@register_model_view(Certificate)
class CertificateView(generic.ObjectView):
queryset = Certificate.objects.all()
@register_model_view(Certificate, "add", detail=False)
@register_model_view(Certificate, "edit")
class CertificateEditView(CertificateEmailNotificationPermissionMixin, generic.ObjectEditView):
queryset = Certificate.objects.all()
form = forms.CertificateForm
@register_model_view(Certificate, "delete")
class CertificateDeleteView(generic.ObjectDeleteView):
queryset = Certificate.objects.all()
@register_model_view(Certificate, "bulk_import", detail=False)
class CertificateBulkImportView(CertificateEmailNotificationPermissionMixin, generic.BulkImportView):
queryset = Certificate.objects.all()
model_form = forms.CertificateBulkImportForm
@register_model_view(Certificate, "bulk_edit", path="edit", detail=False)
class CertificateBulkEditView(CertificateEmailNotificationPermissionMixin, generic.BulkEditView):
queryset = Certificate.objects.all()
filterset = filtersets.CertificateFilterSet
table = tables.CertificateTable
form = forms.CertificateBulkEditForm
@register_model_view(Certificate, "bulk_delete", path="delete", detail=False)
class CertificateBulkDeleteView(generic.BulkDeleteView):
queryset = Certificate.objects.all()
filterset = filtersets.CertificateFilterSet
table = tables.CertificateTable