Compare commits
10
Commits
426e9c80fd
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a81a04746 | ||
|
|
0f72a53d01 | ||
|
|
30d748969f | ||
|
|
9acf685b34 | ||
|
|
5dedfc9206 | ||
|
|
2a41118e8e | ||
|
|
f296a576f2 | ||
|
|
c4c93c5709 | ||
|
|
8e18ae82b8 | ||
|
|
02d965a77b |
No files matched your search
@@ -1,7 +1,15 @@
|
||||
<!-- Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. -->
|
||||
# Changelog
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
|
||||
* State the fork, the original authors and the Apache 2.0 license clearly in the README and a new NOTICE file
|
||||
* Mark files changed in this fork as modified (Apache License 2.0, section 4b)
|
||||
* Point project URLs to this fork and list ICTU as original author and MrBlake as maintainer
|
||||
|
||||
### Fixed
|
||||
|
||||
* Add the missing migration for the platform constraint's error message (verified against NetBox 4.7.2)
|
||||
@@ -13,6 +21,11 @@
|
||||
|
||||
### 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
|
||||
* Separate Certificates menu in the sidebar
|
||||
* Fill certificate fields automatically from an uploaded PEM or DER file and reject files containing private keys
|
||||
* 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
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
include LICENSE
|
||||
include NOTICE
|
||||
include README.md
|
||||
include SECURITY.md
|
||||
graft netbox_slm
|
||||
prune netbox_slm/tests
|
||||
global-exclude *.py[cod]
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
NetBox SLM (fork)
|
||||
Copyright 2022-2025 ICTU
|
||||
Modifications Copyright 2026 MrBlake
|
||||
|
||||
This product is a modified version of NetBox SLM by ICTU
|
||||
(https://github.com/ICTU/netbox_slm), based on its release 1.9.0.
|
||||
|
||||
The original work is licensed under the Apache License, Version 2.0. The
|
||||
modifications are distributed under the same license; see the LICENSE file.
|
||||
|
||||
Files that were changed in this fork carry a notice stating that they were
|
||||
modified. The complete history, including all original commits, is available at
|
||||
https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
|
||||
This fork is maintained independently and is not affiliated with or endorsed
|
||||
by ICTU.
|
||||
@@ -1,8 +1,12 @@
|
||||
# NetBox SLM
|
||||
|
||||
Software lifecycle and license management for NetBox: software products,
|
||||
versions, installations and licenses — with expiry notifications and optional
|
||||
tenant assignment.
|
||||
versions, installations, licenses and certificates — with expiry notifications
|
||||
and optional tenant assignment.
|
||||
|
||||
> **Fork notice:** This is a modified version of [NetBox SLM](https://github.com/ICTU/netbox_slm)
|
||||
> by **ICTU**, licensed under the [Apache License 2.0](LICENSE). It is maintained independently
|
||||
> and is not affiliated with or endorsed by ICTU. See [Origin, license and credits](#origin-license-and-credits).
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
@@ -12,6 +16,20 @@ tenant assignment.
|
||||
| **Python** | `>=3.11` |
|
||||
| **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-SLM> |
|
||||
|
||||
## Screenshots
|
||||
|
||||
Software licenses with expiry dates:
|
||||
|
||||

|
||||
|
||||
Certificates:
|
||||
|
||||

|
||||
|
||||
Software installations on devices and virtual machines:
|
||||
|
||||

|
||||
|
||||
## Features
|
||||
|
||||
- Manage software products and manufacturers
|
||||
@@ -24,6 +42,9 @@ tenant assignment.
|
||||
- Additional custom warning period in days, weeks or months
|
||||
- NetBox notifications and optional e-mail via NetBox's SMTP configuration
|
||||
- Assign licenses to tenant groups and tenants
|
||||
- Manage certificates with common name, SANs, issuer, serial number, fingerprint and validity period
|
||||
- Assign certificates to software products, installations, devices, virtual machines and tenants
|
||||
- Store certificate files and storage locations (private keys are intentionally not stored)
|
||||
- Full NetBox UI and REST API
|
||||
- Filters, bulk import and bulk edit
|
||||
- UI available in English and German (follows the user's NetBox language)
|
||||
@@ -131,7 +152,9 @@ The plugin's database tables are not dropped automatically.
|
||||
|
||||
### Expiry notifications
|
||||
|
||||
Notifications are enabled by default for licenses with an expiry date. The
|
||||
Notifications are enabled by default for licenses and certificates with an
|
||||
expiry date. Both use the same settings, so this section applies to
|
||||
certificates as well. The
|
||||
default reminders are one month and one week before expiry. Per license, an
|
||||
additional custom warning period can be set or the defaults can be disabled.
|
||||
|
||||
@@ -144,24 +167,70 @@ on the license, the plugin also sends an e-mail to the address stored in the
|
||||
user account; NetBox SMTP must be configured for this.
|
||||
|
||||
Enabling e-mail delivery can only be changed by administrators or users with
|
||||
the permission `netbox_slm.manage_softwarelicense_email_notifications`. SMTP
|
||||
the permission `netbox_slm.manage_license_emails`
|
||||
(licenses) or `netbox_slm.manage_certificate_emails`
|
||||
(certificates). SMTP
|
||||
credentials are maintained only in the NetBox server configuration and are not
|
||||
visible in the plugin.
|
||||
|
||||
The check runs once a day as a NetBox system job. Once the first configured
|
||||
The check runs once a day as a NetBox system job (one job each for licenses
|
||||
and certificates). Once the first configured
|
||||
reminder date is reached, subscribers are notified on every job run up to and
|
||||
including the expiry date. The NetBox RQ worker must run with scheduler support,
|
||||
which is the default for a standard NetBox installation with `rqworker`.
|
||||
|
||||
## Origin and license
|
||||
### Certificates
|
||||
|
||||
This repository is based on the original project
|
||||
[ICTU/netbox_slm](https://github.com/ICTU/netbox_slm). **ICTU** is the original
|
||||
author and publisher; [Mart Visser](https://github.com/MartVisser) is named as
|
||||
the contact in the original project.
|
||||
Certificates are managed under **Licences → Certificates**. Each certificate
|
||||
stores:
|
||||
|
||||
The changes in this fork are maintained at
|
||||
- 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, storage location (with optional URL) and provider portal URL
|
||||
- Optional assignment to a software product, installation, device, virtual
|
||||
machine, tenant group and tenant
|
||||
|
||||
When a certificate file (PEM or DER) is uploaded, the common name, subject
|
||||
alternative names, issuer, serial number, SHA-256 fingerprint and validity
|
||||
period are read from the file and overwrite the corresponding fields. Name and
|
||||
type are only filled in if they were left empty (the type is derived from the
|
||||
CA flag and extended key usage). For PEM bundles the first certificate is used.
|
||||
Files that contain a private key are rejected.
|
||||
|
||||
> **Note:** Private keys are intentionally not stored. Keep them in a dedicated
|
||||
> secret store and reference that location through the storage location fields.
|
||||
|
||||
Certificates are available in the REST API at `/api/plugins/slm/certificates/`
|
||||
and can be filtered by e.g. `type`, `common_name`, `issuer`, `device_id`,
|
||||
`virtualmachine_id`, `tenant_id`, `expiration_date__lte` and
|
||||
`expiration_date__gte`.
|
||||
|
||||
## Origin, license and credits
|
||||
|
||||
**Original project:** [NetBox SLM](https://github.com/ICTU/netbox_slm) by **ICTU**
|
||||
(Copyright 2022-2025 ICTU). The original plugin was started by Hedde van der Heide
|
||||
and developed by ICTU and its contributors; [Mart Visser](https://github.com/MartVisser)
|
||||
is named as the contact of the original project. This fork is based on release 1.9.0,
|
||||
and the complete original commit history is retained in this repository.
|
||||
|
||||
**This fork:** maintained by MrBlake at
|
||||
[git.mrblake.cc/MrBlake/NetBox-SLM](https://git.mrblake.cc/MrBlake/NetBox-SLM).
|
||||
It is not affiliated with or endorsed by ICTU. Please report problems with this fork
|
||||
[here](https://git.mrblake.cc/MrBlake/NetBox-SLM/issues), not to the original project.
|
||||
|
||||
Licensed under the [Apache License 2.0](LICENSE). Notices of the original
|
||||
authors are retained.
|
||||
**Main changes compared to the original** (details in [CHANGELOG.md](CHANGELOG.md)):
|
||||
|
||||
- Certificate management with expiry reminders and import from PEM/DER files
|
||||
- Tenant group and tenant assignment for licenses
|
||||
- Renewal intervals, license files, license keys and vendor portal links
|
||||
- License expiry notifications in NetBox and optionally by email
|
||||
- German translation
|
||||
- Support for NetBox 4.6 and 4.7, installation via Git/pip instead of Docker
|
||||
|
||||
**License:** The original work and all modifications are licensed under the
|
||||
[Apache License, Version 2.0](LICENSE). The [NOTICE](NOTICE) file lists the copyright
|
||||
holders. The original copyright and license notices are retained, and every file
|
||||
changed in this fork carries a notice stating that it was modified.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 118 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 97 KiB |
+11
-4
@@ -1,5 +1,6 @@
|
||||
"""
|
||||
Copyright 2022-2025 ICTU
|
||||
Modifications Copyright 2026 MrBlake (NetBox-SLM fork, https://git.mrblake.cc/MrBlake/NetBox-SLM)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
@@ -17,7 +18,7 @@ limitations under the License.
|
||||
from netbox.plugins import PluginConfig
|
||||
from django.utils.translation import gettext, gettext_lazy as _
|
||||
|
||||
__version__ = "1.13.1"
|
||||
__version__ = "1.14.1"
|
||||
|
||||
|
||||
class SLMConfig(PluginConfig):
|
||||
@@ -25,8 +26,7 @@ class SLMConfig(PluginConfig):
|
||||
verbose_name = _("Licences")
|
||||
version = __version__
|
||||
description = _("Licence Management NetBox Plugin.")
|
||||
author = "ICTU"
|
||||
author_email = "[email protected]"
|
||||
author = "ICTU (original), MrBlake (fork)"
|
||||
base_url = "slm"
|
||||
required_settings = []
|
||||
default_settings = {
|
||||
@@ -40,11 +40,18 @@ 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
|
||||
|
||||
from netbox.plugins.registration import register_menu
|
||||
from netbox_slm import navigation
|
||||
|
||||
if hasattr(navigation, "certificate_menu"):
|
||||
register_menu(navigation.certificate_menu)
|
||||
|
||||
|
||||
config = SLMConfig
|
||||
@@ -1,9 +1,19 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from django.core.files.uploadedfile import UploadedFile
|
||||
from rest_framework import serializers
|
||||
from rest_framework.serializers import SerializerMethodField, HyperlinkedIdentityField
|
||||
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.certificate_parser import CertificateParseError, apply_certificate_file
|
||||
from netbox_slm.models import (
|
||||
Certificate,
|
||||
SoftwareProduct,
|
||||
SoftwareProductVersion,
|
||||
SoftwareProductInstallation,
|
||||
SoftwareLicense,
|
||||
)
|
||||
|
||||
|
||||
class SoftwareLicenseSerializer(NetBoxModelSerializer):
|
||||
@@ -58,7 +68,7 @@ class SoftwareLicenseSerializer(NetBoxModelSerializer):
|
||||
if (
|
||||
"email_notifications" in attrs
|
||||
and request is not None
|
||||
and not request.user.has_perm("netbox_slm.manage_softwarelicense_email_notifications")
|
||||
and not request.user.has_perm("netbox_slm.manage_license_emails")
|
||||
):
|
||||
raise serializers.ValidationError(
|
||||
{"email_notifications": _("You do not have permission to change email notifications.")}
|
||||
@@ -185,3 +195,100 @@ 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")
|
||||
extra_kwargs = {"name": {"required": False, "allow_blank": True}}
|
||||
|
||||
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_emails")
|
||||
):
|
||||
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.")}
|
||||
)
|
||||
uploaded_file = attrs.get("certificate_file")
|
||||
if isinstance(uploaded_file, UploadedFile):
|
||||
try:
|
||||
apply_certificate_file(attrs, uploaded_file)
|
||||
except CertificateParseError as error:
|
||||
raise serializers.ValidationError({"certificate_file": str(error)}) from error
|
||||
if not attrs.get("name", getattr(self.instance, "name", "")):
|
||||
raise serializers.ValidationError({"name": _("Enter a name or upload a certificate file.")})
|
||||
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
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from netbox.api.routers import NetBoxRouter
|
||||
from netbox_slm.api.views import (
|
||||
NetboxSLMRootView,
|
||||
@@ -5,6 +7,7 @@ from netbox_slm.api.views import (
|
||||
SoftwareProductVersionViewSet,
|
||||
SoftwareProductInstallationViewSet,
|
||||
SoftwareLicenseViewSet,
|
||||
CertificateViewSet,
|
||||
)
|
||||
|
||||
router = NetBoxRouter()
|
||||
@@ -14,5 +17,6 @@ router.register("softwareproducts", SoftwareProductViewSet)
|
||||
router.register("softwareproductversions", SoftwareProductVersionViewSet)
|
||||
router.register("softwareproductinstallations", SoftwareProductInstallationViewSet)
|
||||
router.register("softwarelicenses", SoftwareLicenseViewSet)
|
||||
router.register("certificates", CertificateViewSet)
|
||||
|
||||
urlpatterns = router.urls
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from rest_framework.routers import APIRootView
|
||||
|
||||
from netbox.api.viewsets import NetBoxModelViewSet
|
||||
@@ -6,18 +8,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 +53,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
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Extract metadata from uploaded X.509 certificate files (PEM or DER)."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
class CertificateParseError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class CertificateInfo:
|
||||
common_name: str = ""
|
||||
subject_alternative_names: list[str] = field(default_factory=list)
|
||||
issuer: str = ""
|
||||
serial_number: str = ""
|
||||
fingerprint: str = ""
|
||||
start_date: date | None = None
|
||||
expiration_date: date | None = None
|
||||
type: str = ""
|
||||
|
||||
|
||||
def _common_name(name):
|
||||
attributes = name.get_attributes_for_oid(NameOID.COMMON_NAME)
|
||||
return str(attributes[0].value) if attributes else ""
|
||||
|
||||
|
||||
def _format_hex(data):
|
||||
return ":".join(f"{byte:02X}" for byte in data)
|
||||
|
||||
|
||||
def _serial_bytes(serial):
|
||||
return serial.to_bytes((serial.bit_length() + 7) // 8 or 1, "big")
|
||||
|
||||
|
||||
def _guess_type(certificate):
|
||||
# Values match netbox_slm.models.CertificateTypes
|
||||
try:
|
||||
if certificate.extensions.get_extension_for_class(x509.BasicConstraints).value.ca:
|
||||
return "ca"
|
||||
except x509.ExtensionNotFound:
|
||||
pass
|
||||
try:
|
||||
usages = set(certificate.extensions.get_extension_for_class(x509.ExtendedKeyUsage).value)
|
||||
except x509.ExtensionNotFound:
|
||||
return ""
|
||||
for oid, value in (
|
||||
(ExtendedKeyUsageOID.SERVER_AUTH, "server"),
|
||||
(ExtendedKeyUsageOID.CODE_SIGNING, "code_signing"),
|
||||
(ExtendedKeyUsageOID.EMAIL_PROTECTION, "email"),
|
||||
(ExtendedKeyUsageOID.CLIENT_AUTH, "client"),
|
||||
):
|
||||
if oid in usages:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def parse_certificate(data: bytes) -> CertificateInfo:
|
||||
"""Parse the first certificate of a PEM or DER file. Files containing private keys are rejected."""
|
||||
if b"PRIVATE KEY" in data:
|
||||
raise CertificateParseError(
|
||||
_("The file contains a private key. Please upload only the certificate without its private key.")
|
||||
)
|
||||
try:
|
||||
if b"-----BEGIN CERTIFICATE-----" in data:
|
||||
certificate = x509.load_pem_x509_certificates(data)[0]
|
||||
else:
|
||||
certificate = x509.load_der_x509_certificate(data)
|
||||
except ValueError as error:
|
||||
raise CertificateParseError(
|
||||
_("The file is not a valid PEM or DER encoded X.509 certificate.")
|
||||
) from error
|
||||
|
||||
sans = []
|
||||
try:
|
||||
extension = certificate.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
|
||||
sans += extension.get_values_for_type(x509.DNSName)
|
||||
sans += [str(address) for address in extension.get_values_for_type(x509.IPAddress)]
|
||||
except x509.ExtensionNotFound:
|
||||
pass
|
||||
|
||||
issuer = _common_name(certificate.issuer) or certificate.issuer.rfc4514_string()
|
||||
return CertificateInfo(
|
||||
common_name=_common_name(certificate.subject),
|
||||
subject_alternative_names=sans,
|
||||
issuer=issuer[:255],
|
||||
serial_number=_format_hex(_serial_bytes(certificate.serial_number)),
|
||||
fingerprint=_format_hex(certificate.fingerprint(hashes.SHA256())),
|
||||
start_date=certificate.not_valid_before_utc.date(),
|
||||
expiration_date=certificate.not_valid_after_utc.date(),
|
||||
type=_guess_type(certificate),
|
||||
)
|
||||
|
||||
|
||||
def apply_certificate_file(values: dict, uploaded_file) -> None:
|
||||
"""
|
||||
Fill certificate fields in ``values`` (form cleaned_data or serializer attrs) from an uploaded file.
|
||||
|
||||
Fields derived from the certificate are overwritten so they always match the uploaded file. Name and type
|
||||
are only set when they were left empty.
|
||||
"""
|
||||
uploaded_file.seek(0)
|
||||
info = parse_certificate(uploaded_file.read())
|
||||
uploaded_file.seek(0)
|
||||
|
||||
values["common_name"] = info.common_name
|
||||
values["subject_alternative_names"] = "\n".join(info.subject_alternative_names)
|
||||
values["issuer"] = info.issuer
|
||||
values["serial_number"] = info.serial_number
|
||||
values["fingerprint"] = info.fingerprint
|
||||
values["start_date"] = info.start_date
|
||||
values["expiration_date"] = info.expiration_date
|
||||
if not values.get("name"):
|
||||
values["name"] = info.common_name or info.fingerprint[:23]
|
||||
if not values.get("type") and info.type:
|
||||
values["type"] = info.type
|
||||
@@ -1 +1,2 @@
|
||||
LICENSE_EXPIRING = "netbox_slm_license_expiring"
|
||||
CERTIFICATE_EXPIRING = "netbox_slm_certificate_expiring"
|
||||
@@ -1,6 +1,8 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
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 +12,8 @@ from netbox_slm.models import (
|
||||
SoftwareProductInstallation,
|
||||
SoftwareLicense,
|
||||
SoftwareReleaseTypes,
|
||||
Certificate,
|
||||
CertificateTypes,
|
||||
RenewalIntervalUnits,
|
||||
)
|
||||
from virtualization.models import Cluster, VirtualMachine
|
||||
@@ -151,3 +155,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)
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from .software_license import (
|
||||
SoftwareLicenseForm,
|
||||
SoftwareLicenseFilterForm,
|
||||
@@ -22,3 +24,9 @@ from .software_product_version import (
|
||||
SoftwareProductVersionBulkImportForm,
|
||||
SoftwareProductVersionBulkEditForm,
|
||||
)
|
||||
from .certificate import (
|
||||
CertificateForm,
|
||||
CertificateFilterForm,
|
||||
CertificateBulkImportForm,
|
||||
CertificateBulkEditForm,
|
||||
)
|
||||
@@ -0,0 +1,330 @@
|
||||
from django.core.files.uploadedfile import UploadedFile
|
||||
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.certificate_parser import CertificateParseError, apply_certificate_file
|
||||
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()
|
||||
name = CharField(
|
||||
required=False,
|
||||
max_length=128,
|
||||
label=_("Name"),
|
||||
help_text=_("Taken from the certificate's common name if left empty"),
|
||||
)
|
||||
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"),
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["certificate_file"].help_text = _(
|
||||
"PEM or DER file without private key. Common name, SANs, issuer, serial number, fingerprint and "
|
||||
"validity are filled in automatically."
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
# NetBox form mixins may return None from clean(), so always use self.cleaned_data
|
||||
super().clean()
|
||||
cleaned_data = self.cleaned_data
|
||||
uploaded_file = cleaned_data.get("certificate_file")
|
||||
if isinstance(uploaded_file, UploadedFile):
|
||||
try:
|
||||
apply_certificate_file(cleaned_data, uploaded_file)
|
||||
except CertificateParseError as error:
|
||||
self.add_error("certificate_file", error)
|
||||
if not cleaned_data.get("name") and "name" not in self.errors:
|
||||
self.add_error("name", _("Enter a name or upload a certificate file."))
|
||||
return cleaned_data
|
||||
|
||||
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"),
|
||||
)
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from django.forms import CharField, DateField, ChoiceField, IntegerField, NullBooleanField, Textarea
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from django.forms import CharField
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from django.forms import ValidationError
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from django.forms import DateField, CharField, MultipleChoiceField
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
+102
-43
@@ -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.
@@ -417,3 +417,147 @@ 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"
|
||||
|
||||
msgid "Taken from the certificate's common name if left empty"
|
||||
msgstr "Wird aus dem Common Name des Zertifikats übernommen, wenn leer"
|
||||
|
||||
msgid "Enter a name or upload a certificate file."
|
||||
msgstr "Bitte einen Namen eingeben oder eine Zertifikatsdatei hochladen."
|
||||
|
||||
msgid "PEM or DER file without private key. Common name, SANs, issuer, serial number, fingerprint and validity are filled in automatically."
|
||||
msgstr "PEM- oder DER-Datei ohne privaten Schlüssel. Common Name, SANs, Aussteller, Seriennummer, Fingerabdruck und Gültigkeit werden automatisch ausgefüllt."
|
||||
|
||||
msgid "The file contains a private key. Please upload only the certificate without its private key."
|
||||
msgstr "Die Datei enthält einen privaten Schlüssel. Bitte nur das Zertifikat ohne privaten Schlüssel hochladen."
|
||||
|
||||
msgid "The file is not a valid PEM or DER encoded X.509 certificate."
|
||||
msgstr "Die Datei ist kein gültiges PEM- oder DER-kodiertes X.509-Zertifikat."
|
||||
@@ -0,0 +1,177 @@
|
||||
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),
|
||||
("netbox_slm", "0015_platform_constraint_message"),
|
||||
]
|
||||
|
||||
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",
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
from django.db import migrations
|
||||
|
||||
# NetBox ObjectPermission actions are limited to 30 characters.
|
||||
RENAMES = [
|
||||
("softwarelicense", "manage_softwarelicense_email_notifications", "manage_license_emails"),
|
||||
("certificate", "manage_certificate_email_notifications", "manage_certificate_emails"),
|
||||
]
|
||||
|
||||
|
||||
def rename_permissions(apps, schema_editor, reverse=False):
|
||||
Permission = apps.get_model("auth", "Permission")
|
||||
for model, old, new in RENAMES:
|
||||
if reverse:
|
||||
old, new = new, old
|
||||
Permission.objects.filter(content_type__app_label="netbox_slm", content_type__model=model, codename=old).update(
|
||||
codename=new
|
||||
)
|
||||
|
||||
|
||||
def reverse_rename_permissions(apps, schema_editor):
|
||||
rename_permissions(apps, schema_editor, reverse=True)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("auth", "0001_initial"),
|
||||
("netbox_slm", "0016_certificate"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name="softwarelicense",
|
||||
options={
|
||||
"permissions": [("manage_license_emails", "Can manage license email notifications")],
|
||||
"verbose_name": "software license",
|
||||
"verbose_name_plural": "software licenses",
|
||||
},
|
||||
),
|
||||
migrations.AlterModelOptions(
|
||||
name="certificate",
|
||||
options={
|
||||
"permissions": [("manage_certificate_emails", "Can manage certificate email notifications")],
|
||||
"verbose_name": "certificate",
|
||||
"verbose_name_plural": "certificates",
|
||||
},
|
||||
),
|
||||
migrations.RunPython(rename_permissions, reverse_rename_permissions),
|
||||
]
|
||||
+201
-50
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
import calendar
|
||||
from datetime import timedelta
|
||||
|
||||
@@ -68,6 +70,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 +188,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 +263,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 +288,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
|
||||
@@ -268,7 +329,7 @@ class SoftwareLicense(NetBoxModel):
|
||||
verbose_name = _("software license")
|
||||
verbose_name_plural = _("software licenses")
|
||||
permissions = [
|
||||
("manage_softwarelicense_email_notifications", _("Can manage license email notifications")),
|
||||
("manage_license_emails", _("Can manage license email notifications")),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
@@ -291,43 +352,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 +381,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_emails", _("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",
|
||||
)
|
||||
]
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from netbox.plugins import PluginMenuButton, PluginMenuItem, PluginMenu, get_plugin_config
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from . import SLMConfig
|
||||
@@ -81,12 +83,40 @@ slm_items = (
|
||||
),
|
||||
)
|
||||
|
||||
certificate_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"):
|
||||
menu = PluginMenu(
|
||||
label=_("Licences"),
|
||||
groups=((SLMConfig.verbose_name, slm_items),),
|
||||
icon_class="mdi mdi-content-save",
|
||||
)
|
||||
# NetBox loads only one menu per plugin; this one is registered in SLMConfig.ready()
|
||||
certificate_menu = PluginMenu(
|
||||
label=_("Certificates"),
|
||||
groups=((_("Certificates"), certificate_items),),
|
||||
icon_class="mdi mdi-certificate",
|
||||
)
|
||||
else:
|
||||
# auto imported by default PluginConfig.menu_items = navigation.menu_items
|
||||
menu_items = slm_items
|
||||
menu_items = slm_items + certificate_items
|
||||
+71
-1
@@ -1,9 +1,17 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
import django_tables2 as tables
|
||||
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 +203,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 %}
|
||||
@@ -1,3 +1,5 @@
|
||||
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
|
||||
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
|
||||
{% load helpers %}
|
||||
{% load i18n %}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
|
||||
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
|
||||
{% extends 'generic/object.html' %}
|
||||
{% load buttons %}
|
||||
{% load static %}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
|
||||
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
|
||||
{% extends 'generic/object.html' %}
|
||||
{% load buttons %}
|
||||
{% load static %}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
|
||||
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
|
||||
{% extends 'generic/object.html' %}
|
||||
{% load buttons %}
|
||||
{% load static %}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
|
||||
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
|
||||
{% extends 'generic/object.html' %}
|
||||
{% load buttons %}
|
||||
{% load static %}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from django.test import TestCase
|
||||
|
||||
from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Site
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from datetime import date, timedelta
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
@@ -10,8 +12,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 +212,118 @@ 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_certificate_form_fills_fields_from_uploaded_file(self):
|
||||
import datetime
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
|
||||
from netbox_slm.forms import CertificateForm
|
||||
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "upload.example.com")])
|
||||
certificate = (
|
||||
x509.CertificateBuilder()
|
||||
.subject_name(name)
|
||||
.issuer_name(name)
|
||||
.public_key(key.public_key())
|
||||
.serial_number(1234)
|
||||
.not_valid_before(datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC))
|
||||
.not_valid_after(datetime.datetime(2027, 1, 1, tzinfo=datetime.UTC))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName("upload.example.com")]), critical=False)
|
||||
.sign(key, hashes.SHA256())
|
||||
)
|
||||
upload = SimpleUploadedFile("cert.pem", certificate.public_bytes(serialization.Encoding.PEM))
|
||||
|
||||
form = CertificateForm(data={}, files={"certificate_file": upload})
|
||||
form.is_valid()
|
||||
|
||||
self.assertNotIn("name", form.errors)
|
||||
self.assertNotIn("certificate_file", form.errors)
|
||||
self.assertEqual("upload.example.com", form.cleaned_data["name"])
|
||||
self.assertEqual("upload.example.com", form.cleaned_data["subject_alternative_names"])
|
||||
self.assertEqual(datetime.date(2027, 1, 1), form.cleaned_data["expiration_date"])
|
||||
|
||||
def test_certificate_form_rejects_private_key(self):
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
|
||||
from netbox_slm.forms import CertificateForm
|
||||
|
||||
upload = SimpleUploadedFile("key.pem", b"-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n")
|
||||
form = CertificateForm(data={"name": "with key"}, files={"certificate_file": upload})
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertIn("certificate_file", form.errors)
|
||||
|
||||
def test_german_translation(self):
|
||||
with override("de"):
|
||||
self.assertEqual("Zertifikate", gettext("Certificates"))
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from django.urls import path, include
|
||||
|
||||
from netbox_slm import views # noqa F401
|
||||
@@ -12,4 +14,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"))),
|
||||
]
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from .software_license import (
|
||||
SoftwareLicenseListView,
|
||||
SoftwareLicenseView,
|
||||
@@ -30,3 +32,11 @@ from .software_product_version import (
|
||||
SoftwareProductVersionBulkDeleteView,
|
||||
SoftwareProductVersionBulkImportView,
|
||||
)
|
||||
from .certificate import (
|
||||
CertificateListView,
|
||||
CertificateView,
|
||||
CertificateEditView,
|
||||
CertificateDeleteView,
|
||||
CertificateBulkDeleteView,
|
||||
CertificateBulkImportView,
|
||||
)
|
||||
@@ -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_emails"
|
||||
|
||||
|
||||
@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
|
||||
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
from netbox.views import generic
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from netbox_slm import filtersets, forms, tables
|
||||
@@ -8,7 +10,7 @@ from utilities.views import register_model_view
|
||||
class EmailNotificationPermissionMixin:
|
||||
"""Prevent users without the dedicated permission from changing SMTP delivery."""
|
||||
|
||||
email_permission = "netbox_slm.manage_softwarelicense_email_notifications"
|
||||
email_permission = "netbox_slm.manage_license_emails"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
form_attribute = "model_form" if hasattr(self, "model_form") else "form"
|
||||
|
||||
+10
-3
@@ -1,3 +1,5 @@
|
||||
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
|
||||
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
|
||||
[build-system]
|
||||
requires = ["setuptools"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
@@ -12,6 +14,9 @@ license = { text = "Apache-2.0" }
|
||||
authors = [
|
||||
{name = "ICTU", email = "[email protected]"},
|
||||
]
|
||||
maintainers = [
|
||||
{name = "MrBlake"},
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Environment :: Plugins",
|
||||
@@ -32,6 +37,7 @@ classifiers = [
|
||||
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
|
||||
]
|
||||
dependencies = [
|
||||
"cryptography >= 41.0",
|
||||
"license-expression == 30.4.4",
|
||||
]
|
||||
|
||||
@@ -47,9 +53,10 @@ ci = [
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/ICTU/netbox_slm/"
|
||||
Changelog = "https://github.com/ICTU/netbox_slm/blob/master/CHANGELOG.md"
|
||||
Issues = "https://github.com/ICTU/netbox_slm/issues/"
|
||||
Homepage = "https://git.mrblake.cc/MrBlake/NetBox-SLM"
|
||||
Changelog = "https://git.mrblake.cc/MrBlake/NetBox-SLM/src/branch/master/CHANGELOG.md"
|
||||
Issues = "https://git.mrblake.cc/MrBlake/NetBox-SLM/issues"
|
||||
Upstream = "https://github.com/ICTU/netbox_slm"
|
||||
|
||||
[tool.setuptools.dynamic]
|
||||
version = {attr = "netbox_slm.__version__"}
|
||||
|
||||
Reference in new issue
Block a user