This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
authentik/passbook/core/policies.py

135 lines
4.9 KiB
Python
Raw Normal View History

2019-02-16 09:24:31 +00:00
"""passbook core policy engine"""
from logging import getLogger
2019-03-21 13:53:57 +00:00
from amqp.exceptions import UnexpectedFrame
2019-02-16 09:24:31 +00:00
from celery import group
2019-03-21 13:53:57 +00:00
from celery.exceptions import TimeoutError as CeleryTimeoutError
2019-03-21 10:08:32 +00:00
from django.core.cache import cache
2019-03-03 19:54:23 +00:00
from ipware import get_client_ip
2019-02-16 09:24:31 +00:00
from passbook.core.celery import CELERY_APP
from passbook.core.models import Policy, User
LOGGER = getLogger(__name__)
2019-02-16 09:24:31 +00:00
2019-03-21 10:08:32 +00:00
def _cache_key(policy, user):
return "policy_%s#%s" % (policy.uuid, user.pk)
2019-03-21 10:08:32 +00:00
2019-02-16 09:24:31 +00:00
@CELERY_APP.task()
def _policy_engine_task(user_pk, policy_pk, **kwargs):
"""Task wrapper to run policy checking"""
if not user_pk:
raise ValueError()
2019-02-16 09:24:31 +00:00
policy_obj = Policy.objects.filter(pk=policy_pk).select_subclasses().first()
user_obj = User.objects.get(pk=user_pk)
for key, value in kwargs.items():
setattr(user_obj, key, value)
LOGGER.debug("Running policy `%s`#%s for user %s...", policy_obj.name,
policy_obj.pk.hex, user_obj)
policy_result = policy_obj.passes(user_obj)
# Handle policy result correctly if result, message or just result
message = None
if isinstance(policy_result, (tuple, list)):
policy_result, message = policy_result
# Invert result if policy.negate is set
if policy_obj.negate:
policy_result = not policy_result
LOGGER.debug("Policy %r#%s got %s", policy_obj.name, policy_obj.pk.hex, policy_result)
2019-03-21 10:08:32 +00:00
cache_key = _cache_key(policy_obj, user_obj)
cache.set(cache_key, (policy_obj.action, policy_result, message))
LOGGER.debug("Cached entry as %s", cache_key)
return policy_obj.action, policy_result, message
2019-02-16 09:24:31 +00:00
class PolicyEngine:
"""Orchestrate policy checking, launch tasks and return result"""
2019-03-21 10:08:32 +00:00
__group = None
__cached = None
2019-02-16 09:24:31 +00:00
policies = None
__get_timeout = 0
2019-03-21 10:08:32 +00:00
__request = None
__user = None
2019-02-16 09:24:31 +00:00
def __init__(self, policies):
self.policies = policies
2019-03-21 10:08:32 +00:00
self.__request = None
self.__user = None
2019-02-16 09:24:31 +00:00
def for_user(self, user):
"""Check policies for user"""
2019-03-21 10:08:32 +00:00
self.__user = user
return self
def with_request(self, request):
"""Set request"""
2019-03-21 10:08:32 +00:00
self.__request = request
return self
def build(self):
"""Build task group"""
2019-03-21 10:08:32 +00:00
if not self.__user:
raise ValueError("User not set.")
2019-02-16 09:24:31 +00:00
signatures = []
2019-03-21 10:08:32 +00:00
cached_policies = []
2019-02-16 09:24:31 +00:00
kwargs = {
2019-03-21 10:08:32 +00:00
'__password__': getattr(self.__user, '__password__', None),
2019-04-29 21:18:51 +00:00
'session': dict(getattr(self.__request, 'session', {}).items()),
2019-02-16 09:24:31 +00:00
}
2019-03-21 10:08:32 +00:00
if self.__request:
kwargs['remote_ip'], _ = get_client_ip(self.__request)
2019-03-03 19:34:00 +00:00
if not kwargs['remote_ip']:
2019-03-03 19:54:23 +00:00
kwargs['remote_ip'] = '255.255.255.255'
2019-02-16 09:24:31 +00:00
for policy in self.policies:
2019-03-21 10:08:32 +00:00
cached_policy = cache.get(_cache_key(policy, self.__user), None)
if cached_policy:
LOGGER.debug("Taking result from cache for %s", policy.pk.hex)
2019-03-21 10:08:32 +00:00
cached_policies.append(cached_policy)
else:
LOGGER.debug("Evaluating policy %s", policy.pk.hex)
signatures.append(_policy_engine_task.signature(
2019-03-21 14:02:33 +00:00
args=(self.__user.pk, policy.pk.hex),
kwargs=kwargs,
time_limit=policy.timeout))
self.__get_timeout += policy.timeout
LOGGER.debug("Set total policy timeout to %r", self.__get_timeout)
2019-03-21 10:08:32 +00:00
# If all policies are cached, we have an empty list here.
if signatures:
self.__group = group(signatures)()
2019-03-21 14:05:04 +00:00
self.__get_timeout += 3
self.__get_timeout = (self.__get_timeout / len(self.policies)) * 1.5
2019-03-21 10:08:32 +00:00
self.__cached = cached_policies
2019-02-16 09:24:31 +00:00
return self
@property
def result(self):
"""Get policy-checking result"""
messages = []
2019-03-21 10:08:32 +00:00
result = []
try:
2019-03-21 10:08:32 +00:00
if self.__group:
# ValueError can be thrown from _policy_engine_task when user is None
2019-03-21 14:02:33 +00:00
result += self.__group.get(timeout=self.__get_timeout)
2019-03-21 10:08:32 +00:00
result += self.__cached
except ValueError as exc:
2019-03-21 13:53:57 +00:00
# ValueError can be thrown from _policy_engine_task when user is None
return False, [str(exc)]
except UnexpectedFrame as exc:
return False, [str(exc)]
except CeleryTimeoutError as exc:
return False, [str(exc)]
2019-03-21 10:08:32 +00:00
for policy_action, policy_result, policy_message in result:
passing = (policy_action == Policy.ACTION_ALLOW and policy_result) or \
(policy_action == Policy.ACTION_DENY and not policy_result)
LOGGER.debug('Action=%s, Result=%r => %r', policy_action, policy_result, passing)
if policy_message:
messages.append(policy_message)
if not passing:
return False, messages
return True, messages
2019-03-08 18:49:53 +00:00
@property
def passing(self):
"""Only get true/false if user passes"""
return self.result[0]