2018-11-23 16:05:41 +00:00
|
|
|
"""passbook audit models"""
|
2019-12-05 15:14:08 +00:00
|
|
|
from enum import Enum
|
|
|
|
from inspect import getmodule, stack
|
2020-02-14 14:17:40 +00:00
|
|
|
from typing import Any, Dict, Optional
|
2020-05-20 07:17:06 +00:00
|
|
|
from uuid import UUID, uuid4
|
2019-12-05 15:14:08 +00:00
|
|
|
|
2018-11-23 16:05:41 +00:00
|
|
|
from django.conf import settings
|
2018-12-10 14:26:28 +00:00
|
|
|
from django.contrib.auth.models import AnonymousUser
|
2018-12-10 12:47:51 +00:00
|
|
|
from django.core.exceptions import ValidationError
|
2018-11-23 16:05:41 +00:00
|
|
|
from django.db import models
|
2020-09-18 21:39:37 +00:00
|
|
|
from django.db.models.base import Model
|
2019-12-05 15:14:08 +00:00
|
|
|
from django.http import HttpRequest
|
2018-12-10 12:47:51 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2020-08-15 19:04:22 +00:00
|
|
|
from django.views.debug import SafeExceptionReporterFilter
|
2019-12-05 15:14:08 +00:00
|
|
|
from guardian.shortcuts import get_anonymous_user
|
2019-10-01 08:24:10 +00:00
|
|
|
from structlog import get_logger
|
2018-11-23 16:05:41 +00:00
|
|
|
|
2020-09-18 21:39:37 +00:00
|
|
|
from passbook.core.middleware import SESSION_IMPERSONATE_ORIGINAL_USER
|
2019-12-05 13:33:55 +00:00
|
|
|
from passbook.lib.utils.http import get_client_ip
|
2018-11-23 16:05:41 +00:00
|
|
|
|
2019-10-04 08:08:53 +00:00
|
|
|
LOGGER = get_logger()
|
2018-11-23 16:05:41 +00:00
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
|
2020-06-29 17:13:07 +00:00
|
|
|
def cleanse_dict(source: Dict[Any, Any]) -> Dict[Any, Any]:
|
|
|
|
"""Cleanse a dictionary, recursively"""
|
|
|
|
final_dict = {}
|
|
|
|
for key, value in source.items():
|
|
|
|
try:
|
2020-08-15 19:04:22 +00:00
|
|
|
if SafeExceptionReporterFilter.hidden_settings.search(key):
|
|
|
|
final_dict[key] = SafeExceptionReporterFilter.cleansed_substitute
|
2020-06-29 17:13:07 +00:00
|
|
|
else:
|
|
|
|
final_dict[key] = value
|
|
|
|
except TypeError:
|
|
|
|
final_dict[key] = value
|
|
|
|
if isinstance(value, dict):
|
|
|
|
final_dict[key] = cleanse_dict(value)
|
|
|
|
return final_dict
|
|
|
|
|
|
|
|
|
2020-09-18 21:39:37 +00:00
|
|
|
def model_to_dict(model: Model) -> Dict[str, Any]:
|
|
|
|
"""Convert model to dict"""
|
|
|
|
name = str(model)
|
|
|
|
if hasattr(model, "name"):
|
|
|
|
name = model.name
|
|
|
|
return {
|
|
|
|
"app": model._meta.app_label,
|
|
|
|
"model_name": model._meta.model_name,
|
|
|
|
"pk": model.pk,
|
|
|
|
"name": name,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-12-31 12:33:07 +00:00
|
|
|
def sanitize_dict(source: Dict[Any, Any]) -> Dict[Any, Any]:
|
|
|
|
"""clean source of all Models that would interfere with the JSONField.
|
|
|
|
Models are replaced with a dictionary of {
|
|
|
|
app: str,
|
|
|
|
name: str,
|
|
|
|
pk: Any
|
|
|
|
}"""
|
2020-06-29 14:19:56 +00:00
|
|
|
final_dict = {}
|
2019-12-31 12:33:07 +00:00
|
|
|
for key, value in source.items():
|
|
|
|
if isinstance(value, dict):
|
2020-06-29 14:19:56 +00:00
|
|
|
final_dict[key] = sanitize_dict(value)
|
2019-12-31 12:33:07 +00:00
|
|
|
elif isinstance(value, models.Model):
|
2020-09-18 21:39:37 +00:00
|
|
|
final_dict[key] = sanitize_dict(model_to_dict(value))
|
2020-01-02 12:00:16 +00:00
|
|
|
elif isinstance(value, UUID):
|
2020-06-29 14:19:56 +00:00
|
|
|
final_dict[key] = value.hex
|
|
|
|
else:
|
|
|
|
final_dict[key] = value
|
|
|
|
return final_dict
|
2019-12-31 12:33:07 +00:00
|
|
|
|
|
|
|
|
2019-12-05 15:14:08 +00:00
|
|
|
class EventAction(Enum):
|
|
|
|
"""All possible actions to save into the audit log"""
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
LOGIN = "login"
|
|
|
|
LOGIN_FAILED = "login_failed"
|
|
|
|
LOGOUT = "logout"
|
|
|
|
AUTHORIZE_APPLICATION = "authorize_application"
|
|
|
|
SUSPICIOUS_REQUEST = "suspicious_request"
|
|
|
|
SIGN_UP = "sign_up"
|
|
|
|
PASSWORD_RESET = "password_reset" # noqa # nosec
|
|
|
|
INVITE_CREATED = "invitation_created"
|
|
|
|
INVITE_USED = "invitation_used"
|
2020-09-18 21:39:37 +00:00
|
|
|
IMPERSONATION_STARTED = "impersonation_started"
|
|
|
|
IMPERSONATION_ENDED = "impersonation_ended"
|
2019-12-31 11:51:16 +00:00
|
|
|
CUSTOM = "custom"
|
2019-12-05 15:14:08 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def as_choices():
|
|
|
|
"""Generate choices of actions used for database"""
|
2020-05-06 22:32:03 +00:00
|
|
|
return tuple(
|
|
|
|
(x, y.value) for x, y in getattr(EventAction, "__members__").items()
|
|
|
|
)
|
2019-12-05 15:14:08 +00:00
|
|
|
|
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
class Event(models.Model):
|
2019-10-28 13:26:34 +00:00
|
|
|
"""An individual audit log event"""
|
2018-11-23 16:05:41 +00:00
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
event_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
2019-12-31 11:51:16 +00:00
|
|
|
user = models.ForeignKey(
|
|
|
|
settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL
|
|
|
|
)
|
2019-12-05 15:14:08 +00:00
|
|
|
action = models.TextField(choices=EventAction.as_choices())
|
2018-11-23 16:05:41 +00:00
|
|
|
date = models.DateTimeField(auto_now_add=True)
|
|
|
|
app = models.TextField()
|
2020-08-15 19:04:22 +00:00
|
|
|
context = models.JSONField(default=dict, blank=True)
|
2019-12-05 15:14:08 +00:00
|
|
|
client_ip = models.GenericIPAddressField(null=True)
|
2018-12-13 17:01:45 +00:00
|
|
|
created = models.DateTimeField(auto_now_add=True)
|
2018-12-10 12:47:51 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2019-12-05 15:14:08 +00:00
|
|
|
def _get_app_from_request(request: HttpRequest) -> str:
|
|
|
|
if not isinstance(request, HttpRequest):
|
|
|
|
return ""
|
|
|
|
return request.resolver_match.app_name
|
|
|
|
|
|
|
|
@staticmethod
|
2019-12-31 11:51:16 +00:00
|
|
|
def new(
|
|
|
|
action: EventAction,
|
|
|
|
app: Optional[str] = None,
|
|
|
|
_inspect_offset: int = 1,
|
|
|
|
**kwargs,
|
|
|
|
) -> "Event":
|
2019-12-05 15:14:08 +00:00
|
|
|
"""Create new Event instance from arguments. Instance is NOT saved."""
|
|
|
|
if not isinstance(action, EventAction):
|
2019-12-31 11:51:16 +00:00
|
|
|
raise ValueError(
|
|
|
|
f"action must be EventAction instance but was {type(action)}"
|
|
|
|
)
|
2019-12-05 15:14:08 +00:00
|
|
|
if not app:
|
|
|
|
app = getmodule(stack()[_inspect_offset][0]).__name__
|
2020-06-29 17:13:07 +00:00
|
|
|
cleaned_kwargs = cleanse_dict(sanitize_dict(kwargs))
|
2019-12-31 12:33:07 +00:00
|
|
|
event = Event(action=action.value, app=app, context=cleaned_kwargs)
|
2019-12-05 15:14:08 +00:00
|
|
|
return event
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
def from_http(
|
|
|
|
self, request: HttpRequest, user: Optional[settings.AUTH_USER_MODEL] = None
|
|
|
|
) -> "Event":
|
2019-12-05 15:14:08 +00:00
|
|
|
"""Add data from a Django-HttpRequest, allowing the creation of
|
|
|
|
Events independently from requests.
|
|
|
|
`user` arguments optionally overrides user from requests."""
|
2019-12-31 11:51:16 +00:00
|
|
|
if hasattr(request, "user"):
|
2019-12-05 15:14:08 +00:00
|
|
|
if isinstance(request.user, AnonymousUser):
|
|
|
|
self.user = get_anonymous_user()
|
|
|
|
else:
|
|
|
|
self.user = request.user
|
|
|
|
if user:
|
|
|
|
self.user = user
|
2020-09-18 21:39:37 +00:00
|
|
|
# Check if we're currently impersonating, and add that user
|
|
|
|
if hasattr(request, "session"):
|
|
|
|
if SESSION_IMPERSONATE_ORIGINAL_USER in request.session:
|
|
|
|
self.context["on_behalf_of"] = model_to_dict(
|
|
|
|
request.session[SESSION_IMPERSONATE_ORIGINAL_USER]
|
|
|
|
)
|
2019-12-05 15:14:08 +00:00
|
|
|
# User 255.255.255.255 as fallback if IP cannot be determined
|
2019-12-31 11:51:16 +00:00
|
|
|
self.client_ip = get_client_ip(request) or "255.255.255.255"
|
2019-12-05 15:14:08 +00:00
|
|
|
# If there's no app set, we get it from the requests too
|
|
|
|
if not self.app:
|
|
|
|
self.app = Event._get_app_from_request(request)
|
|
|
|
self.save()
|
|
|
|
return self
|
2018-11-23 16:05:41 +00:00
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
2018-12-10 12:47:51 +00:00
|
|
|
if not self._state.adding:
|
2019-12-31 11:51:16 +00:00
|
|
|
raise ValidationError(
|
|
|
|
"you may not edit an existing %s" % self._meta.model_name
|
|
|
|
)
|
2020-02-18 16:05:11 +00:00
|
|
|
LOGGER.debug(
|
|
|
|
"Created Audit event",
|
|
|
|
action=self.action,
|
|
|
|
context=self.context,
|
|
|
|
client_ip=self.client_ip,
|
2020-02-24 18:14:43 +00:00
|
|
|
user=self.user,
|
2020-02-18 16:05:11 +00:00
|
|
|
)
|
2019-12-05 15:14:08 +00:00
|
|
|
return super().save(*args, **kwargs)
|
2018-12-10 12:47:51 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
verbose_name = _("Audit Event")
|
|
|
|
verbose_name_plural = _("Audit Events")
|