forked from certsocietegenerale/FIR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
executable file
·241 lines (197 loc) · 7.99 KB
/
Copy pathapi.py
File metadata and controls
executable file
·241 lines (197 loc) · 7.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
from django.core.files import File as FileWrapper
from django.shortcuts import get_object_or_404
from rest_framework import serializers, viewsets, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import PermissionDenied
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response
from django_filters.rest_framework import (
NumberFilter,
CharFilter,
DateTimeFilter,
FilterSet,
DjangoFilterBackend,
)
from rest_framework.mixins import (
DestroyModelMixin,
ListModelMixin,
RetrieveModelMixin,
)
from incidents.models import Incident
from fir_api.permissions import CanViewIncident, CanWriteIncident
from fir_artifacts.models import File, Artifact
from fir_artifacts.files import handle_uploaded_file, do_download, do_download_archive
class ArtifactFilter(FilterSet):
"""
A custom filter class for artifacts filtering
"""
id = NumberFilter(field_name="id")
type = CharFilter(field_name="type")
value = CharFilter(field_name="value", lookup_expr="icontains")
incidents = NumberFilter(field_name="incidents__id")
class Meta:
model = Artifact
fields = ["id", "type", "incidents", "value"]
class FileFilter(FilterSet):
"""
Custom filtering so we can partially match on name
"""
id = NumberFilter(field_name="id")
description = CharFilter(field_name="description", lookup_expr="icontains")
uploaded_before = DateTimeFilter(field_name="date", lookup_expr="lte")
uploaded_after = DateTimeFilter(field_name="date", lookup_expr="gte")
incident = NumberFilter(field_name="incident__id")
class Meta:
model = File
fields = ["id", "description", "incident"]
class ArtifactSerializer(serializers.ModelSerializer):
"""
Serializer for /api/artifacts
"""
incidents = serializers.SerializerMethodField()
def get_incidents(self, obj):
request = self.context.get("request")
if not request:
return []
allowed_incidents = Incident.authorization.for_user(
request.user, "incidents.view_incidents"
)
return list(
obj.incidents.filter(
id__in=allowed_incidents.values_list("id", flat=True)
).values_list("id", flat=True)
)
class Meta:
model = Artifact
fields = ["id", "type", "value", "incidents"]
read_only_fields = ["id", "type", "value"]
class IncidentArtifactSerializer(serializers.ModelSerializer):
"""
Serializer for /api/incident/<id>
"""
incidents_count = serializers.IntegerField(source="incidents.count", read_only=True)
class Meta:
model = Artifact
fields = ("id", "type", "value", "incidents_count")
read_only_fields = ("id", "type", "value", "incidents_count")
class FileSerializer(serializers.ModelSerializer):
incident = serializers.HyperlinkedRelatedField(
read_only=True, view_name="api:incidents-detail"
)
url = serializers.HyperlinkedIdentityField(view_name="api:files-detail")
class Meta:
model = File
fields = ["id", "description", "url", "incident"]
read_only_fields = ["id"]
class FileViewSet(
DestroyModelMixin, ListModelMixin, RetrieveModelMixin, viewsets.GenericViewSet
):
"""
API endpoint for listing files.
Files can be uploaded and downloaded via endpoints /files/<incidentID>/upload , /files/<fileID>/download and /files/<incidentID>/download-all
"""
serializer_class = FileSerializer
permission_classes = [IsAuthenticated, CanViewIncident | CanWriteIncident]
filter_backends = [DjangoFilterBackend, OrderingFilter]
ordering_fields = ["id", "date", "incident"]
filterset_class = FileFilter
def get_queryset(self):
incidents_allowed = Incident.authorization.for_user(
self.request.user, "incidents.view_incidents"
)
queryset = File.objects.filter(incident__in=incidents_allowed).order_by(
"id", "date"
)
return queryset
@action(detail=True)
def download(self, request, pk):
file_object = get_object_or_404(File, pk=pk)
self.check_object_permissions(self.request, file_object.incident)
return do_download(request, pk)
@action(detail=True, url_path="download-all")
def download_all(self, request, pk):
inc = get_object_or_404(Incident, pk=pk)
self.check_object_permissions(self.request, Incident.objects.get(pk=pk))
if inc.file_set.count() == 0:
return Response(
data={"Error": "Incident does not have any file."},
status=status.HTTP_404_NOT_FOUND,
)
return do_download_archive(request, pk)
@action(detail=True, methods=["POST"])
def upload(self, request, pk):
incident = get_object_or_404(
Incident.authorization.for_user(
self.request.user, "incidents.handle_incidents"
),
pk=pk,
)
files_added = []
if type(self.request.data).__name__ == "dict":
uploaded_files = request.FILES.get("file", [])
else:
uploaded_files = request.FILES.getlist("file", [])
if type(self.request.data).__name__ == "dict":
descriptions = request.data.get("description", [])
else:
descriptions = request.data.getlist("description", [])
if len(descriptions) != len(uploaded_files):
return Response(
data={"Error": "Missing 'description' or 'file'."},
status=status.HTTP_400_BAD_REQUEST,
)
for uploaded_file, description in zip(uploaded_files, descriptions):
file_wrapper = FileWrapper(uploaded_file.file)
file_wrapper.name = uploaded_file.name
file = handle_uploaded_file(file_wrapper, description, incident)
files_added.append(file)
resp_data = FileSerializer(
files_added, many=True, context={"request": request}
).data
return Response(resp_data)
def perform_destroy(self, instance):
hashes = instance.get_hashes()
for h in hashes:
try:
a = Artifact.objects.get(value=hashes[h]).delete()
except Artifact.NotFound:
pass
super().perform_destroy(instance)
class ArtifactViewSet(ListModelMixin, RetrieveModelMixin, viewsets.GenericViewSet):
"""
API endpoint to list artifacts.
Artifacts can't be created or edited via the API, they are automatically generated from incident descriptions and comments.
You can detach an artifact from an incident by accessing /artifacts/<id>/detach/<incidentID>
"""
serializer_class = ArtifactSerializer
permission_classes = [IsAuthenticated]
filter_backends = [DjangoFilterBackend, OrderingFilter]
ordering_fields = ["id", "type", "value"]
filterset_class = ArtifactFilter
def get_queryset(self):
incidents_allowed = Incident.authorization.for_user(
self.request.user, "incidents.view_incidents"
)
queryset = (
Artifact.objects.filter(incidents__in=incidents_allowed)
.distinct()
.order_by("id")
)
return queryset
@action(detail=True, methods=["POST"], url_path=r"detach/(?P<incident_id>\d+)")
def detach(self, request, pk, incident_id):
artifact = get_object_or_404(Artifact, pk=pk)
try:
related = artifact.incidents.get(pk=incident_id)
except Incident.DoesNotExist:
return Response(
data={"detail": "Unknown related object"},
status=status.HTTP_404_NOT_FOUND,
)
if not request.user.has_perm("incidents.handle_incidents", obj=related):
raise PermissionDenied()
artifact.incidents.remove(related)
if artifact.incidents.count() == 0:
artifact.delete()
return Response({"detail": "Artifact detached"})