2020-05-08 17:46:39 +00:00
|
|
|
"""passbook multi-stage authentication engine"""
|
2020-06-30 09:18:39 +00:00
|
|
|
from traceback import format_tb
|
2020-05-23 22:57:25 +00:00
|
|
|
from typing import Any, Dict, Optional
|
2018-12-13 17:02:08 +00:00
|
|
|
|
2020-09-24 18:06:37 +00:00
|
|
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
2020-06-07 14:35:08 +00:00
|
|
|
from django.http import (
|
|
|
|
Http404,
|
|
|
|
HttpRequest,
|
|
|
|
HttpResponse,
|
|
|
|
HttpResponseRedirect,
|
|
|
|
JsonResponse,
|
|
|
|
)
|
2020-09-15 07:54:19 +00:00
|
|
|
from django.shortcuts import get_object_or_404, redirect, reverse
|
2020-06-07 14:35:08 +00:00
|
|
|
from django.template.response import TemplateResponse
|
2020-05-23 22:57:25 +00:00
|
|
|
from django.utils.decorators import method_decorator
|
|
|
|
from django.views.decorators.clickjacking import xframe_options_sameorigin
|
|
|
|
from django.views.generic import TemplateView, View
|
2019-10-01 08:24:10 +00:00
|
|
|
from structlog import get_logger
|
2018-12-13 17:02:08 +00:00
|
|
|
|
2020-06-29 17:13:07 +00:00
|
|
|
from passbook.audit.models import cleanse_dict
|
2020-09-14 19:52:43 +00:00
|
|
|
from passbook.core.models import PASSBOOK_USER_DEBUG
|
2020-05-09 18:54:56 +00:00
|
|
|
from passbook.flows.exceptions import EmptyFlowException, FlowNonApplicableException
|
2020-09-24 18:05:49 +00:00
|
|
|
from passbook.flows.models import ConfigurableStage, Flow, FlowDesignation, Stage
|
2020-09-24 18:06:37 +00:00
|
|
|
from passbook.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan, FlowPlanner
|
2020-07-20 14:33:34 +00:00
|
|
|
from passbook.lib.utils.reflection import class_to_path
|
2020-07-14 19:53:39 +00:00
|
|
|
from passbook.lib.utils.urls import is_url_absolute, redirect_with_qs
|
2020-09-15 07:54:19 +00:00
|
|
|
from passbook.policies.http import AccessDeniedResponse
|
2018-12-13 17:02:08 +00:00
|
|
|
|
2019-10-04 08:08:53 +00:00
|
|
|
LOGGER = get_logger()
|
2019-12-31 11:45:29 +00:00
|
|
|
# Argument used to redirect user after login
|
2019-12-31 11:51:16 +00:00
|
|
|
NEXT_ARG_NAME = "next"
|
2020-05-08 14:10:27 +00:00
|
|
|
SESSION_KEY_PLAN = "passbook_flows_plan"
|
2020-07-12 20:47:46 +00:00
|
|
|
SESSION_KEY_APPLICATION_PRE = "passbook_flows_application_pre"
|
2020-06-21 18:46:38 +00:00
|
|
|
SESSION_KEY_GET = "passbook_flows_get"
|
2019-12-31 11:45:29 +00:00
|
|
|
|
2018-12-13 17:02:08 +00:00
|
|
|
|
2020-05-23 22:57:25 +00:00
|
|
|
@method_decorator(xframe_options_sameorigin, name="dispatch")
|
2020-05-08 14:10:27 +00:00
|
|
|
class FlowExecutorView(View):
|
2020-05-08 17:46:39 +00:00
|
|
|
"""Stage 1 Flow executor, passing requests to Stage Views"""
|
2018-12-13 17:02:08 +00:00
|
|
|
|
2020-05-08 14:10:27 +00:00
|
|
|
flow: Flow
|
2019-02-25 11:29:40 +00:00
|
|
|
|
2020-05-09 21:19:36 +00:00
|
|
|
plan: Optional[FlowPlan] = None
|
2020-05-08 17:46:39 +00:00
|
|
|
current_stage: Stage
|
|
|
|
current_stage_view: View
|
2018-12-13 17:02:08 +00:00
|
|
|
|
2020-05-08 14:10:27 +00:00
|
|
|
def setup(self, request: HttpRequest, flow_slug: str):
|
|
|
|
super().setup(request, flow_slug=flow_slug)
|
2020-05-31 21:01:08 +00:00
|
|
|
self.flow = get_object_or_404(Flow.objects.select_related(), slug=flow_slug)
|
2018-12-18 14:34:26 +00:00
|
|
|
|
2020-05-09 18:54:56 +00:00
|
|
|
def handle_invalid_flow(self, exc: BaseException) -> HttpResponse:
|
2020-05-08 14:10:27 +00:00
|
|
|
"""When a flow is non-applicable check if user is on the correct domain"""
|
2019-10-07 14:33:48 +00:00
|
|
|
if NEXT_ARG_NAME in self.request.GET:
|
2020-07-14 19:53:39 +00:00
|
|
|
if not is_url_absolute(self.request.GET.get(NEXT_ARG_NAME)):
|
|
|
|
LOGGER.debug("f(exec): Redirecting to next on fail")
|
|
|
|
return redirect(self.request.GET.get(NEXT_ARG_NAME))
|
2020-05-11 13:01:14 +00:00
|
|
|
message = exc.__doc__ if exc.__doc__ else str(exc)
|
2020-09-15 07:54:19 +00:00
|
|
|
return self.stage_invalid(error_message=message)
|
2020-05-08 12:33:14 +00:00
|
|
|
|
|
|
|
def dispatch(self, request: HttpRequest, flow_slug: str) -> HttpResponse:
|
|
|
|
# Early check if theres an active Plan for the current session
|
2020-05-10 18:15:24 +00:00
|
|
|
if SESSION_KEY_PLAN in self.request.session:
|
|
|
|
self.plan = self.request.session[SESSION_KEY_PLAN]
|
|
|
|
if self.plan.flow_pk != self.flow.pk.hex:
|
|
|
|
LOGGER.warning(
|
|
|
|
"f(exec): Found existing plan for other flow, deleteing plan",
|
|
|
|
flow_slug=flow_slug,
|
|
|
|
)
|
|
|
|
# Existing plan is deleted from session and instance
|
|
|
|
self.plan = None
|
|
|
|
self.cancel()
|
|
|
|
LOGGER.debug("f(exec): Continuing existing plan", flow_slug=flow_slug)
|
|
|
|
|
|
|
|
# Don't check session again as we've either already loaded the plan or we need to plan
|
|
|
|
if not self.plan:
|
2020-05-08 12:33:14 +00:00
|
|
|
LOGGER.debug(
|
2020-05-09 23:01:58 +00:00
|
|
|
"f(exec): No active Plan found, initiating planner", flow_slug=flow_slug
|
2020-05-08 12:33:14 +00:00
|
|
|
)
|
|
|
|
try:
|
|
|
|
self.plan = self._initiate_plan()
|
2020-05-09 18:54:56 +00:00
|
|
|
except FlowNonApplicableException as exc:
|
2020-05-09 23:01:58 +00:00
|
|
|
LOGGER.warning("f(exec): Flow not applicable to current user", exc=exc)
|
2020-09-15 07:54:19 +00:00
|
|
|
return to_stage_response(self.request, self.handle_invalid_flow(exc))
|
2020-05-09 18:54:56 +00:00
|
|
|
except EmptyFlowException as exc:
|
2020-05-09 23:01:58 +00:00
|
|
|
LOGGER.warning("f(exec): Flow is empty", exc=exc)
|
2020-09-15 07:54:19 +00:00
|
|
|
return to_stage_response(self.request, self.handle_invalid_flow(exc))
|
2020-05-08 17:46:39 +00:00
|
|
|
# We don't save the Plan after getting the next stage
|
2020-05-08 12:33:14 +00:00
|
|
|
# as it hasn't been successfully passed yet
|
2020-10-20 13:06:36 +00:00
|
|
|
next_stage = self.plan.next(self.request)
|
2020-08-19 08:49:14 +00:00
|
|
|
if not next_stage:
|
|
|
|
LOGGER.debug("f(exec): no more stages, flow is done.")
|
|
|
|
return self._flow_done()
|
|
|
|
self.current_stage = next_stage
|
2020-05-08 16:29:18 +00:00
|
|
|
LOGGER.debug(
|
2020-05-09 23:01:58 +00:00
|
|
|
"f(exec): Current stage",
|
|
|
|
current_stage=self.current_stage,
|
|
|
|
flow_slug=self.flow.slug,
|
2020-05-08 16:29:18 +00:00
|
|
|
)
|
2020-09-29 08:32:41 +00:00
|
|
|
stage_cls = self.current_stage.type
|
2020-05-08 17:46:39 +00:00
|
|
|
self.current_stage_view = stage_cls(self)
|
2020-06-07 14:35:08 +00:00
|
|
|
self.current_stage_view.args = self.args
|
|
|
|
self.current_stage_view.kwargs = self.kwargs
|
2020-05-08 17:46:39 +00:00
|
|
|
self.current_stage_view.request = request
|
2020-05-08 12:33:14 +00:00
|
|
|
return super().dispatch(request)
|
|
|
|
|
|
|
|
def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
|
2020-05-08 17:46:39 +00:00
|
|
|
"""pass get request to current stage"""
|
2020-05-08 12:33:14 +00:00
|
|
|
LOGGER.debug(
|
2020-05-09 23:01:58 +00:00
|
|
|
"f(exec): Passing GET",
|
2020-05-08 17:46:39 +00:00
|
|
|
view_class=class_to_path(self.current_stage_view.__class__),
|
2020-06-18 20:43:51 +00:00
|
|
|
stage=self.current_stage,
|
2020-05-08 14:51:12 +00:00
|
|
|
flow_slug=self.flow.slug,
|
2020-05-08 12:33:14 +00:00
|
|
|
)
|
2020-06-30 09:18:39 +00:00
|
|
|
try:
|
|
|
|
stage_response = self.current_stage_view.get(request, *args, **kwargs)
|
|
|
|
return to_stage_response(request, stage_response)
|
|
|
|
except Exception as exc: # pylint: disable=broad-except
|
2020-06-30 10:14:40 +00:00
|
|
|
LOGGER.exception(exc)
|
2020-09-15 07:54:19 +00:00
|
|
|
return to_stage_response(request, FlowErrorResponse(request, exc))
|
2020-05-08 12:33:14 +00:00
|
|
|
|
|
|
|
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
|
2020-05-08 17:46:39 +00:00
|
|
|
"""pass post request to current stage"""
|
2020-05-08 12:33:14 +00:00
|
|
|
LOGGER.debug(
|
2020-05-09 23:01:58 +00:00
|
|
|
"f(exec): Passing POST",
|
2020-05-08 17:46:39 +00:00
|
|
|
view_class=class_to_path(self.current_stage_view.__class__),
|
2020-06-18 20:43:51 +00:00
|
|
|
stage=self.current_stage,
|
2020-05-08 14:51:12 +00:00
|
|
|
flow_slug=self.flow.slug,
|
2020-05-08 12:33:14 +00:00
|
|
|
)
|
2020-06-30 09:18:39 +00:00
|
|
|
try:
|
|
|
|
stage_response = self.current_stage_view.post(request, *args, **kwargs)
|
|
|
|
return to_stage_response(request, stage_response)
|
|
|
|
except Exception as exc: # pylint: disable=broad-except
|
2020-06-30 10:14:40 +00:00
|
|
|
LOGGER.exception(exc)
|
2020-09-15 07:54:19 +00:00
|
|
|
return to_stage_response(request, FlowErrorResponse(request, exc))
|
2020-05-08 12:33:14 +00:00
|
|
|
|
|
|
|
def _initiate_plan(self) -> FlowPlan:
|
|
|
|
planner = FlowPlanner(self.flow)
|
|
|
|
plan = planner.plan(self.request)
|
|
|
|
self.request.session[SESSION_KEY_PLAN] = plan
|
|
|
|
return plan
|
2020-05-08 14:10:27 +00:00
|
|
|
|
|
|
|
def _flow_done(self) -> HttpResponse:
|
2020-05-08 17:46:39 +00:00
|
|
|
"""User Successfully passed all stages"""
|
2020-06-19 17:34:27 +00:00
|
|
|
# Since this is wrapped by the ExecutorShell, the next argument is saved in the session
|
2020-07-14 19:42:47 +00:00
|
|
|
# extract the next param before cancel as that cleans it
|
2020-06-21 18:46:38 +00:00
|
|
|
next_param = self.request.session.get(SESSION_KEY_GET, {}).get(
|
2020-11-22 22:44:21 +00:00
|
|
|
NEXT_ARG_NAME, "passbook_core:shell"
|
2020-06-19 17:34:27 +00:00
|
|
|
)
|
2020-07-14 19:42:47 +00:00
|
|
|
self.cancel()
|
2020-05-11 13:01:14 +00:00
|
|
|
return redirect_with_qs(next_param)
|
2020-05-08 14:10:27 +00:00
|
|
|
|
2020-05-08 17:46:39 +00:00
|
|
|
def stage_ok(self) -> HttpResponse:
|
|
|
|
"""Callback called by stages upon successful completion.
|
2020-05-08 14:10:27 +00:00
|
|
|
Persists updated plan and context to session."""
|
|
|
|
LOGGER.debug(
|
2020-05-09 23:01:58 +00:00
|
|
|
"f(exec): Stage ok",
|
2020-05-08 17:46:39 +00:00
|
|
|
stage_class=class_to_path(self.current_stage_view.__class__),
|
2020-05-08 14:51:12 +00:00
|
|
|
flow_slug=self.flow.slug,
|
2020-05-08 14:10:27 +00:00
|
|
|
)
|
2020-06-18 20:43:51 +00:00
|
|
|
self.plan.pop()
|
2020-05-08 14:10:27 +00:00
|
|
|
self.request.session[SESSION_KEY_PLAN] = self.plan
|
2020-05-08 17:46:39 +00:00
|
|
|
if self.plan.stages:
|
2020-05-08 14:10:27 +00:00
|
|
|
LOGGER.debug(
|
2020-05-09 23:01:58 +00:00
|
|
|
"f(exec): Continuing with next stage",
|
2020-05-08 17:46:39 +00:00
|
|
|
reamining=len(self.plan.stages),
|
2020-05-08 14:51:12 +00:00
|
|
|
flow_slug=self.flow.slug,
|
2020-05-08 14:10:27 +00:00
|
|
|
)
|
|
|
|
return redirect_with_qs(
|
|
|
|
"passbook_flows:flow-executor", self.request.GET, **self.kwargs
|
|
|
|
)
|
2020-05-08 17:46:39 +00:00
|
|
|
# User passed all stages
|
2020-05-08 14:10:27 +00:00
|
|
|
LOGGER.debug(
|
2020-05-09 23:01:58 +00:00
|
|
|
"f(exec): User passed all stages",
|
2020-05-08 14:51:12 +00:00
|
|
|
flow_slug=self.flow.slug,
|
2020-06-29 17:13:07 +00:00
|
|
|
context=cleanse_dict(self.plan.context),
|
2020-05-08 14:10:27 +00:00
|
|
|
)
|
|
|
|
return self._flow_done()
|
|
|
|
|
2020-09-14 19:52:43 +00:00
|
|
|
def stage_invalid(self, error_message: Optional[str] = None) -> HttpResponse:
|
2020-05-08 17:46:39 +00:00
|
|
|
"""Callback used stage when data is correct but a policy denies access
|
2020-09-14 19:52:43 +00:00
|
|
|
or the user account is disabled.
|
|
|
|
|
|
|
|
Optionally, an exception can be passed, which will be shown if the current user
|
|
|
|
is a superuser."""
|
2020-05-09 23:01:58 +00:00
|
|
|
LOGGER.debug("f(exec): Stage invalid", flow_slug=self.flow.slug)
|
2020-05-08 14:10:27 +00:00
|
|
|
self.cancel()
|
2020-09-19 00:15:07 +00:00
|
|
|
response = AccessDeniedResponse(
|
|
|
|
self.request, template="flows/denied_shell.html"
|
|
|
|
)
|
2020-09-15 07:54:19 +00:00
|
|
|
response.error_message = error_message
|
2020-09-19 00:15:07 +00:00
|
|
|
return to_stage_response(self.request, response)
|
2020-05-08 14:10:27 +00:00
|
|
|
|
2020-05-09 21:19:36 +00:00
|
|
|
def cancel(self):
|
2020-05-08 14:10:27 +00:00
|
|
|
"""Cancel current execution and return a redirect"""
|
2020-07-12 20:47:46 +00:00
|
|
|
keys_to_delete = [
|
|
|
|
SESSION_KEY_APPLICATION_PRE,
|
|
|
|
SESSION_KEY_PLAN,
|
|
|
|
SESSION_KEY_GET,
|
|
|
|
]
|
|
|
|
for key in keys_to_delete:
|
|
|
|
if key in self.request.session:
|
|
|
|
del self.request.session[key]
|
2020-05-08 14:50:50 +00:00
|
|
|
|
|
|
|
|
2020-09-15 07:54:19 +00:00
|
|
|
class FlowErrorResponse(TemplateResponse):
|
|
|
|
"""Response class when an unhandled error occurs during a stage. Normal users
|
|
|
|
are shown an error message, superusers are shown a full stacktrace."""
|
|
|
|
|
|
|
|
error: Exception
|
2020-05-09 18:54:56 +00:00
|
|
|
|
2020-09-15 07:54:19 +00:00
|
|
|
def __init__(self, request: HttpRequest, error: Exception) -> None:
|
|
|
|
# For some reason pyright complains about keyword argument usage here
|
|
|
|
# pyright: reportGeneralTypeIssues=false
|
|
|
|
super().__init__(request=request, template="flows/error.html")
|
|
|
|
self.error = error
|
2020-09-14 19:52:43 +00:00
|
|
|
|
2020-09-15 07:54:19 +00:00
|
|
|
def resolve_context(
|
|
|
|
self, context: Optional[Dict[str, Any]]
|
|
|
|
) -> Optional[Dict[str, Any]]:
|
|
|
|
if not context:
|
|
|
|
context = {}
|
|
|
|
context["error"] = self.error
|
|
|
|
if self._request.user and self._request.user.is_authenticated:
|
|
|
|
if self._request.user.is_superuser or self._request.user.attributes.get(
|
|
|
|
PASSBOOK_USER_DEBUG, False
|
|
|
|
):
|
|
|
|
context["tb"] = "".join(format_tb(self.error.__traceback__))
|
|
|
|
return context
|
2020-09-14 19:52:43 +00:00
|
|
|
|
2020-05-09 18:54:56 +00:00
|
|
|
|
2020-06-29 22:11:01 +00:00
|
|
|
class FlowExecutorShellView(TemplateView):
|
|
|
|
"""Executor Shell view, loads a dummy card with a spinner
|
|
|
|
that loads the next stage in the background."""
|
|
|
|
|
|
|
|
template_name = "flows/shell.html"
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs) -> Dict[str, Any]:
|
|
|
|
kwargs["exec_url"] = reverse("passbook_flows:flow-executor", kwargs=self.kwargs)
|
|
|
|
self.request.session[SESSION_KEY_GET] = self.request.GET
|
|
|
|
return kwargs
|
|
|
|
|
|
|
|
|
|
|
|
class CancelView(View):
|
|
|
|
"""View which canels the currently active plan"""
|
|
|
|
|
|
|
|
def get(self, request: HttpRequest) -> HttpResponse:
|
|
|
|
"""View which canels the currently active plan"""
|
|
|
|
if SESSION_KEY_PLAN in request.session:
|
|
|
|
del request.session[SESSION_KEY_PLAN]
|
|
|
|
LOGGER.debug("Canceled current plan")
|
2020-11-22 22:44:21 +00:00
|
|
|
return redirect("passbook_core:shell")
|
2020-06-29 22:11:01 +00:00
|
|
|
|
|
|
|
|
2020-05-09 18:54:56 +00:00
|
|
|
class ToDefaultFlow(View):
|
|
|
|
"""Redirect to default flow matching by designation"""
|
|
|
|
|
|
|
|
designation: Optional[FlowDesignation] = None
|
|
|
|
|
|
|
|
def dispatch(self, request: HttpRequest) -> HttpResponse:
|
2020-05-23 18:23:09 +00:00
|
|
|
flow = Flow.with_policy(request, designation=self.designation)
|
|
|
|
if not flow:
|
|
|
|
raise Http404
|
2020-05-11 13:01:14 +00:00
|
|
|
# If user already has a pending plan, clear it so we don't have to later.
|
|
|
|
if SESSION_KEY_PLAN in self.request.session:
|
|
|
|
plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
|
|
|
|
if plan.flow_pk != flow.pk.hex:
|
|
|
|
LOGGER.warning(
|
|
|
|
"f(def): Found existing plan for other flow, deleteing plan",
|
|
|
|
flow_slug=flow.slug,
|
|
|
|
)
|
|
|
|
del self.request.session[SESSION_KEY_PLAN]
|
2020-05-09 18:54:56 +00:00
|
|
|
return redirect_with_qs(
|
2020-05-23 22:57:25 +00:00
|
|
|
"passbook_flows:flow-executor-shell", request.GET, flow_slug=flow.slug
|
2020-05-09 18:54:56 +00:00
|
|
|
)
|
2020-05-23 22:57:25 +00:00
|
|
|
|
|
|
|
|
2020-06-07 14:35:08 +00:00
|
|
|
def to_stage_response(request: HttpRequest, source: HttpResponse) -> HttpResponse:
|
|
|
|
"""Convert normal HttpResponse into JSON Response"""
|
|
|
|
if isinstance(source, HttpResponseRedirect) or source.status_code == 302:
|
|
|
|
redirect_url = source["Location"]
|
|
|
|
if request.path != redirect_url:
|
|
|
|
return JsonResponse({"type": "redirect", "to": redirect_url})
|
|
|
|
return source
|
|
|
|
if isinstance(source, TemplateResponse):
|
|
|
|
return JsonResponse(
|
|
|
|
{"type": "template", "body": source.render().content.decode("utf-8")}
|
|
|
|
)
|
|
|
|
# Check for actual HttpResponse (without isinstance as we dont want to check inheritance)
|
|
|
|
if source.__class__ == HttpResponse:
|
|
|
|
return JsonResponse(
|
|
|
|
{"type": "template", "body": source.content.decode("utf-8")}
|
|
|
|
)
|
|
|
|
return source
|
2020-09-24 18:05:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ConfigureFlowInitView(LoginRequiredMixin, View):
|
|
|
|
"""Initiate planner for selected change flow and redirect to flow executor,
|
|
|
|
or raise Http404 if no configure_flow has been set."""
|
|
|
|
|
|
|
|
def get(self, request: HttpRequest, stage_uuid: str) -> HttpResponse:
|
|
|
|
"""Initiate planner for selected change flow and redirect to flow executor,
|
|
|
|
or raise Http404 if no configure_flow has been set."""
|
|
|
|
try:
|
|
|
|
stage: Stage = Stage.objects.get_subclass(pk=stage_uuid)
|
|
|
|
except Stage.DoesNotExist as exc:
|
|
|
|
raise Http404 from exc
|
2020-09-24 18:06:37 +00:00
|
|
|
if not isinstance(stage, ConfigurableStage):
|
2020-09-24 18:05:49 +00:00
|
|
|
LOGGER.debug("Stage does not inherit ConfigurableStage", stage=stage)
|
|
|
|
raise Http404
|
|
|
|
if not stage.configure_flow:
|
|
|
|
LOGGER.debug("Stage has no configure_flow set", stage=stage)
|
|
|
|
raise Http404
|
|
|
|
|
|
|
|
plan = FlowPlanner(stage.configure_flow).plan(
|
|
|
|
request, {PLAN_CONTEXT_PENDING_USER: request.user}
|
|
|
|
)
|
|
|
|
request.session[SESSION_KEY_PLAN] = plan
|
|
|
|
return redirect_with_qs(
|
|
|
|
"passbook_flows:flow-executor-shell",
|
|
|
|
self.request.GET,
|
|
|
|
flow_slug=stage.configure_flow.slug,
|
|
|
|
)
|