Skip to content

Commit

Permalink
Merge branch 'hotfix' into 'master'
Browse files Browse the repository at this point in the history
Hotfix

See merge request arenadata/development/adcm!3384
  • Loading branch information
kuhella committed Nov 28, 2023
2 parents 2d81344 + cce7e49 commit 270d139
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 11 deletions.
2 changes: 1 addition & 1 deletion python/adcm/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@
},
"audit": {
"handlers": ["audit_file_handler"],
"level": LOG_LEVEL,
"level": "INFO",
"propagate": True,
},
"task_runner_err": {
Expand Down
4 changes: 3 additions & 1 deletion python/audit/cef_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class CEFLogConstants:
device_product: str = "Arenadata Cluster Manager"
adcm_version: str = settings.ADCM_VERSION
operation_name_session: str = "User logged"
extension_keys: tuple[str] = ("actor", "act", "operation", "resource", "result", "timestamp")
extension_keys: tuple[str, ...] = ("actor", "act", "operation", "resource", "result", "timestamp", "address")


def cef_logger(
Expand All @@ -47,6 +47,7 @@ def cef_logger(
extension["operation"] = operation_name
extension["result"] = audit_instance.login_result
extension["timestamp"] = str(audit_instance.login_time)
extension["address"] = audit_instance.address

elif isinstance(audit_instance, AuditLog):
operation_name = audit_instance.operation_name
Expand All @@ -60,6 +61,7 @@ def cef_logger(
if audit_instance.operation_result == AuditLogOperationResult.DENIED:
severity = 3
extension["timestamp"] = str(audit_instance.operation_time)
extension["address"] = audit_instance.address

else:
raise NotImplementedError
Expand Down
15 changes: 12 additions & 3 deletions python/audit/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from audit.cef_logger import cef_logger
from audit.models import AuditSession, AuditSessionLoginResult, AuditUser
from audit.utils import get_client_ip
from cm.models import ADCM, ConfigLog
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
Expand All @@ -30,6 +31,7 @@ def __init__(self, get_response):
@staticmethod
def _audit(
request_path: str,
request_host: str | None,
user: User | AnonymousUser | None = None,
username: str = None,
) -> tuple[User | None, AuditSessionLoginResult]:
Expand All @@ -53,8 +55,10 @@ def _audit(
if user is not None:
audit_user = AuditUser.objects.filter(username=user.username).order_by("-pk").first()

auditsession = AuditSession.objects.create(user=audit_user, login_result=result, login_details=details)
cef_logger(audit_instance=auditsession, signature_id=resolve(request_path).route)
audit_session = AuditSession.objects.create(
user=audit_user, login_result=result, login_details=details, address=request_host
)
cef_logger(audit_instance=audit_session, signature_id=resolve(request_path).route)

return user, result

Expand Down Expand Up @@ -141,7 +145,12 @@ def __call__(self, request):
response = self.get_response(request)

username = request.POST.get("username") or username or request.user.username
user, result = self._audit(request.path, user=request.user, username=username)
user, result = self._audit(
request_path=request.path,
request_host=get_client_ip(request=request),
user=request.user,
username=username,
)

login_attempts_response = None
if user:
Expand Down
34 changes: 34 additions & 0 deletions python/audit/migrations/0006_add_address.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Generated by Django 3.2.19 on 2023-11-14 08:35

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("audit", "0005_audit_user"),
]

operations = [
migrations.AddField(
model_name="auditlog",
name="address",
field=models.CharField(max_length=255, null=True),
),
migrations.AddField(
model_name="auditsession",
name="address",
field=models.CharField(max_length=255, null=True),
),
]
2 changes: 2 additions & 0 deletions python/audit/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,15 @@ class AuditLog(Model):
operation_time = DateTimeField(auto_now_add=True)
user = ForeignKey(AuditUser, on_delete=CASCADE, null=True)
object_changes = JSONField(default=dict)
address = CharField(max_length=255, null=True)


class AuditSession(Model):
user = ForeignKey(AuditUser, on_delete=CASCADE, null=True)
login_result = CharField(max_length=2000, choices=AuditSessionLoginResult.choices)
login_time = DateTimeField(auto_now_add=True)
login_details = JSONField(default=dict, null=True)
address = CharField(max_length=255, null=True)


@dataclass
Expand Down
25 changes: 19 additions & 6 deletions python/audit/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
TaskLog,
)
from django.contrib.auth.models import User as DjangoUser
from django.core.handlers.wsgi import WSGIRequest
from django.db.models import Model, ObjectDoesNotExist
from django.http.response import Http404
from django.urls import resolve
Expand All @@ -48,7 +49,6 @@
from rbac.models import Group, Policy, Role, User
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.generics import GenericAPIView
from rest_framework.request import Request
from rest_framework.status import (
HTTP_400_BAD_REQUEST,
HTTP_403_FORBIDDEN,
Expand All @@ -58,18 +58,18 @@
from rest_framework.viewsets import ModelViewSet


def _get_view_and_request(args) -> tuple[GenericAPIView, Request]:
def _get_view_and_request(args) -> tuple[GenericAPIView, WSGIRequest]:
if len(args) == 2: # for audit view methods
view: GenericAPIView = args[0]
request: Request = args[1]
request: WSGIRequest = args[1]
else: # for audit has_permissions method
view: GenericAPIView = args[2]
request: Request = args[1]
request: WSGIRequest = args[1]

return view, request


def _get_deleted_obj(view: GenericAPIView, request: Request, kwargs) -> Model | None:
def _get_deleted_obj(view: GenericAPIView, request: WSGIRequest, kwargs) -> Model | None:
# pylint: disable=too-many-branches

try:
Expand Down Expand Up @@ -221,7 +221,7 @@ def wrapped(*args, **kwargs):
audit_object: AuditObject
operation_name: str
view: GenericAPIView | ModelViewSet
request: Request
request: WSGIRequest
object_changes: dict

error = None
Expand Down Expand Up @@ -347,6 +347,7 @@ def wrapped(*args, **kwargs):
operation_result=operation_result,
user=audit_user,
object_changes=object_changes,
address=get_client_ip(request=request),
)
cef_logger(audit_instance=auditlog, signature_id=resolve(request.path).route)

Expand Down Expand Up @@ -384,3 +385,15 @@ def make_audit_log(operation_type, result, operation_status):
user=AuditUser.objects.get(username="system"),
)
cef_logger(audit_instance=audit_log, signature_id="Background operation", empty_resource=True)


def get_client_ip(request: WSGIRequest) -> str | None:
header_fields = ["HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED_HOST", "HTTP_X_FORWARDED_SERVER", "REMOTE_ADDR"]
host = None

for field in header_fields:
if field in request.META:
host = request.META[field].split(",")[-1]
break

return host

0 comments on commit 270d139

Please sign in to comment.