authentik.policies.reputation.models

authentik reputation request policy

  1"""authentik reputation request policy"""
  2
  3from datetime import timedelta
  4from uuid import uuid4
  5
  6from django.db import models
  7from django.db.models import Sum
  8from django.db.models.query_utils import Q
  9from django.utils.timezone import now
 10from django.utils.translation import gettext_lazy as _
 11from rest_framework.serializers import BaseSerializer
 12from structlog import get_logger
 13
 14from authentik.lib.config import CONFIG
 15from authentik.lib.models import ExpiringModel, InternallyManagedMixin, SerializerModel
 16from authentik.policies.models import Policy
 17from authentik.policies.types import PolicyRequest, PolicyResult
 18from authentik.root.middleware import ClientIPMiddleware
 19
 20LOGGER = get_logger()
 21
 22
 23def reputation_expiry():
 24    """Reputation expiry"""
 25    return now() + timedelta(seconds=CONFIG.get_int("reputation.expiry"))
 26
 27
 28class ReputationPolicy(Policy):
 29    """Return true if request IP/target username's score is below a certain threshold"""
 30
 31    check_ip = models.BooleanField(default=True)
 32    check_username = models.BooleanField(default=True)
 33    threshold = models.IntegerField(default=-5)
 34
 35    @property
 36    def serializer(self) -> type[BaseSerializer]:
 37        from authentik.policies.reputation.api import ReputationPolicySerializer
 38
 39        return ReputationPolicySerializer
 40
 41    @property
 42    def component(self) -> str:
 43        return "ak-policy-reputation-form"
 44
 45    def passes(self, request: PolicyRequest) -> PolicyResult:
 46        remote_ip = ClientIPMiddleware.get_client_ip(request.http_request)
 47        query = Q()
 48        if self.check_ip:
 49            query |= Q(ip=remote_ip)
 50        if self.check_username:
 51            query |= Q(identifier=request.user.username)
 52        score = (
 53            Reputation.objects.filter(query).aggregate(total_score=Sum("score"))["total_score"] or 0
 54        )
 55        passing = score <= self.threshold
 56        LOGGER.debug(
 57            "Score for user",
 58            username=request.user.username,
 59            remote_ip=remote_ip,
 60            score=score,
 61            passing=passing,
 62        )
 63        return PolicyResult(bool(passing))
 64
 65    class Meta(Policy.PolicyMeta):
 66        verbose_name = _("Reputation Policy")
 67        verbose_name_plural = _("Reputation Policies")
 68
 69
 70class Reputation(InternallyManagedMixin, ExpiringModel, SerializerModel):
 71    """Reputation for user and or IP."""
 72
 73    reputation_uuid = models.UUIDField(primary_key=True, unique=True, default=uuid4)
 74
 75    identifier = models.TextField()
 76    ip = models.GenericIPAddressField()
 77    ip_geo_data = models.JSONField(default=dict)
 78    ip_asn_data = models.JSONField(default=dict)
 79    score = models.BigIntegerField(default=0)
 80
 81    expires = models.DateTimeField(default=reputation_expiry)
 82
 83    updated = models.DateTimeField(auto_now=True)
 84
 85    @property
 86    def serializer(self) -> type[BaseSerializer]:
 87        from authentik.policies.reputation.api import ReputationSerializer
 88
 89        return ReputationSerializer
 90
 91    def __str__(self) -> str:
 92        return f"Reputation {self.identifier}/{self.ip} @ {self.score}"
 93
 94    class Meta:
 95        verbose_name = _("Reputation Score")
 96        verbose_name_plural = _("Reputation Scores")
 97        unique_together = ("identifier", "ip")
 98        indexes = ExpiringModel.Meta.indexes + [
 99            models.Index(fields=["identifier"]),
100            models.Index(fields=["ip"]),
101            models.Index(fields=["ip", "identifier"]),
102        ]
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def reputation_expiry():
24def reputation_expiry():
25    """Reputation expiry"""
26    return now() + timedelta(seconds=CONFIG.get_int("reputation.expiry"))

Reputation expiry

