authentik.api.search.ql

DjangoQL search

  1"""DjangoQL search"""
  2
  3from django.db.models import QuerySet
  4from django.db.models.constants import LOOKUP_SEP
  5from djangoql.ast import Name
  6from djangoql.exceptions import DjangoQLError
  7from djangoql.parser import DjangoQLParser
  8from djangoql.queryset import build_filter
  9from djangoql.schema import DjangoQLSchema
 10from rest_framework.filters import SearchFilter
 11from rest_framework.request import Request
 12from structlog.stdlib import get_logger
 13
 14from authentik.api.search.fields import JSONSearchField
 15from authentik.rbac.endpoint_checks import EndpointChecks
 16from authentik.rbac.field_rules import FieldRules
 17
 18LOGGER = get_logger()
 19
 20
 21class BaseSchema(DjangoQLSchema):
 22    """Base Schema which deals with JSON Fields"""
 23
 24    def resolve_name(self, name: Name):
 25        model = self.model_label(self.current_model)
 26        root_field = name.parts[0]
 27        field = self.models[model].get(root_field)
 28        # If the query goes into a JSON field, return the root
 29        # field as the JSON field will do the rest
 30        if isinstance(field, JSONSearchField):
 31            # This is a workaround; build_filter will remove the right-most
 32            # entry in the path as that is intended to be the same as the field
 33            # however for JSON that is not the case
 34            if name.parts[-1] != root_field:
 35                name.parts.append(root_field)
 36            return field
 37        return super().resolve_name(name)
 38
 39
 40class HiddenFieldsSearchFilter(SearchFilter):
 41    """This is used to prevent unauthorized users from probing values of fields hidden to them."""
 42
 43    def __init__(self):
 44        super().__init__()
 45        self.hidden_whole_fields: set[str] = set()
 46
 47    def get_search_fields(self, view, request: Request):
 48        fields = super().get_search_fields(view, request)
 49        if not fields or not self.hidden_whole_fields:
 50            return fields
 51        return [
 52            field for field in fields if self.searched_field(field) not in self.hidden_whole_fields
 53        ]
 54
 55    def searched_field(self, search_field: str) -> str:
 56        """The model field a `search_fields` entry starts from, without DRF's lookup prefix
 57        (`^`, `=`, `@` or `$`) or a `__` path into related models"""
 58        if search_field[:1] in self.lookup_prefixes:
 59            search_field = search_field[1:]
 60        return search_field.split(LOOKUP_SEP)[0]
 61
 62
 63class QLSearch(SearchFilter):
 64    """rest_framework search filter which uses DjangoQL"""
 65
 66    def __init__(self):
 67        super().__init__()
 68        self._fallback = HiddenFieldsSearchFilter()
 69
 70    def get_search_terms(self, request: Request) -> str:
 71        """Search terms are set by a ?search=... query parameter,
 72        and may be comma and/or whitespace delimited."""
 73        params = request.query_params.get("search", "")
 74        params = params.replace("\x00", "")  # strip null characters
 75        return params
 76
 77    def get_schema(self, request: Request, view) -> BaseSchema:
 78        ql_fields = []
 79        if hasattr(view, "get_ql_fields"):
 80            ql_fields = view.get_ql_fields()
 81
 82        class InlineSchema(BaseSchema):
 83            def get_fields(self, model):
 84                return ql_fields or []
 85
 86        return InlineSchema
 87
 88    def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
 89        rules = EndpointChecks.for_request(request).field_rules()
 90        rules.refuse_hidden_parameters(request, view)
 91        self._fallback.hidden_whole_fields = rules.hidden_whole_fields
 92        search_query = self.get_search_terms(request)
 93        schema = self.get_schema(request, view)
 94        if len(search_query) == 0:
 95            return self._fallback.filter_queryset(request, queryset, view)
 96        try:
 97            return self.apply_search(queryset, search_query, schema, rules)
 98        except DjangoQLError as exc:
 99            LOGGER.debug("Failed to parse search expression", exc=exc)
