Skip to content

Commit

Permalink
add pydocstring checks
Browse files Browse the repository at this point in the history
  • Loading branch information
mathiasertl committed Sep 9, 2023
1 parent c73d6f4 commit 429ca3c
Show file tree
Hide file tree
Showing 99 changed files with 119 additions and 449 deletions.
2 changes: 1 addition & 1 deletion ca/django_ca/acme/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ class AcmeResponseNotFound(AcmeResponseError):


class AcmeResponseBadNonce(AcmeResponseError):
"""
"""ACME response when a bad nonce was submitted.
.. seealso:: RFC 8555, section 6.5:
Expand Down
1 change: 0 additions & 1 deletion ca/django_ca/acme/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ def parse_acme_csr(value: str) -> x509.CertificateSigningRequest:
Returns
-------
:py:class:`~cg:cryptography.x509.CertificateSigningRequest`
The CSR as used by cryptography.
"""
Expand Down
9 changes: 2 additions & 7 deletions ca/django_ca/acme/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ class ContactValidationMixin:

def validate_contacts(self, message: messages.Registration) -> None:
"""Validate the contact information for this message."""

for contact in message.contact:
if contact.startswith(messages.Registration.email_prefix):
addr = contact[len(messages.Registration.email_prefix) :]
Expand Down Expand Up @@ -135,7 +134,7 @@ def validate_contacts(self, message: messages.Registration) -> None:

class AcmeDirectory(View):
"""
`Equivalent LE URL <https://acme-v02.api.letsencrypt.org/directory>`__
`Equivalent LE URL <https://acme-v02.api.letsencrypt.org/directory>`__.
.. seealso:: `RFC 8555, section 7.1.1 <https://tools.ietf.org/html/rfc8555#section-7.1.1>`_
"""
Expand Down Expand Up @@ -205,7 +204,6 @@ def get_cache_key(self, nonce: str) -> str:

def get_nonce(self) -> str:
"""Get a random Nonce and add it to the cache."""

data = secrets.token_bytes(self.nonce_length)
nonce = jose.json_util.encode_b64jose(data)
cache.set(self.get_cache_key(nonce), 0)
Expand Down Expand Up @@ -277,7 +275,6 @@ def set_link_relations(self, response: "HttpResponseBase", **kwargs: str) -> Non
.. seealso:: https://tools.ietf.org/html/rfc8288
"""

