authentik.lib.validators

Serializer validators

  1"""Serializer validators"""
  2
  3from typing import Any
  4
  5from django.conf import settings
  6from django.contrib.auth.hashers import (
  7    Argon2PasswordHasher,
  8    BasePasswordHasher,
  9    BCryptSHA256PasswordHasher,
 10    PBKDF2PasswordHasher,
 11    ScryptPasswordHasher,
 12    identify_hasher,
 13    must_update_salt,
 14)
 15from django.utils.module_loading import import_string
 16from django.utils.translation import gettext_lazy as _
 17from rest_framework.exceptions import ValidationError
 18from rest_framework.serializers import Serializer
 19from rest_framework.utils.representation import smart_repr
 20
 21
 22class PasswordHashRequiresOverride(ValidationError):
 23    """A valid password hash that does not match the current import defaults."""
 24
 25
 26class PasswordHashValidator:
 27    """Validate a Django password hash."""
 28
 29    def __init__(self, strict: bool = True):
 30        self.strict = strict
 31
 32    def __call__(self, password_hash: str) -> None:
 33        # 1. Validate hash function
 34        allowed_algorithms = [
 35            import_string(path)().algorithm for path in settings.PASSWORD_HASHERS_IMPORT_ALLOWED
 36        ]
 37        try:
 38            hasher = identify_hasher(password_hash)
 39        except ValueError as exc:
 40            raise ValidationError(
 41                "Cannot identify hash function. "
 42                f"Password hash must use one of: {", ".join(allowed_algorithms)}."
 43            ) from exc
 44        if self.strict and hasher.algorithm not in allowed_algorithms:
 45            raise PasswordHashRequiresOverride(
 46                f"Hash function {hasher.algorithm} not allowed. "
 47                f"Password hash must use one of: {", ".join(allowed_algorithms)}."
 48            )
 49
 50        # 2. Validate hash
 51        try:
 52            decoded = hasher.decode(password_hash)
 53        # `AssertionError` is here because Django is stupid. "default$1$2$3" triggers it.
 54        except (AssertionError, ValueError) as exc:
 55            raise ValidationError("Password hash could not be decoded.") from exc
 56
 57        if not self.strict:
 58            return
 59        # Django decides whether the hash needs an update, we only explain why
 60        if not hasher.must_update(password_hash):
 61            return
 62        messages: list[str] = []
 63
 64        # 3. Validate salt
 65        if must_update_salt(decoded["salt"], hasher.salt_entropy):
 66            messages.append(
 67                "Password salt seems not to meet the current requirement of "
 68                f"{hasher.salt_entropy} bits of entropy."
 69            )
 70
 71        # 4. Validate parameters
 72        current = self.current_parameters(hasher)
 73        provided = {name: decoded[name] for name in current}
 74        # If it's not the salt, it's the parameters, even unlisted ones (e.g. argon2's hash length)
 75        if provided != current or not messages:
 76            messages.append(
 77                "Password hash parameters do not match authentik's current settings. "
 78                f"Provided: {provided}. Expected: {current}."
 79            )
 80
 81        raise PasswordHashRequiresOverride(messages)
 82
 83    @classmethod
 84    def current_parameters(cls, hasher: BasePasswordHasher) -> dict[str, Any]:
 85        if isinstance(hasher, PBKDF2PasswordHasher):
 86            return {"iterations": hasher.iterations}
 87        if isinstance(hasher, Argon2PasswordHasher):
 88            params = hasher.params()
 89            return {
 90                "variety": f"argon2{params.type.name.lower()}",
 91                "version": params.version,
 92                "memory_cost": params.memory_cost,
 93                "time_cost": params.time_cost,
 94                "parallelism": params.parallelism,
 95            }
 96        if isinstance(hasher, BCryptSHA256PasswordHasher):
 97            return {"work_factor": hasher.rounds}
 98        if isinstance(hasher, ScryptPasswordHasher):
 99            return {
100                "block_size": hasher.block_size,
101                "parallelism": hasher.parallelism,
102                "work_factor": hasher.work_factor,
103            }
104        raise ValueError(f"Unsupported password hasher: {hasher.algorithm}")
105
106
107class RequiredTogetherValidator:
108    """Serializer-level validator that ensures all fields in `fields` are only
109    used together"""
110
111    fields: list[str]
112    requires_context = True
113    message = _("The fields {field_names} must be used together.")
114
115    def __init__(self, fields: list[str], message: str | None = None) -> None:
116        self.fields = fields
117        self.message = message or self.message
118
119    def __call__(self, attrs: dict, serializer: Serializer):
120        """Check that if any of the fields in `self.fields` are set, all of them must be set"""
121        if any(field in attrs for field in self.fields) and not all(
122            field in attrs for field in self.fields
123        ):
124            field_names = ", ".join(self.fields)
125            message = self.message.format(field_names=field_names)
126            raise ValidationError(message, code="required")
127
128    def __repr__(self):
129        return f"<{self.__class__.__name__}(fields={smart_repr(self.fields)})>"
class PasswordHashRequiresOverride(rest_framework.exceptions.ValidationError):
23class PasswordHashRequiresOverride(ValidationError):
24    """A valid password hash that does not match the current import defaults."""

A valid password hash that does not match the current import defaults.

