-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_csrf.py
438 lines (356 loc) · 13.9 KB
/
test_csrf.py
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2015 Glencoe Software, Inc.
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Simple integration tests to ensure that the CSRF middleware is enabled and
working correctly.
"""
import omero
import omero.clients
from omero.rtypes import rstring
from omeroweb.testlib import IWebTest
from omeroweb.testlib import post, get, _response, csrf_response
from django.test import Client
from django.core.urlresolvers import reverse
try:
from PIL import Image, ImageDraw # see ticket:2597
except ImportError: # see ticket:2597
import Image
import ImageDraw
from random import randint as rint
import tempfile
class TestCsrf(IWebTest):
"""
Tests to ensure that Django CSRF middleware for OMERO.web is enabled and
working correctly.
"""
def image_with_channels(self):
"""
Returns a new foundational Image with Channel objects attached for
view method testing.
"""
pixels = self.create_pixels(client=self.client)
for the_c in range(pixels.getSizeC().val):
channel = omero.model.ChannelI()
channel.logicalChannel = omero.model.LogicalChannelI()
pixels.addChannel(channel)
image = pixels.getImage()
return self.sf.getUpdateService().saveAndReturnObject(image)
def new_tag(self):
"""
Returns a new Tag objects
"""
tag = omero.model.TagAnnotationI()
tag.textValue = rstring(self.uuid())
tag.ns = rstring("pytest")
return self.sf.getUpdateService().saveAndReturnObject(tag)
# Client
def test_csrf_middleware_enabled(self):
"""
If the CSRF middleware is enabled login attempts that do not include
the CSRF token should fail with an HTTP 403 (forbidden) status code.
"""
# https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#testing
django_client = Client(enforce_csrf_checks=True)
data = {
'server': 1,
'username': self.client.getProperty('omero.user'),
'password': self.client.getProperty('omero.pass')
}
login_url = reverse('weblogin')
_response(django_client, login_url, 'post', data=data, status_code=403)
logout_url = reverse('weblogout')
_response(django_client, logout_url, 'post', status_code=403)
def test_forgot_password(self):
request_url = reverse('waforgottenpassword')
data = {
'username': "omename",
'email': "email"
}
post(self.django_client, request_url, data)
def test_move_data(self):
group_id = self.new_group(experimenters=[self.user]).id.val
request_url = reverse('chgrp')
data = {
'image': self.image_with_channels().id.val,
'group_id': group_id
}
post(self.django_root_client, request_url, data)
def test_add_and_remove_comment(self):
request_url = reverse('annotate_comment')
data = {
'comment': 'foobar',
'image': self.image_with_channels().id.val
}
post(self.django_client, request_url, data)
# Remove comment, see remove tag,
# http://localhost/webclient/action/remove/[comment|tag|file]/ID/
def test_attach_file(self):
# Due to EOF both posts must be test separately
# Bad post
img = self.image_with_channels()
try:
temp = tempfile.NamedTemporaryFile(suffix='.csrf')
temp.write("Testing without csrf token")
temp.seek(0)
request_url = reverse('annotate_file')
data = {
'image': img.id.val,
'index': 0,
'annotation_file': temp
}
post(self.django_client, request_url, data)
finally:
temp.close()
# Good post
try:
temp = tempfile.NamedTemporaryFile(suffix='.csrf')
temp.write("Testing csrf token")
temp.seek(0)
request_url = reverse('annotate_file')
data = {
'image': img.id.val,
'index': 0,
'annotation_file': temp
}
post(self.django_client, request_url, data)
finally:
temp.close()
# link existing annotation is handled by the same request.
# Remove file, see remove tag,
# http://localhost/webclient/action/remove/[comment|tag|file]/ID/
def test_edit_channel_names(self):
"""
CSRF protection does not check `GET` requests so we need to be sure
that this request results in an HTTP 405 (method not allowed) status
code.
"""
img = self.image_with_channels()
data = {'channel0': 'foobar'}
request_url = reverse(
'edit_channel_names', args=[img.id.val]
)
get(self.django_client, request_url, data, status_code=405, csrf=True)
post(self.django_client, request_url, data)
def test_copy_past_rendering_settings(self):
"""
CSRF protection does not check `GET` requests so we need to be sure
that this request results in an HTTP 405 (method not allowed) status
code.
"""
img = self.create_test_image(session=self.sf)
# put image id into session
session = self.django_client.session
session['fromid'] = img.id.val
session.save()
request_url = reverse('webgateway.views.copy_image_rdef_json')
data = {
'toids': img.id.val
}
post(self.django_client, request_url, data)
get(self.django_client, request_url, data, status_code=405, csrf=True)
def test_reset_rendering_settings(self):
"""
CSRF protection does not check `GET` requests so we need to be sure
that this request results in an HTTP 405 (method not allowed) status
code.
"""
img = self.create_test_image(session=self.sf)
# Reset through webclient as it is calling directly
# webgateway.reset_image_rdef_json
request_url = reverse('reset_rdef_json')
data = {
'toids': img.id.val,
'to_type': 'image'
}
post(self.django_client, request_url, data)
get(self.django_client, request_url, data, status_code=405)
get(self.django_client, request_url, data, status_code=405, csrf=True)
def test_apply_owners_rendering_settings(self):
img = self.create_test_image(session=self.sf)
request_url = reverse('reset_owners_rdef_json')
data = {
'toids': img.id.val,
'to_type': 'image'
}
post(self.django_client, request_url, data)
def test_ome_tiff_script(self):
"""
CSRF protection does not check `GET` requests so we need to be sure
that this request results in an HTTP 405 (method not allowed) status
code.
"""
img = self.create_test_image(session=self.sf)
request_url = reverse('ome_tiff_script', args=[img.id.val])
post(self.django_client, request_url, {})
get(self.django_client, request_url, status_code=405)
def test_script(self):
img = self.create_test_image(session=self.sf)
script_path = "omero/export_scripts/Batch_Image_Export.py"
script = self.sf.getScriptService().getScriptID(script_path)
request_url = reverse('script_run', args=[script])
data = {
"Data_Type": "Image",
"IDs": img.id.val,
"Choose_T_Section": "Default-T (last-viewed)",
"Choose_Z_Section": "Default-Z (last-viewed)",
"Export_Individual_Channels": "on",
"Export_Merged_Image": "on",
"Folder_Name": "Batch_Image_Export",
"Format": "JPEG",
"Zoom": "100%"
}
post(self.django_client, request_url, data)
# ADMIN
def test_myaccount(self):
request_url = reverse('wamyaccount', args=["save"])
data = {
"omename": self.user.omeName.val,
"first_name": self.user.omeName.val,
"last_name": self.user.lastName.val,
"institution": "foo bar",
"default_group": self.group.id.val
}
post(self.django_client, request_url, data, status_code=302)
def test_avatar(self):
user_id = self.user.id.val
# Due to EOF both posts must be test separately
# Bad post
try:
temp = tempfile.NamedTemporaryFile(suffix='.png')
img = Image.new("RGB", (200, 200), "#FFFFFF")
draw = ImageDraw.Draw(img)
r, g, b = rint(0, 255), rint(0, 255), rint(0, 255)
for i in range(200):
draw.line((i, 0, i, 200), fill=(int(r), int(g), int(b)))
img.save(temp, "PNG")
temp.seek(0)
request_url = reverse('wamanageavatar', args=[user_id, "upload"])
data = {
'filename': 'avatar.png',
"photo": temp
}
csrf_response(self.django_client, request_url, 'post', data,
status_code=302, test_csrf_required=False)
finally:
temp.close()
# Good post
try:
temp = tempfile.NamedTemporaryFile(suffix='.png')
img = Image.new("RGB", (200, 200), "#FFFFFF")
draw = ImageDraw.Draw(img)
r, g, b = rint(0, 255), rint(0, 255), rint(0, 255)
for i in range(200):
draw.line((i, 0, i, 200), fill=(int(r), int(g), int(b)))
img.save(temp, "PNG")
temp.seek(0)
request_url = reverse('wamanageavatar', args=[user_id, "upload"])
data = {
'filename': 'avatar.png',
"photo": temp
}
csrf_response(self.django_client, request_url, 'post', data,
status_code=302, test_csrf_required=False)
finally:
temp.close()
# Crop avatar
request_url = reverse('wamanageavatar', args=[user_id, "crop"])
data = {
'x1': 50,
'x2': 150,
'y1': 50,
'y2': 150
}
csrf_response(self.django_client, request_url, 'post', data,
status_code=302, test_csrf_required=False)
def test_create_group(self):
uuid = self.uuid()
request_url = reverse('wamanagegroupid', args=["create"])
data = {
"name": uuid,
"description": uuid,
"permissions": 0
}
post(self.django_root_client, request_url, data, status_code=302)
def test_create_user(self):
uuid = self.uuid()
groupid = self.new_group().id.val
request_url = reverse('wamanageexperimenterid', args=["create"])
data = {
"omename": uuid,
"first_name": uuid,
"last_name": uuid,
"active": "on",
"default_group": groupid,
"other_groups": groupid,
"password": uuid,
"confirmation": uuid,
"role": "user",
}
post(self.django_root_client, request_url, data, status_code=302)
def test_edit_group(self):
group = self.new_group(perms="rw----")
request_url = reverse('wamanagegroupid', args=["save", group.id.val])
data = {
"name": group.name.val,
"description": "description",
"permissions": 0
}
post(self.django_root_client, request_url, data, status_code=302)
def test_edit_user(self):
user = self.new_user()
request_url = reverse('wamanageexperimenterid',
args=["save", user.id.val])
data = {
"omename": user.omeName.val,
"first_name": user.firstName.val,
"last_name": user.lastName.val,
"default_group": user.copyGroupExperimenterMap()[0].parent.id.val,
"other_groups": user.copyGroupExperimenterMap()[0].parent.id.val,
}
post(self.django_root_client, request_url, data, status_code=302)
def test_edit_group_by_owner(self):
self.add_groups(experimenter=self.user, groups=[self.group],
owner=True)
request_url = reverse('wamanagegroupownerid',
args=["save", self.group.id.val])
data = {
"members": self.user.id.val,
"owners": self.user.id.val,
"permissions": 0
}
post(self.django_client, request_url, data, status_code=302)
def test_change_password(self):
user = self.new_user()
request_url = reverse('wamanagechangepasswordid', args=[user.id.val])
data = {
"old_password": self.root.ic.getProperties().getProperty(
'omero.rootpass'),
"password": "new",
"confirmation": "new"
}
post(self.django_root_client, request_url, data)
def test_su(self):
"""
CSRF protection does not check `GET` requests so we need to be sure
that this request results in an HTTP 405 (method not allowed) status
code.
"""
user = self.new_user()
request_url = reverse('webgateway_su', args=[user.omeName.val])
get(self.django_root_client, request_url, {}, csrf=True)
post(self.django_root_client, request_url)