class ReputationPolicy(authentik.policies.models.Policy):
29class ReputationPolicy(Policy):
30    """Return true if request IP/target username's score is below a certain threshold"""
31
32    check_ip = models.BooleanField(default=True)
33    check_username = models.BooleanField(default=True)
34    threshold = models.IntegerField(default=-5)
35
36    @property
37    def serializer(self) -> type[BaseSerializer]:
38        from authentik.policies.reputation.api import ReputationPolicySerializer
39
40        return ReputationPolicySerializer
41
42    @property
43    def component(self) -> str:
44        return "ak-policy-reputation-form"
45
46    def passes(self, request: PolicyRequest) -> PolicyResult:
47        remote_ip = ClientIPMiddleware.get_client_ip(request.http_request)
48        query = Q()
49        if self.check_ip:
50            query |= Q(ip=remote_ip)
51        if self.check_username:
52            query |= Q(identifier=request.user.username)
53        score = (
54            Reputation.objects.filter(query).aggregate(total_score=Sum("score"))["total_score"] or 0
55        )
56        passing = score <= self.threshold
57        LOGGER.debug(
58            "Score for user",
59            username=request.user.username,
60            remote_ip=remote_ip,
61            score=score,
62            passing=passing,
63        )
64        return PolicyResult(bool(passing))
65
66    class Meta(Policy.PolicyMeta):
67        verbose_name = _("Reputation Policy")
68        verbose_name_plural = _("Reputation Policies")

Return true if request IP/target username's score is below a certain threshold

def check_ip(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def check_username(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def threshold(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

serializer: type[rest_framework.serializers.BaseSerializer]
36    @property
37    def serializer(self) -> type[BaseSerializer]:
38        from authentik.policies.reputation.api import ReputationPolicySerializer
39
40        return ReputationPolicySerializer

Get serializer for this model

component: str
42    @property
43    def component(self) -> str:
44        return "ak-policy-reputation-form"

Return component used to edit this object

46    def passes(self, request: PolicyRequest) -> PolicyResult:
47        remote_ip = ClientIPMiddleware.get_client_ip(request.http_request)
48        query = Q()
49        if self.check_ip:
50            query |= Q(ip=remote_ip)
51        if self.check_username:
52            query |= Q(identifier=request.user.username)
53        score = (
54            Reputation.objects.filter(query).aggregate(total_score=Sum("score"))["total_score"] or 0
55        )
56        passing = score <= self.threshold
57        LOGGER.debug(
58            "Score for user",
59            username=request.user.username,
60            remote_ip=remote_ip,
61            score=score,
62            passing=passing,
63        )
64        return PolicyResult(bool(passing))

Check if request passes this policy

policy_ptr_id
policy_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

class ReputationPolicy.DoesNotExist(authentik.policies.models.Policy.DoesNotExist):

The requested object does not exist

class ReputationPolicy.MultipleObjectsReturned(authentik.policies.models.Policy.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

 71class Reputation(InternallyManagedMixin, ExpiringModel, SerializerModel):
 72    """Reputation for user and or IP."""
 73
 74    reputation_uuid = models.UUIDField(primary_key=True, unique=True, default=uuid4)
 75
 76    identifier = models.TextField()
 77    ip = models.GenericIPAddressField()
 78    ip_geo_data = models.JSONField(default=dict)
 79    ip_asn_data = models.JSONField(default=dict)
 80    score = models.BigIntegerField(default=0)
 81
 82    expires = models.DateTimeField(default=reputation_expiry)
 83
 84    updated = models.DateTimeField(auto_now=True)
 85
 86    @property
 87    def serializer(self) -> type[BaseSerializer]:
 88        from authentik.policies.reputation.api import ReputationSerializer
 89
 90        return ReputationSerializer
 91
 92    def __str__(self) -> str:
 93        return f"Reputation {self.identifier}/{self.ip} @ {self.score}"
 94
 95    class Meta:
 96        verbose_name = _("Reputation Score")
 97        verbose_name_plural = _("Reputation Scores")
 98        unique_together = ("identifier", "ip")
 99        indexes = ExpiringModel.Meta.indexes + [
100            models.Index(fields=["identifier"]),
101            models.Index(fields=["ip"]),
102            models.Index(fields=["ip", "identifier"]),
103        ]

Reputation for user and or IP.

def reputation_uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def identifier(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def ip(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def ip_geo_data(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def ip_asn_data(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def score(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def expires(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def updated(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

serializer: type[rest_framework.serializers.BaseSerializer]
86    @property
87    def serializer(self) -> type[BaseSerializer]:
88        from authentik.policies.reputation.api import ReputationSerializer
89
90        return ReputationSerializer

Get serializer for this model

def expiring(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def get_next_by_expires(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_expires(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_next_by_updated(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_updated(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

class Reputation.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class Reputation.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.