kwargs["index"] = reverse("django_ca:acme-directory", kwargs={"serial": self.kwargs["serial"]})
response["Link"] = ", ".join(
f'<{self.request.build_absolute_uri(v)}>;rel="{k}"' for k, v in kwargs.items()
Expand Down Expand Up @@ -672,7 +669,7 @@ def acme_request(self, message: messages.Registration, slug: Optional[str] = Non


class AcmeAccountOrdersView(AcmeBaseView):
"""View showing orders for an account (not yet implemented)"""
"""View showing orders for an account (not yet implemented)."""

# TODO: implement this view
def process_acme_request(self, slug: Optional[str]) -> AcmeResponse: # pragma: no cover
Expand Down Expand Up @@ -817,7 +814,6 @@ class AcmeOrderFinalizeView(AcmeMessageBaseView[CertificateRequest]):

def validate_csr(self, message: CertificateRequest, authorizations: Iterable[AcmeAuthorization]) -> str:
"""Parse and validate the CSR, returns the PEM as str."""

# Note: Jose wraps the CSR in a josepy.util.ComparableX509, that has *no* public member methods.
# The only public attribute or function is the wrapped object. We encode it back to get the regular
# PEM.
Expand Down Expand Up @@ -1096,7 +1092,6 @@ def get_certificate(self, serial: str) -> Certificate:
This function handles the special authorization requirements for this request (they can be signed by
either the account key pair or the certificate key pair).
"""

certs = Certificate.objects.filter(ca=self.ca).currently_valid()

# If the request is signed with the certificate key (and not the account), a JWK is set for this
Expand Down
11 changes: 3 additions & 8 deletions ca/django_ca/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,10 @@ def _download_response(self, request: HttpRequest, pk: int, bundle: bool = False

def download_view(self, request: HttpRequest, pk: int) -> HttpResponse:
"""A view that allows the user to download a certificate in PEM or DER/ASN1 format."""

return self._download_response(request, pk)

def download_bundle_view(self, request: HttpRequest, pk: int) -> HttpResponse:
"""A view that allows the user to download a certificate bundle in PEM format."""

return self._download_response(request, pk, bundle=True)

@property
Expand All @@ -210,7 +208,6 @@ def profiles_view_name(self) -> str:

def profiles_view(self, request: HttpRequest) -> JsonResponse:
"""Returns profiles."""

if not self.has_change_permission(request):
# NOTE: is_staff/is_active is checked by self.admin_site.admin_view()
raise PermissionDenied
Expand Down Expand Up @@ -273,7 +270,6 @@ def get_search_results(

def output_template(self, obj: X509CertMixinTypeVar, oid: x509.ObjectIdentifier) -> str:
"""Render extension for the given object."""

ext = obj.x509_extensions.get(oid)

if ext is None:
Expand Down Expand Up @@ -762,7 +758,8 @@ def get_form( # type: ignore[override] # pylint: disable=unused-argument
def get_changeform_initial_data(self, request: HttpRequest) -> Dict[str, Any]:
"""Get initial data based on default profile.
When resigning a certificate, get initial data from the certificate."""
When resigning a certificate, get initial data from the certificate.
"""
data: Dict[str, Any] = super().get_changeform_initial_data(request)

hash_algorithm_name = ""
Expand Down Expand Up @@ -870,7 +867,6 @@ def csr_details_view_name(self) -> str:

def csr_details_view(self, request: HttpRequest) -> JsonResponse:
"""Returns details of a CSR request."""

if not request.user.is_staff or not self.has_change_permission(request):
# NOTE: is_staff is already assured by ModelAdmin, but just to be sure
raise PermissionDenied
Expand Down Expand Up @@ -911,7 +907,6 @@ def get_urls(self) -> List[URLPattern]:

def resign(self, request: HttpRequest, obj: Certificate) -> HttpResponse:
"""View for resigning an existing certificate."""

if not self.has_view_permission(request, obj) or not self.has_add_permission(request):
# NOTE: is_staff/is_active is checked by self.admin_site.admin_view()
raise PermissionDenied
Expand Down Expand Up @@ -1173,7 +1168,7 @@ class AcmeAccountAdmin(AcmeAccountAdminBase):
search_fields = ("contact",)

def first_contact(self, obj: AcmeAccount) -> str:
"""return the first contact address."""
"""Return the first contact address."""
return str(obj)

first_contact.short_description = _("Contact") # type: ignore[attr-defined] # django standard
Expand Down
1 change: 0 additions & 1 deletion ca/django_ca/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ class BasicAuth(HttpBasicAuth):
Parameters
----------
permission : str
The permission that the user needs to have in order to pass authn/authz checks.
"""
Expand Down
4 changes: 2 additions & 2 deletions ca/django_ca/api/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@


class NameAttributeSchema(Schema):
"""docstring for class"""
"""docstring for class."""

oid: str = Field(
title="OID",
Expand Down Expand Up @@ -79,7 +79,7 @@ def resolve_created(obj: X509CertMixin) -> datetime:

@staticmethod
def resolve_pem(obj: X509CertMixin) -> str:
"""Convert the public certificate to its PEM format"""
"""Convert the public certificate to its PEM format."""
return obj.pub.pem

@staticmethod
Expand Down
1 change: 0 additions & 1 deletion ca/django_ca/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ def create_api_user(
Parameters
----------
username : str
The username for the API user.
password : str
Expand Down
1 change: 0 additions & 1 deletion ca/django_ca/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
@checks.register(checks.Tags.caches, deploy=True) # type: ignore[type-var]
def check_cache(app_configs: Optional[List[AppConfig]], **kwargs: Any) -> List[checks.CheckMessage]:
"""Check that a cache is configured and issue a warning if the cache is not a shared cache."""

# only run checks if manage.py check is run with no app labels (== all) or the django_ca app label
if app_configs is not None and not [config for config in app_configs if config.name == "django_ca"]:
return []
Expand Down
4 changes: 2 additions & 2 deletions ca/django_ca/extensions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"""Extension classes wrapping various X.509 extensions.
The classes in this module wrap cryptography extensions, but allow adding/removing values, creating extensions
in a more pythonic manner and provide access functions."""
in a more pythonic manner and provide access functions.
"""

from cryptography import x509
from cryptography.hazmat._oid import _OID_NAMES as OID_NAMES
Expand Down Expand Up @@ -52,7 +53,6 @@ def get_extension_name(oid: x509.ObjectIdentifier) -> str:
'Unknown extension (1.2.3)'
"""

if oid in EXTENSION_NAMES:
return EXTENSION_NAMES[oid]

Expand Down
1 change: 0 additions & 1 deletion ca/django_ca/extensions/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,6 @@ def serialize_extension(extension: x509.Extension[x509.ExtensionType]) -> Serial
This is the inverse of :py:func:`~django_ca.extensions.parse_extension` and is used to serialize
extension information for API calls in the admin interface.
"""

value = _serialize_extension(extension.value)
serialized: SerializedExtension = {"critical": extension.critical, "value": value}
return serialized
1 change: 0 additions & 1 deletion ca/django_ca/extensions/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ def extension_as_admin_html(
extension: x509.Extension[x509.ExtensionType], extra_context: Optional[Dict[str, Any]] = None
) -> str:
"""Convert an extension to HTML code suitable for the admin interface."""

template = f"django_ca/admin/extensions/{extension.oid.dotted_string}.html"
if isinstance(extension.value, x509.UnrecognizedExtension):
template = "django_ca/admin/extensions/unrecognized_extension.html"
Expand Down
3 changes: 2 additions & 1 deletion ca/django_ca/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ class Meta:
class CreateCertificateBaseForm(CertificateModelForm):
"""Base class for forms that create a certificate.
This is used by forms for creating a new certificate and resigning an existing one."""
This is used by forms for creating a new certificate and resigning an existing one.
"""

password = forms.CharField(
widget=forms.PasswordInput,
Expand Down
2 changes: 0 additions & 2 deletions ca/django_ca/management/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ def parse_value(self, value: ParseType) -> ActionType:
Parameters
----------
value : str
The value passed by the command line.
"""
Expand Down Expand Up @@ -221,7 +220,6 @@ class IntegerRangeAction(SingleValueAction[int, int]):
Parameters
----------
min: int, Optional
The optional minimum value.
max: int, Optional
Expand Down
6 changes: 1 addition & 5 deletions ca/django_ca/management/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ def execute(self, *args: Any, **options: Any) -> None:

def dump(self, path: str, data: bytes) -> None:
"""Dump `data` to `path` (``-`` means stdout)."""

if path == "-":
self.stdout.write(data, ending=b"")
else:
Expand Down Expand Up @@ -366,7 +365,6 @@ def add_subject_alternative_name_group(
additional_option_strings: Tuple[str, ...] = tuple(),
) -> None:
"""Add argument group for the Subject Alternative Name extension."""

ext_name = constants.EXTENSION_NAMES[ExtensionOID.SUBJECT_ALTERNATIVE_NAME]
description = "This extension lists the names (usually domain names) that a certificate is valid for."
if description_suffix:
Expand Down Expand Up @@ -463,7 +461,6 @@ def add_ocsp_no_check_group(self, parser: CommandParser) -> None:

def add_subject_group(self, parser: CommandParser) -> None:
"""Add argument for a subject."""

group = parser.add_argument_group("Certificate subject", self.subject_help)

# NOTE: Don't set the default value here because it would mask the user not setting anything at all.
Expand All @@ -484,7 +481,6 @@ def test_options( # pylint: disable=unused-argument
**options: Any,
) -> None:
"""Additional tests for validity of some options."""

parsed_expires = profile.get_expires(expires)

if ca.expires < parsed_expires:
Expand Down Expand Up @@ -536,7 +532,7 @@ def wrap_digest(self, algorithm: str, text: str) -> str:
return "\n".join(lines)

def output_status(self, cert: X509CertMixin) -> None:
"""Output certificate status"""
"""Output certificate status."""
now = datetime.now(tz.utc)
if cert.revoked:
self.stdout.write("* Status: Revoked")
Expand Down
2 changes: 0 additions & 2 deletions ca/django_ca/management/commands/list_cas.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ def qs(self, qs: CertificateAuthorityQuerySet) -> CertificateAuthorityQuerySet:

def list_ca(self, ca: CertificateAuthority, indent: str = "") -> None:
"""Output list line for a given CA."""

text = f"{indent}{add_colons(ca.serial)} - {ca.name}"
if ca.enabled is False:
text += " (disabled)"
Expand All @@ -49,7 +48,6 @@ def list_ca(self, ca: CertificateAuthority, indent: str = "") -> None:

def list_children(self, ca: CertificateAuthority, indent: str = "") -> None:
"""Output list lines for children of the given CA."""

children = list(enumerate(self.qs(ca.children.all()), 1))
for index, child in children:
if index == len(children): # last element
Expand Down
7 changes: 0 additions & 7 deletions ca/django_ca/management/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ def add_ca(
Parameters
----------
parser
arg : str, optional
help_text : str, optional
Expand Down Expand Up @@ -97,7 +96,6 @@ def add_ca(

def add_format(self, parser: CommandParser) -> None:
"""Add the -f/--format option."""

parser.add_argument(
"-f",
"--format",
Expand Down Expand Up @@ -133,7 +131,6 @@ def get_hash_algorithm(

def print_extension(self, ext: x509.Extension[x509.ExtensionType]) -> None:
"""Print extension to stdout."""

ext_name = get_extension_name(ext.oid)
if ext.critical:
self.stdout.write(f"* {ext_name} (critical):")
Expand Down Expand Up @@ -181,13 +178,11 @@ def add_general_args(self, parser: CommandParser, default: Optional[str] = "") -
Parameters
----------
parser : CommandParser
default : str, optional
Default value for arguments. Pass ``None`` if you want to be able to know if the value was passed
or not.
"""

group = parser.add_argument_group("General", "General information about the CA.")
group.add_argument("--caa", default=default, metavar="NAME", help="CAA record for this CA.")
group.add_argument(
Expand All @@ -208,7 +203,6 @@ def add_general_args(self, parser: CommandParser, default: Optional[str] = "") -

def add_acme_group(self, parser: CommandParser) -> None:
"""Add arguments for ACMEv2."""

if not ca_settings.CA_ENABLE_ACME:
return

Expand Down Expand Up @@ -287,7 +281,6 @@ def add_ocsp_group(self, parser: CommandParser) -> None:

def add_ca_args(self, parser: ActionsContainer) -> None:
"""Add CA arguments."""

group = parser.add_argument_group(
"X509 v3 certificate extensions for signed certificates",
"Extensions added when signing certificates.",
Expand Down
4 changes: 0 additions & 4 deletions ca/django_ca/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,6 @@ def init(
Parameters
----------
name : str
The name of the CA. This is a human-readable string and is used for administrative purposes only.
subject : :py:class:`cg:cryptography.x509.Name`
Expand Down Expand Up @@ -344,7 +343,6 @@ def init(
Raises
------
ValueError
For various cases of wrong input data (e.g. ``key_size`` not being the power of two).
PermissionError
Expand Down Expand Up @@ -584,7 +582,6 @@ def create_cert( # pylint: disable=too-many-arguments
Parameters
----------
ca : :py:class:`~django_ca.models.CertificateAuthority`
The certificate authority to sign the certificate with.
csr : :py:class:`~cg:cryptography.x509.CertificateSigningRequest`
Expand Down Expand Up @@ -619,7 +616,6 @@ def create_cert( # pylint: disable=too-many-arguments
password : bool, optional
Passed to :py:func:`Profiles.create_cert() <django_ca.profiles.Profile.create_cert>`.
"""

# Get the profile object if none was passed
if profile is None:
profile = profiles[None]
Expand Down
Loading

0 comments on commit 429ca3c

Please sign in to comment.