FEAT - TASKER INCIDENT RECOVERY: read-only аудит удалённых комментариев
This commit is contained in:
@@ -3,6 +3,7 @@ from html import escape
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.db.models import Count, Q
|
||||
from django.http import JsonResponse
|
||||
from django.utils import timezone
|
||||
from django.utils.decorators import method_decorator
|
||||
@@ -16,6 +17,7 @@ from plane.authentication.nodedc_workspace_policy import get_nodedc_workspace_cr
|
||||
from plane.authentication.views.nodedc_workspace_adapter import parse_json_body
|
||||
from plane.db.models import (
|
||||
Issue,
|
||||
IssueActivity,
|
||||
IssueAssignee,
|
||||
IssueComment,
|
||||
IssueLabel,
|
||||
@@ -37,6 +39,8 @@ MAX_AGENT_AVATAR_URL_LENGTH = 2_000_000
|
||||
MARKDOWN_HEADING_PATTERN = re.compile(r"^\s{0,3}#{1,6}\s+(.+?)\s*$")
|
||||
HEX_COLOR_PATTERN = re.compile(r"^#[0-9a-fA-F]{6}$")
|
||||
DATA_IMAGE_PATTERN = re.compile(r"^data:image/(png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$")
|
||||
DEFAULT_COMMENT_AUDIT_LIMIT = 100
|
||||
MAX_COMMENT_AUDIT_LIMIT = 500
|
||||
|
||||
|
||||
def unauthorized_response():
|
||||
@@ -133,6 +137,56 @@ def serialize_comment(comment):
|
||||
}
|
||||
|
||||
|
||||
def serialize_deleted_comment(comment, deletion_activity=None, include_body=False):
|
||||
serialized = {
|
||||
"id": str(comment.id),
|
||||
"issue_id": str(comment.issue_id),
|
||||
"actor_id": str(comment.actor_id) if comment.actor_id else None,
|
||||
"actor_display_name": comment.actor.display_name if comment.actor else None,
|
||||
"created_by_id": str(comment.created_by_id) if comment.created_by_id else None,
|
||||
"updated_by_id": str(comment.updated_by_id) if comment.updated_by_id else None,
|
||||
"updated_by_display_name": comment.updated_by.display_name if comment.updated_by else None,
|
||||
"created_at": comment.created_at.isoformat(),
|
||||
"updated_at": comment.updated_at.isoformat(),
|
||||
"edited_at": comment.edited_at.isoformat() if comment.edited_at else None,
|
||||
"deleted_at": comment.deleted_at.isoformat() if comment.deleted_at else None,
|
||||
"deletion_activity": None,
|
||||
}
|
||||
if include_body:
|
||||
serialized["body"] = comment.comment_html
|
||||
if deletion_activity is not None:
|
||||
serialized["deletion_activity"] = {
|
||||
"id": str(deletion_activity.id),
|
||||
"actor_id": str(deletion_activity.actor_id) if deletion_activity.actor_id else None,
|
||||
"actor_display_name": deletion_activity.actor.display_name if deletion_activity.actor else None,
|
||||
"created_at": deletion_activity.created_at.isoformat(),
|
||||
"epoch": deletion_activity.epoch,
|
||||
}
|
||||
return serialized
|
||||
|
||||
|
||||
def parse_comment_audit_integer(request, name, default, minimum, maximum):
|
||||
raw_value = request.GET.get(name)
|
||||
if raw_value in (None, ""):
|
||||
return default, None
|
||||
try:
|
||||
value = int(raw_value)
|
||||
except (TypeError, ValueError):
|
||||
return None, validation_error(f"invalid_{name}")
|
||||
if value < minimum or value > maximum:
|
||||
return None, validation_error(f"invalid_{name}")
|
||||
return value, None
|
||||
|
||||
|
||||
def parse_comment_audit_boolean(request, name):
|
||||
raw_value = request.GET.get(name, "false").strip().lower()
|
||||
if raw_value in {"1", "true", "yes"}:
|
||||
return True, None
|
||||
if raw_value in {"0", "false", "no", ""}:
|
||||
return False, None
|
||||
return None, validation_error(f"invalid_{name}")
|
||||
|
||||
|
||||
def resolve_project(project_id, workspace_slug=None):
|
||||
queryset = Project.objects.filter(
|
||||
id=project_id,
|
||||
@@ -1036,6 +1090,115 @@ class NodeDCAgentIssueCommentEndpoint(View):
|
||||
return JsonResponse({"ok": True, "comment": serialize_comment(comment)})
|
||||
|
||||
|
||||
@method_decorator(csrf_exempt, name="dispatch")
|
||||
class NodeDCAgentProjectCommentAuditEndpoint(View):
|
||||
def get(self, request, project_id):
|
||||
error_response = validate_internal_request(request)
|
||||
if error_response is not None:
|
||||
return error_response
|
||||
|
||||
project = resolve_project(project_id, request.GET.get("workspace_slug"))
|
||||
if project is None:
|
||||
return validation_error("project_not_found", status=404)
|
||||
|
||||
project_access_error = validate_agent_project_access(request, project)
|
||||
if project_access_error is not None:
|
||||
return project_access_error
|
||||
|
||||
limit, error_response = parse_comment_audit_integer(
|
||||
request,
|
||||
"limit",
|
||||
DEFAULT_COMMENT_AUDIT_LIMIT,
|
||||
1,
|
||||
MAX_COMMENT_AUDIT_LIMIT,
|
||||
)
|
||||
if error_response is not None:
|
||||
return error_response
|
||||
offset, error_response = parse_comment_audit_integer(request, "offset", 0, 0, 1_000_000)
|
||||
if error_response is not None:
|
||||
return error_response
|
||||
include_bodies, error_response = parse_comment_audit_boolean(request, "include_bodies")
|
||||
if error_response is not None:
|
||||
return error_response
|
||||
|
||||
issues = Issue.issue_objects.filter(project=project).order_by("sequence_id")
|
||||
issue_id = request.GET.get("issue_id")
|
||||
if issue_id:
|
||||
issues = issues.filter(id=issue_id)
|
||||
if not issues.exists():
|
||||
return validation_error("issue_not_found", status=404)
|
||||
|
||||
issue_rows = list(issues.values("id", "sequence_id", "name"))
|
||||
issue_ids = [row["id"] for row in issue_rows]
|
||||
comments = IssueComment.all_objects.filter(project=project, issue_id__in=issue_ids)
|
||||
grouped_counts = {
|
||||
str(row["issue_id"]): {
|
||||
"active_count": row["active_count"],
|
||||
"deleted_count": row["deleted_count"],
|
||||
}
|
||||
for row in comments.values("issue_id").annotate(
|
||||
active_count=Count("id", filter=Q(deleted_at__isnull=True)),
|
||||
deleted_count=Count("id", filter=Q(deleted_at__isnull=False)),
|
||||
)
|
||||
}
|
||||
|
||||
active_count = comments.filter(deleted_at__isnull=True).count()
|
||||
deleted_comments = comments.filter(deleted_at__isnull=False)
|
||||
deleted_count = deleted_comments.count()
|
||||
deleted_page = list(
|
||||
deleted_comments.select_related("actor", "created_by", "updated_by", "issue")
|
||||
.order_by("-deleted_at", "-created_at", "-id")[offset : offset + limit]
|
||||
)
|
||||
deleted_ids = [comment.id for comment in deleted_page]
|
||||
deletion_activities = {}
|
||||
for activity in (
|
||||
IssueActivity.all_objects.filter(
|
||||
project=project,
|
||||
field="comment",
|
||||
verb="deleted",
|
||||
issue_comment_id__in=deleted_ids,
|
||||
)
|
||||
.select_related("actor")
|
||||
.order_by("issue_comment_id", "-created_at")
|
||||
):
|
||||
deletion_activities.setdefault(str(activity.issue_comment_id), activity)
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
"ok": True,
|
||||
"project": serialize_project(project),
|
||||
"inventory": {
|
||||
"active_count": active_count,
|
||||
"deleted_count": deleted_count,
|
||||
"issue_count": len(issue_rows),
|
||||
"issues": [
|
||||
{
|
||||
"issue_id": str(row["id"]),
|
||||
"sequence_id": row["sequence_id"],
|
||||
"title": row["name"],
|
||||
**grouped_counts.get(
|
||||
str(row["id"]),
|
||||
{"active_count": 0, "deleted_count": 0},
|
||||
),
|
||||
}
|
||||
for row in issue_rows
|
||||
],
|
||||
"deleted_comments": [
|
||||
serialize_deleted_comment(
|
||||
comment,
|
||||
deletion_activities.get(str(comment.id)),
|
||||
include_body=include_bodies,
|
||||
)
|
||||
for comment in deleted_page
|
||||
],
|
||||
"offset": offset,
|
||||
"limit": limit,
|
||||
"has_more": offset + len(deleted_page) < deleted_count,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@method_decorator(csrf_exempt, name="dispatch")
|
||||
class NodeDCAgentIssueLabelsEndpoint(View):
|
||||
def put(self, request, issue_id):
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from django.test import RequestFactory
|
||||
from django.utils import timezone
|
||||
|
||||
from plane.authentication.views import nodedc_agent_adapter
|
||||
from plane.authentication.views.nodedc_agent_adapter import NodeDCAgentProjectCommentAuditEndpoint
|
||||
from plane.db.models import Issue, IssueActivity, IssueComment, Project, State, Workspace, WorkspaceMember
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.django_db
|
||||
def test_comment_audit_reports_active_and_soft_deleted_comments(monkeypatch, create_user):
|
||||
workspace = Workspace.objects.create(
|
||||
name="Audit Workspace",
|
||||
slug="audit-workspace",
|
||||
owner=create_user,
|
||||
)
|
||||
WorkspaceMember.objects.create(workspace=workspace, member=create_user, role=20, is_active=True)
|
||||
project = Project.objects.create(
|
||||
name="Audit Project",
|
||||
identifier="AUDIT",
|
||||
workspace=workspace,
|
||||
created_by=create_user,
|
||||
)
|
||||
state = State.objects.create(
|
||||
name="Todo",
|
||||
project=project,
|
||||
workspace=workspace,
|
||||
group="backlog",
|
||||
default=True,
|
||||
)
|
||||
issue = Issue.objects.create(
|
||||
name="Comment incident",
|
||||
workspace=workspace,
|
||||
project=project,
|
||||
state=state,
|
||||
created_by=create_user,
|
||||
)
|
||||
IssueComment.objects.create(
|
||||
workspace=workspace,
|
||||
project=project,
|
||||
issue=issue,
|
||||
actor=create_user,
|
||||
comment_html="<p>active</p>",
|
||||
created_by=create_user,
|
||||
)
|
||||
deleted_comment = IssueComment.objects.create(
|
||||
workspace=workspace,
|
||||
project=project,
|
||||
issue=issue,
|
||||
actor=create_user,
|
||||
comment_html="<p>recover me</p>",
|
||||
created_by=create_user,
|
||||
)
|
||||
deleted_comment.deleted_at = timezone.now()
|
||||
deleted_comment.updated_by = create_user
|
||||
deleted_comment.save(update_fields=["deleted_at", "updated_by", "updated_at"], disable_auto_set_user=True)
|
||||
deletion_activity = IssueActivity.objects.create(
|
||||
workspace=workspace,
|
||||
project=project,
|
||||
issue=issue,
|
||||
issue_comment_id=deleted_comment.id,
|
||||
actor=create_user,
|
||||
field="comment",
|
||||
verb="deleted",
|
||||
comment="deleted the comment",
|
||||
epoch=timezone.now().timestamp(),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(nodedc_agent_adapter, "is_internal_logout_request_authorized", lambda request: True)
|
||||
monkeypatch.setattr(
|
||||
nodedc_agent_adapter,
|
||||
"get_nodedc_workspace_creation_policy",
|
||||
lambda owner, workspace_slug: {"service_modules": {"codex_agents": True}},
|
||||
)
|
||||
request = RequestFactory().get(
|
||||
"/api/internal/nodedc/agent/projects/project/comments/audit",
|
||||
{"workspace_slug": workspace.slug, "include_bodies": "true"},
|
||||
HTTP_X_NODEDC_AGENT_ID="agent-1",
|
||||
HTTP_X_NODEDC_AGENT_OWNER_USER_ID=str(create_user.id),
|
||||
HTTP_X_NODEDC_AGENT_TOKEN_ID="token-1",
|
||||
)
|
||||
|
||||
response = NodeDCAgentProjectCommentAuditEndpoint.as_view()(request, project_id=project.id)
|
||||
payload = json.loads(response.content)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert payload["inventory"]["active_count"] == 1
|
||||
assert payload["inventory"]["deleted_count"] == 1
|
||||
assert payload["inventory"]["issues"] == [
|
||||
{
|
||||
"issue_id": str(issue.id),
|
||||
"sequence_id": issue.sequence_id,
|
||||
"title": issue.name,
|
||||
"active_count": 1,
|
||||
"deleted_count": 1,
|
||||
}
|
||||
]
|
||||
assert payload["inventory"]["deleted_comments"][0]["id"] == str(deleted_comment.id)
|
||||
assert payload["inventory"]["deleted_comments"][0]["body"] == "<p>recover me</p>"
|
||||
assert payload["inventory"]["deleted_comments"][0]["deletion_activity"]["id"] == str(deletion_activity.id)
|
||||
assert payload["inventory"]["deleted_comments"][0]["deletion_activity"]["actor_id"] == str(create_user.id)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_comment_audit_rejects_unbounded_limit(monkeypatch):
|
||||
monkeypatch.setattr(nodedc_agent_adapter, "is_internal_logout_request_authorized", lambda request: True)
|
||||
request = RequestFactory().get(
|
||||
"/api/internal/nodedc/agent/projects/project/comments/audit",
|
||||
{"limit": "501"},
|
||||
HTTP_X_NODEDC_AGENT_ID="agent-1",
|
||||
HTTP_X_NODEDC_AGENT_OWNER_USER_ID="owner-1",
|
||||
HTTP_X_NODEDC_AGENT_TOKEN_ID="token-1",
|
||||
)
|
||||
|
||||
value, response = nodedc_agent_adapter.parse_comment_audit_integer(
|
||||
request,
|
||||
"limit",
|
||||
nodedc_agent_adapter.DEFAULT_COMMENT_AUDIT_LIMIT,
|
||||
1,
|
||||
nodedc_agent_adapter.MAX_COMMENT_AUDIT_LIMIT,
|
||||
)
|
||||
|
||||
assert value is None
|
||||
assert response.status_code == 400
|
||||
assert json.loads(response.content) == {"ok": False, "error": "invalid_limit"}
|
||||
@@ -22,6 +22,7 @@ from plane.authentication.views.nodedc_agent_adapter import (
|
||||
NodeDCAgentIssueListEndpoint,
|
||||
NodeDCAgentIssueMoveEndpoint,
|
||||
NodeDCAgentIssueUpdateEndpoint,
|
||||
NodeDCAgentProjectCommentAuditEndpoint,
|
||||
NodeDCAgentProjectContextEndpoint,
|
||||
NodeDCAgentProjectLabelsEnsureEndpoint,
|
||||
NodeDCAgentProjectResolveEndpoint,
|
||||
@@ -100,6 +101,11 @@ urlpatterns = [
|
||||
NodeDCAgentProjectLabelsEnsureEndpoint.as_view(),
|
||||
name="nodedc-agent-project-labels-ensure",
|
||||
),
|
||||
path(
|
||||
"api/internal/nodedc/agent/projects/<uuid:project_id>/comments/audit",
|
||||
NodeDCAgentProjectCommentAuditEndpoint.as_view(),
|
||||
name="nodedc-agent-project-comment-audit",
|
||||
),
|
||||
path(
|
||||
"api/internal/nodedc/agent/issues",
|
||||
NodeDCAgentIssueListEndpoint.as_view(),
|
||||
|
||||
Reference in New Issue
Block a user