class PasswordHashValidator:
 27class PasswordHashValidator:
 28    """Validate a Django password hash."""
 29
 30    def __init__(self, strict: bool = True):
 31        self.strict = strict
 32
 33    def __call__(self, password_hash: str) -> None:
 34        # 1. Validate hash function
 35        allowed_algorithms = [
 36            import_string(path)().algorithm for path in settings.PASSWORD_HASHERS_IMPORT_ALLOWED
 37        ]
 38        try:
 39            hasher = identify_hasher(password_hash)
 40        except ValueError as exc:
 41            raise ValidationError(
 42                "Cannot identify hash function. "
 43                f"Password hash must use one of: {", ".join(allowed_algorithms)}."
 44            ) from exc
 45        if self.strict and hasher.algorithm not in allowed_algorithms:
 46            raise PasswordHashRequiresOverride(
 47                f"Hash function {hasher.algorithm} not allowed. "
 48                f"Password hash must use one of: {", ".join(allowed_algorithms)}."
 49            )
 50
 51        # 2. Validate hash
 52        try:
 53            decoded = hasher.decode(password_hash)
 54        # `AssertionError` is here because Django is stupid. "default$1$2$3" triggers it.
 55        except (AssertionError, ValueError) as exc:
 56            raise ValidationError("Password hash could not be decoded.") from exc
 57
 58        if not self.strict:
 59            return
 60        # Django decides whether the hash needs an update, we only explain why
 61        if not hasher.must_update(password_hash):
 62            return
 63        messages: list[str] = []
 64
 65        # 3. Validate salt
 66        if must_update_salt(decoded["salt"], hasher.salt_entropy):
 67            messages.append(
 68                "Password salt seems not to meet the current requirement of "
 69                f"{hasher.salt_entropy} bits of entropy."
 70            )
 71
 72        # 4. Validate parameters
 73        current = self.current_parameters(hasher)
 74        provided = {name: decoded[name] for name in current}
 75        # If it's not the salt, it's the parameters, even unlisted ones (e.g. argon2's hash length)
 76        if provided != current or not messages:
 77            messages.append(
 78                "Password hash parameters do not match authentik's current settings. "
 79                f"Provided: {provided}. Expected: {current}."
 80            )
 81
 82        raise PasswordHashRequiresOverride(messages)
 83
 84    @classmethod
 85    def current_parameters(cls, hasher: BasePasswordHasher) -> dict[str, Any]:
 86        if isinstance(hasher, PBKDF2PasswordHasher):
 87            return {"iterations": hasher.iterations}
 88        if isinstance(hasher, Argon2PasswordHasher):
 89            params = hasher.params()
 90            return {
 91                "variety": f"argon2{params.type.name.lower()}",
 92                "version": params.version,
 93                "memory_cost": params.memory_cost,
 94                "time_cost": params.time_cost,
 95                "parallelism": params.parallelism,
 96            }
 97        if isinstance(hasher, BCryptSHA256PasswordHasher):
 98            return {"work_factor": hasher.rounds}
 99        if isinstance(hasher, ScryptPasswordHasher):
100            return {
101                "block_size": hasher.block_size,
102                "parallelism": hasher.parallelism,
103                "work_factor": hasher.work_factor,
104            }
105        raise ValueError(f"Unsupported password hasher: {hasher.algorithm}")

Validate a Django password hash.

PasswordHashValidator(strict: bool = True)
30    def __init__(self, strict: bool = True):
31        self.strict = strict
strict
@classmethod
def current_parameters( cls, hasher: django.contrib.auth.hashers.BasePasswordHasher) -> dict[str, typing.Any]:
 84    @classmethod
 85    def current_parameters(cls, hasher: BasePasswordHasher) -> dict[str, Any]:
 86        if isinstance(hasher, PBKDF2PasswordHasher):
 87            return {"iterations": hasher.iterations}
 88        if isinstance(hasher, Argon2PasswordHasher):
 89            params = hasher.params()
 90            return {
 91                "variety": f"argon2{params.type.name.lower()}",
 92                "version": params.version,
 93                "memory_cost": params.memory_cost,
 94                "time_cost": params.time_cost,
 95                "parallelism": params.parallelism,
 96            }
 97        if isinstance(hasher, BCryptSHA256PasswordHasher):
 98            return {"work_factor": hasher.rounds}
 99        if isinstance(hasher, ScryptPasswordHasher):
100            return {
101                "block_size": hasher.block_size,
102                "parallelism": hasher.parallelism,
103                "work_factor": hasher.work_factor,
104            }
105        raise ValueError(f"Unsupported password hasher: {hasher.algorithm}")
class RequiredTogetherValidator:
108class RequiredTogetherValidator:
109    """Serializer-level validator that ensures all fields in `fields` are only
110    used together"""
111
112    fields: list[str]
113    requires_context = True
114    message = _("The fields {field_names} must be used together.")
115
116    def __init__(self, fields: list[str], message: str | None = None) -> None:
117        self.fields = fields
118        self.message = message or self.message
119
120    def __call__(self, attrs: dict, serializer: Serializer):
121        """Check that if any of the fields in `self.fields` are set, all of them must be set"""
122        if any(field in attrs for field in self.fields) and not all(
123            field in attrs for field in self.fields
124        ):
125            field_names = ", ".join(self.fields)
126            message = self.message.format(field_names=field_names)
127            raise ValidationError(message, code="required")
128
129    def __repr__(self):
130        return f"<{self.__class__.__name__}(fields={smart_repr(self.fields)})>"

Serializer-level validator that ensures all fields in fields are only used together

RequiredTogetherValidator(fields: list[str], message: str | None = None)
116    def __init__(self, fields: list[str], message: str | None = None) -> None:
117        self.fields = fields
118        self.message = message or self.message
fields: list[str]
requires_context = True
message = 'The fields {field_names} must be used together.'