100            return self._fallback.filter_queryset(request, queryset, view)
101
102    def apply_search(
103        self, queryset: QuerySet, search: str, schema: type[BaseSchema], rules: FieldRules
104    ) -> QuerySet:
105        """This is a rewrite of `djangoql.queryset.apply_search`"""
106        ast = DjangoQLParser().parse(search)
107        if rules.hidden:
108            rules.guard_search(ast)
109        schema_instance = schema(queryset.model)
110        schema_instance.validate(ast)
111        return queryset.filter(build_filter(ast, schema_instance))
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class BaseSchema(djangoql.schema.DjangoQLSchema):
22class BaseSchema(DjangoQLSchema):
23    """Base Schema which deals with JSON Fields"""
24
25    def resolve_name(self, name: Name):
26        model = self.model_label(self.current_model)
27        root_field = name.parts[0]
28        field = self.models[model].get(root_field)
29        # If the query goes into a JSON field, return the root
30        # field as the JSON field will do the rest
31        if isinstance(field, JSONSearchField):
32            # This is a workaround; build_filter will remove the right-most
33            # entry in the path as that is intended to be the same as the field
34            # however for JSON that is not the case
35            if name.parts[-1] != root_field:
36                name.parts.append(root_field)
37            return field
38        return super().resolve_name(name)

Base Schema which deals with JSON Fields

def resolve_name(self, name: djangoql.ast.Name):
25    def resolve_name(self, name: Name):
26        model = self.model_label(self.current_model)
27        root_field = name.parts[0]
28        field = self.models[model].get(root_field)
29        # If the query goes into a JSON field, return the root
30        # field as the JSON field will do the rest
31        if isinstance(field, JSONSearchField):
32            # This is a workaround; build_filter will remove the right-most
33            # entry in the path as that is intended to be the same as the field
34            # however for JSON that is not the case
35            if name.parts[-1] != root_field:
36                name.parts.append(root_field)
37            return field
38        return super().resolve_name(name)
class HiddenFieldsSearchFilter(rest_framework.filters.SearchFilter):
41class HiddenFieldsSearchFilter(SearchFilter):
42    """This is used to prevent unauthorized users from probing values of fields hidden to them."""
43
44    def __init__(self):
45        super().__init__()
46        self.hidden_whole_fields: set[str] = set()
47
48    def get_search_fields(self, view, request: Request):
49        fields = super().get_search_fields(view, request)
50        if not fields or not self.hidden_whole_fields:
51            return fields
52        return [
53            field for field in fields if self.searched_field(field) not in self.hidden_whole_fields
54        ]
55
56    def searched_field(self, search_field: str) -> str:
57        """The model field a `search_fields` entry starts from, without DRF's lookup prefix
58        (`^`, `=`, `@` or `$`) or a `__` path into related models"""
59        if search_field[:1] in self.lookup_prefixes:
60            search_field = search_field[1:]
61        return search_field.split(LOOKUP_SEP)[0]

This is used to prevent unauthorized users from probing values of fields hidden to them.

hidden_whole_fields: set[str]
def get_search_fields(self, view, request: rest_framework.request.Request):
48    def get_search_fields(self, view, request: Request):
49        fields = super().get_search_fields(view, request)
50        if not fields or not self.hidden_whole_fields:
51            return fields
52        return [
53            field for field in fields if self.searched_field(field) not in self.hidden_whole_fields
54        ]

Search fields are obtained from the view, but the request is always passed to this method. Sub-classes can override this method to dynamically change the search fields based on request content.

def searched_field(self, search_field: str) -> str:
56    def searched_field(self, search_field: str) -> str:
57        """The model field a `search_fields` entry starts from, without DRF's lookup prefix
58        (`^`, `=`, `@` or `$`) or a `__` path into related models"""
59        if search_field[:1] in self.lookup_prefixes:
60            search_field = search_field[1:]
61        return search_field.split(LOOKUP_SEP)[0]

The model field a search_fields entry starts from, without DRF's lookup prefix (^, =, @ or $) or a __ path into related models

class QLSearch(rest_framework.filters.SearchFilter):
 64class QLSearch(SearchFilter):
 65    """rest_framework search filter which uses DjangoQL"""
 66
 67    def __init__(self):
 68        super().__init__()
 69        self._fallback = HiddenFieldsSearchFilter()
 70
 71    def get_search_terms(self, request: Request) -> str:
 72        """Search terms are set by a ?search=... query parameter,
 73        and may be comma and/or whitespace delimited."""
 74        params = request.query_params.get("search", "")
 75        params = params.replace("\x00", "")  # strip null characters
 76        return params
 77
 78    def get_schema(self, request: Request, view) -> BaseSchema:
 79        ql_fields = []
 80        if hasattr(view, "get_ql_fields"):
 81            ql_fields = view.get_ql_fields()
 82
 83        class InlineSchema(BaseSchema):
 84            def get_fields(self, model):
 85                return ql_fields or []
 86
 87        return InlineSchema
 88
 89    def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
 90        rules = EndpointChecks.for_request(request).field_rules()
 91        rules.refuse_hidden_parameters(request, view)
 92        self._fallback.hidden_whole_fields = rules.hidden_whole_fields
 93        search_query = self.get_search_terms(request)
 94        schema = self.get_schema(request, view)
 95        if len(search_query) == 0:
 96            return self._fallback.filter_queryset(request, queryset, view)
 97        try:
 98            return self.apply_search(queryset, search_query, schema, rules)
 99        except DjangoQLError as exc:
100            LOGGER.debug("Failed to parse search expression", exc=exc)
101            return self._fallback.filter_queryset(request, queryset, view)
102
103    def apply_search(
104        self, queryset: QuerySet, search: str, schema: type[BaseSchema], rules: FieldRules
105    ) -> QuerySet:
106        """This is a rewrite of `djangoql.queryset.apply_search`"""
107        ast = DjangoQLParser().parse(search)
108        if rules.hidden:
109            rules.guard_search(ast)
110        schema_instance = schema(queryset.model)
111        schema_instance.validate(ast)
112        return queryset.filter(build_filter(ast, schema_instance))

rest_framework search filter which uses DjangoQL

def get_search_terms(self, request: rest_framework.request.Request) -> str:
71    def get_search_terms(self, request: Request) -> str:
72        """Search terms are set by a ?search=... query parameter,
73        and may be comma and/or whitespace delimited."""
74        params = request.query_params.get("search", "")
75        params = params.replace("\x00", "")  # strip null characters
76        return params

Search terms are set by a ?search=... query parameter, and may be comma and/or whitespace delimited.

def get_schema( self, request: rest_framework.request.Request, view) -> BaseSchema:
78    def get_schema(self, request: Request, view) -> BaseSchema:
79        ql_fields = []
80        if hasattr(view, "get_ql_fields"):
81            ql_fields = view.get_ql_fields()
82
83        class InlineSchema(BaseSchema):
84            def get_fields(self, model):
85                return ql_fields or []
86
87        return InlineSchema
def filter_queryset( self, request: rest_framework.request.Request, queryset: django.db.models.query.QuerySet, view) -> django.db.models.query.QuerySet:
 89    def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
 90        rules = EndpointChecks.for_request(request).field_rules()
 91        rules.refuse_hidden_parameters(request, view)
 92        self._fallback.hidden_whole_fields = rules.hidden_whole_fields
 93        search_query = self.get_search_terms(request)
 94        schema = self.get_schema(request, view)
 95        if len(search_query) == 0:
 96            return self._fallback.filter_queryset(request, queryset, view)
 97        try:
 98            return self.apply_search(queryset, search_query, schema, rules)
 99        except DjangoQLError as exc:
100            LOGGER.debug("Failed to parse search expression", exc=exc)
101            return self._fallback.filter_queryset(request, queryset, view)

Return a filtered queryset.