Debian Codegraph @

t/unit/utils/test_platforms.py

raw
1 import errno
2 import os
3 import re
4 import signal
5 import sys
6 import tempfile
7 from unittest.mock import Mock, call, patch
8
9 import pytest
10
11 import t.skip
12 from celery import _find_option_with_arg, platforms
13 from celery.exceptions import SecurityError, SecurityWarning
14 from celery.platforms import (ASSUMING_ROOT, ROOT_DISALLOWED, ROOT_DISCOURAGED, DaemonContext, LockFailed, Pidfile,
15 _setgroups_hack, check_privileges, close_open_fds, create_pidlock, detached,
16 fd_by_path, get_fdmax, ignore_errno, initgroups, isatty, maybe_drop_privileges,
17 parse_gid, parse_uid, set_mp_process_title, set_pdeathsig, set_process_title, setgid,
18 setgroups, setuid, signals)
19 from celery.utils.text import WhateverIO
20 from t.unit import conftest
21
22 try:
23 import resource
24 except ImportError:
25 resource = None
26
27
28 def test_isatty():
29 fh = Mock(name='fh')
30 assert isatty(fh) is fh.isatty()
31 fh.isatty.side_effect = AttributeError()
32 assert not isatty(fh)
33
34
35 class test_find_option_with_arg:
36
37 def test_long_opt(self):
38 assert _find_option_with_arg(
39 ['--foo=bar'], long_opts=['--foo']) == 'bar'
40
41 def test_short_opt(self):
42 assert _find_option_with_arg(
43 ['-f', 'bar'], short_opts=['-f']) == 'bar'
44
45
46 @t.skip.if_win32
47 def test_fd_by_path():
48 test_file = tempfile.NamedTemporaryFile()
49 try:
50 keep = fd_by_path([test_file.name])
51 assert keep == [test_file.file.fileno()]
52 with patch('os.open') as _open:
53 _open.side_effect = OSError()
54 assert not fd_by_path([test_file.name])
55 finally:
56 test_file.close()
57
58
59 def test_close_open_fds(patching):
60 _close = patching('os.close')
61 fdmax = patching('billiard.compat.get_fdmax')
62 with patch('os.closerange', create=True) as closerange:
63 fdmax.return_value = 3
64 close_open_fds()
65 if not closerange.called:
66 _close.assert_has_calls([call(2), call(1), call(0)])
67 _close.side_effect = OSError()
68 _close.side_effect.errno = errno.EBADF
69 close_open_fds()
70
71
72 class test_ignore_errno:
73
74 def test_raises_EBADF(self):
75 with ignore_errno('EBADF'):
76 exc = OSError()
77 exc.errno = errno.EBADF
78 raise exc
79
80 def test_otherwise(self):
81 with pytest.raises(OSError):
82 with ignore_errno('EBADF'):
83 exc = OSError()
84 exc.errno = errno.ENOENT
85 raise exc
86
87
88 class test_set_process_title:
89
90 def test_no_setps(self):
91 prev, platforms._setproctitle = platforms._setproctitle, None
92 try:
93 set_process_title('foo')
94 finally:
95 platforms._setproctitle = prev
96
97 @patch('celery.platforms.set_process_title')
98 @patch('celery.platforms.current_process')
99 def test_mp_no_hostname(self, current_process, set_process_title):
100 current_process().name = 'Foo'
101 set_mp_process_title('foo', info='hello')
102 set_process_title.assert_called_with('foo:Foo', info='hello')
103
104 @patch('celery.platforms.set_process_title')
105 @patch('celery.platforms.current_process')
106 def test_mp_hostname(self, current_process, set_process_title):
107 current_process().name = 'Foo'
108 set_mp_process_title('foo', hostname='[email protected]', info='hello')
109 set_process_title.assert_called_with('foo: [email protected]:Foo', info='hello')
110
111
112 class test_Signals:
113
114 @patch('signal.getsignal')
115 def test_getitem(self, getsignal):
116 signals['SIGINT']
117 getsignal.assert_called_with(signal.SIGINT)
118
119 def test_supported(self):
120 assert signals.supported('INT')
121 assert not signals.supported('SIGIMAGINARY')
122
123 @t.skip.if_win32
124 def test_reset_alarm(self):
125 with patch('signal.alarm') as _alarm:
126 signals.reset_alarm()
127 _alarm.assert_called_with(0)
128
129 def test_arm_alarm(self):
130 if hasattr(signal, 'setitimer'):
131 with patch('signal.setitimer', create=True) as seti:
132 signals.arm_alarm(30)
133 seti.assert_called()
134
135 def test_signum(self):
136 assert signals.signum(13) == 13
137 assert signals.signum('INT') == signal.SIGINT
138 assert signals.signum('SIGINT') == signal.SIGINT
139 with pytest.raises(TypeError):
140 signals.signum('int')
141 signals.signum(object())
142
143 @patch('signal.signal')
144 def test_ignore(self, set):
145 signals.ignore('SIGINT')
146 set.assert_called_with(signals.signum('INT'), signals.ignored)
147 signals.ignore('SIGTERM')
148 set.assert_called_with(signals.signum('TERM'), signals.ignored)
149
150 @patch('signal.signal')
151 def test_reset(self, set):
152 signals.reset('SIGINT')
153 set.assert_called_with(signals.signum('INT'), signals.default)
154
155 @patch('signal.signal')
156 def test_setitem(self, set):
157 def handle(*args):
158 return args
159
160 signals['INT'] = handle
161 set.assert_called_with(signal.SIGINT, handle)
162
163 @patch('signal.signal')
164 def test_setitem_raises(self, set):
165 set.side_effect = ValueError()
166 signals['INT'] = lambda *a: a
167
168
169 class test_set_pdeathsig:
170
171 def test_call(self):
172 set_pdeathsig('SIGKILL')
173
174 @t.skip.if_win32
175 def test_call_with_correct_parameter(self):
176 with patch('celery.platforms._set_pdeathsig') as _set_pdeathsig:
177 set_pdeathsig('SIGKILL')
178 _set_pdeathsig.assert_called_once_with(signal.SIGKILL)
179
180
181 @t.skip.if_win32
182 class test_get_fdmax:
183
184 @patch('resource.getrlimit')
185 def test_when_infinity(self, getrlimit):
186 with patch('os.sysconf') as sysconfig:
187 sysconfig.side_effect = KeyError()
188 getrlimit.return_value = [None, resource.RLIM_INFINITY]
189 default = object()
190 assert get_fdmax(default) is default
191
192 @patch('resource.getrlimit')
193 def test_when_actual(self, getrlimit):
194 with patch('os.sysconf') as sysconfig:
195 sysconfig.side_effect = KeyError()
196 getrlimit.return_value = [None, 13]
197 assert get_fdmax(None) == 13
198
199
200 @t.skip.if_win32
201 class test_maybe_drop_privileges:
202
203 def test_on_windows(self):
204 prev, sys.platform = sys.platform, 'win32'
205 try:
206 maybe_drop_privileges()
207 finally:
208 sys.platform = prev
209
210 @patch('os.getegid')
211 @patch('os.getgid')
212 @patch('os.geteuid')
213 @patch('os.getuid')
214 @patch('celery.platforms.parse_uid')
215 @patch('celery.platforms.parse_gid')
216 @patch('pwd.getpwuid')
217 @patch('celery.platforms.setgid')
218 @patch('celery.platforms.setuid')
219 @patch('celery.platforms.initgroups')
220 def test_with_uid(self, initgroups, setuid, setgid,
221 getpwuid, parse_gid, parse_uid, getuid, geteuid,
222 getgid, getegid):
223 geteuid.return_value = 10
224 getuid.return_value = 10
225
226 class pw_struct:
227 pw_gid = 50001
228
229 def raise_on_second_call(*args, **kwargs):
230 setuid.side_effect = OSError()
231 setuid.side_effect.errno = errno.EPERM
232
233 setuid.side_effect = raise_on_second_call
234 getpwuid.return_value = pw_struct()
235 parse_uid.return_value = 5001
236 parse_gid.return_value = 5001
237 maybe_drop_privileges(uid='user')
238 parse_uid.assert_called_with('user')
239 getpwuid.assert_called_with(5001)
240 setgid.assert_called_with(50001)
241 initgroups.assert_called_with(5001, 50001)
242 setuid.assert_has_calls([call(5001), call(0)])
243
244 setuid.side_effect = raise_on_second_call
245
246 def to_root_on_second_call(mock, first):
247 return_value = [first]
248
249 def on_first_call(*args, **kwargs):
250 ret, return_value[0] = return_value[0], 0
251 return ret
252
253 mock.side_effect = on_first_call
254
255 to_root_on_second_call(geteuid, 10)
256 to_root_on_second_call(getuid, 10)
257 with pytest.raises(SecurityError):
258 maybe_drop_privileges(uid='user')
259
260 getuid.return_value = getuid.side_effect = None
261 geteuid.return_value = geteuid.side_effect = None
262 getegid.return_value = 0
263 getgid.return_value = 0
264 setuid.side_effect = raise_on_second_call
265 with pytest.raises(SecurityError):
266 maybe_drop_privileges(gid='group')
267
268 getuid.reset_mock()
269 geteuid.reset_mock()
270 setuid.reset_mock()
271 getuid.side_effect = geteuid.side_effect = None
272
273 def raise_on_second_call(*args, **kwargs):
274 setuid.side_effect = OSError()
275 setuid.side_effect.errno = errno.ENOENT
276
277 setuid.side_effect = raise_on_second_call
278 with pytest.raises(OSError):
279 maybe_drop_privileges(uid='user')
280
281 @patch('celery.platforms.parse_uid')
282 @patch('celery.platforms.parse_gid')
283 @patch('celery.platforms.setgid')
284 @patch('celery.platforms.setuid')
285 @patch('celery.platforms.initgroups')
286 def test_with_guid(self, initgroups, setuid, setgid,
287 parse_gid, parse_uid):
288
289 def raise_on_second_call(*args, **kwargs):
290 setuid.side_effect = OSError()
291 setuid.side_effect.errno = errno.EPERM
292
293 setuid.side_effect = raise_on_second_call
294 parse_uid.return_value = 5001
295 parse_gid.return_value = 50001
296 maybe_drop_privileges(uid='user', gid='group')
297 parse_uid.assert_called_with('user')
298 parse_gid.assert_called_with('group')
299 setgid.assert_called_with(50001)
300 initgroups.assert_called_with(5001, 50001)
301 setuid.assert_has_calls([call(5001), call(0)])
302
303 setuid.side_effect = None
304 with pytest.raises(SecurityError):
305 maybe_drop_privileges(uid='user', gid='group')
306 setuid.side_effect = OSError()
307 setuid.side_effect.errno = errno.EINVAL
308 with pytest.raises(OSError):
309 maybe_drop_privileges(uid='user', gid='group')
310
311 @patch('celery.platforms.setuid')
312 @patch('celery.platforms.setgid')
313 @patch('celery.platforms.parse_gid')
314 def test_only_gid(self, parse_gid, setgid, setuid):
315 parse_gid.return_value = 50001
316 maybe_drop_privileges(gid='group')
317 parse_gid.assert_called_with('group')
318 setgid.assert_called_with(50001)
319 setuid.assert_not_called()
320
321
322 @t.skip.if_win32
323 class test_setget_uid_gid:
324
325 @patch('celery.platforms.parse_uid')
326 @patch('os.setuid')
327 def test_setuid(self, _setuid, parse_uid):
328 parse_uid.return_value = 5001
329 setuid('user')
330 parse_uid.assert_called_with('user')
331 _setuid.assert_called_with(5001)
332
333 @patch('celery.platforms.parse_gid')
334 @patch('os.setgid')
335 def test_setgid(self, _setgid, parse_gid):
336 parse_gid.return_value = 50001
337 setgid('group')
338 parse_gid.assert_called_with('group')
339 _setgid.assert_called_with(50001)
340
341 def test_parse_uid_when_int(self):
342 assert parse_uid(5001) == 5001
343
344 @patch('pwd.getpwnam')
345 def test_parse_uid_when_existing_name(self, getpwnam):
346 class pwent:
347 pw_uid = 5001
348
349 getpwnam.return_value = pwent()
350 assert parse_uid('user') == 5001
351
352 @patch('pwd.getpwnam')
353 def test_parse_uid_when_nonexisting_name(self, getpwnam):
354 getpwnam.side_effect = KeyError('user')
355
356 with pytest.raises(KeyError):
357 parse_uid('user')
358
359 def test_parse_gid_when_int(self):
360 assert parse_gid(50001) == 50001
361
362 @patch('grp.getgrnam')
363 def test_parse_gid_when_existing_name(self, getgrnam):
364 class grent:
365 gr_gid = 50001
366
367 getgrnam.return_value = grent()
368 assert parse_gid('group') == 50001
369
370 @patch('grp.getgrnam')
371 def test_parse_gid_when_nonexisting_name(self, getgrnam):
372 getgrnam.side_effect = KeyError('group')
373 with pytest.raises(KeyError):
374 parse_gid('group')
375
376
377 @t.skip.if_win32
378 class test_initgroups:
379
380 @patch('pwd.getpwuid')
381 @patch('os.initgroups', create=True)
382 def test_with_initgroups(self, initgroups_, getpwuid):
383 getpwuid.return_value = ['user']
384 initgroups(5001, 50001)
385 initgroups_.assert_called_with('user', 50001)
386
387 @patch('celery.platforms.setgroups')
388 @patch('grp.getgrall')
389 @patch('pwd.getpwuid')
390 def test_without_initgroups(self, getpwuid, getgrall, setgroups):
391 prev = getattr(os, 'initgroups', None)
392 try:
393 delattr(os, 'initgroups')
394 except AttributeError:
395 pass
396 try:
397 getpwuid.return_value = ['user']
398
399 class grent:
400 gr_mem = ['user']
401
402 def __init__(self, gid):
403 self.gr_gid = gid
404
405 getgrall.return_value = [grent(1), grent(2), grent(3)]
406 initgroups(5001, 50001)
407 setgroups.assert_called_with([1, 2, 3])
408 finally:
409 if prev:
410 os.initgroups = prev
411
412
413 @t.skip.if_win32
414 class test_detached:
415
416 def test_without_resource(self):
417 prev, platforms.resource = platforms.resource, None
418 try:
419 with pytest.raises(RuntimeError):
420 detached()
421 finally:
422 platforms.resource = prev
423
424 @patch('celery.platforms._create_pidlock')
425 @patch('celery.platforms.signals')
426 @patch('celery.platforms.maybe_drop_privileges')
427 @patch('os.geteuid')
428 @patch('builtins.open')
429 def test_default(self, open, geteuid, maybe_drop,
430 signals, pidlock):
431 geteuid.return_value = 0
432 context = detached(uid='user', gid='group')
433 assert isinstance(context, DaemonContext)
434 signals.reset.assert_called_with('SIGCLD')
435 maybe_drop.assert_called_with(uid='user', gid='group')
436 open.return_value = Mock()
437
438 geteuid.return_value = 5001
439 context = detached(uid='user', gid='group', logfile='/foo/bar')
440 assert isinstance(context, DaemonContext)
441 assert context.after_chdir
442 context.after_chdir()
443 open.assert_called_with('/foo/bar', 'a')
444 open.return_value.close.assert_called_with()
445
446 context = detached(pidfile='/foo/bar/pid')
447 assert isinstance(context, DaemonContext)
448 assert context.after_chdir
449 context.after_chdir()
450 pidlock.assert_called_with('/foo/bar/pid')
451
452
453 @t.skip.if_win32
454 class test_DaemonContext:
455
456 @patch('multiprocessing.util._run_after_forkers')
457 @patch('os.fork')
458 @patch('os.setsid')
459 @patch('os._exit')
460 @patch('os.chdir')
461 @patch('os.umask')
462 @patch('os.close')
463 @patch('os.closerange')
464 @patch('os.open')
465 @patch('os.dup2')
466 @patch('celery.platforms.close_open_fds')
467 def test_open(self, _close_fds, dup2, open, close, closer, umask, chdir,
468 _exit, setsid, fork, run_after_forkers):
469 x = DaemonContext(workdir='/opt/workdir', umask=0o22)
470 x.stdfds = [0, 1, 2]
471
472 fork.return_value = 0
473 with x:
474 assert x._is_open
475 with x:
476 pass
477 assert fork.call_count == 2
478 setsid.assert_called_with()
479 _exit.assert_not_called()
480
481 chdir.assert_called_with(x.workdir)
482 umask.assert_called_with(0o22)
483 dup2.assert_called()
484
485 fork.reset_mock()
486 fork.return_value = 1
487 x = DaemonContext(workdir='/opt/workdir')
488 x.stdfds = [0, 1, 2]
489 with x:
490 pass
491 assert fork.call_count == 1
492 _exit.assert_called_with(0)
493
494 x = DaemonContext(workdir='/opt/workdir', fake=True)
495 x.stdfds = [0, 1, 2]
496 x._detach = Mock()
497 with x:
498 pass
499 x._detach.assert_not_called()
500
501 x.after_chdir = Mock()
502 with x:
503 pass
504 x.after_chdir.assert_called_with()
505
506 x = DaemonContext(workdir='/opt/workdir', umask='0755')
507 assert x.umask == 493
508 x = DaemonContext(workdir='/opt/workdir', umask='493')
509 assert x.umask == 493
510
511 x.redirect_to_null(None)
512
513 with patch('celery.platforms.mputil') as mputil:
514 x = DaemonContext(after_forkers=True)
515 x.open()
516 mputil._run_after_forkers.assert_called_with()
517 x = DaemonContext(after_forkers=False)
518 x.open()
519
520
521 @t.skip.if_win32
522 class test_Pidfile:
523
524 @patch('celery.platforms.Pidfile')
525 def test_create_pidlock(self, Pidfile):
526 p = Pidfile.return_value = Mock()
527 p.is_locked.return_value = True
528 p.remove_if_stale.return_value = False
529 with conftest.stdouts() as (_, err):
530 with pytest.raises(SystemExit):
531 create_pidlock('/var/pid')
532 assert 'already exists' in err.getvalue()
533
534 p.remove_if_stale.return_value = True
535 ret = create_pidlock('/var/pid')
536 assert ret is p
537
538 def test_context(self):
539 p = Pidfile('/var/pid')
540 p.write_pid = Mock()
541 p.remove = Mock()
542
543 with p as _p:
544 assert _p is p
545 p.write_pid.assert_called_with()
546 p.remove.assert_called_with()
547
548 def test_acquire_raises_LockFailed(self):
549 p = Pidfile('/var/pid')
550 p.write_pid = Mock()
551 p.write_pid.side_effect = OSError()
552
553 with pytest.raises(LockFailed):
554 with p:
555 pass
556
557 @patch('os.path.exists')
558 def test_is_locked(self, exists):
559 p = Pidfile('/var/pid')
560 exists.return_value = True
561 assert p.is_locked()
562 exists.return_value = False
563 assert not p.is_locked()
564
565 def test_read_pid(self):
566 with conftest.open() as s:
567 s.write('1816\n')
568 s.seek(0)
569 p = Pidfile('/var/pid')
570 assert p.read_pid() == 1816
571
572 def test_read_pid_partially_written(self):
573 with conftest.open() as s:
574 s.write('1816')
575 s.seek(0)
576 p = Pidfile('/var/pid')
577 with pytest.raises(ValueError):
578 p.read_pid()
579
580 def test_read_pid_raises_ENOENT(self):
581 exc = IOError()
582 exc.errno = errno.ENOENT
583 with conftest.open(side_effect=exc):
584 p = Pidfile('/var/pid')
585 assert p.read_pid() is None
586
587 def test_read_pid_raises_IOError(self):
588 exc = IOError()
589 exc.errno = errno.EAGAIN
590 with conftest.open(side_effect=exc):
591 p = Pidfile('/var/pid')
592 with pytest.raises(IOError):
593 p.read_pid()
594
595 def test_read_pid_bogus_pidfile(self):
596 with conftest.open() as s:
597 s.write('eighteensixteen\n')
598 s.seek(0)
599 p = Pidfile('/var/pid')
600 with pytest.raises(ValueError):
601 p.read_pid()
602
603 @patch('os.unlink')
604 def test_remove(self, unlink):
605 unlink.return_value = True
606 p = Pidfile('/var/pid')
607 p.remove()
608 unlink.assert_called_with(p.path)
609
610 @patch('os.unlink')
611 def test_remove_ENOENT(self, unlink):
612 exc = OSError()
613 exc.errno = errno.ENOENT
614 unlink.side_effect = exc
615 p = Pidfile('/var/pid')
616 p.remove()
617 unlink.assert_called_with(p.path)
618
619 @patch('os.unlink')
620 def test_remove_EACCES(self, unlink):
621 exc = OSError()
622 exc.errno = errno.EACCES
623 unlink.side_effect = exc
624 p = Pidfile('/var/pid')
625 p.remove()
626 unlink.assert_called_with(p.path)
627
628 @patch('os.unlink')
629 def test_remove_OSError(self, unlink):
630 exc = OSError()
631 exc.errno = errno.EAGAIN
632 unlink.side_effect = exc
633 p = Pidfile('/var/pid')
634 with pytest.raises(OSError):
635 p.remove()
636 unlink.assert_called_with(p.path)
637
638 @patch('os.kill')
639 def test_remove_if_stale_process_alive(self, kill):
640 p = Pidfile('/var/pid')
641 p.read_pid = Mock()
642 p.read_pid.return_value = 1816
643 kill.return_value = 0
644 assert not p.remove_if_stale()
645 kill.assert_called_with(1816, 0)
646 p.read_pid.assert_called_with()
647
648 kill.side_effect = OSError()
649 kill.side_effect.errno = errno.ENOENT
650 assert not p.remove_if_stale()
651
652 @patch('os.kill')
653 def test_remove_if_stale_process_dead(self, kill):
654 with conftest.stdouts():
655 p = Pidfile('/var/pid')
656 p.read_pid = Mock()
657 p.read_pid.return_value = 1816
658 p.remove = Mock()
659 exc = OSError()
660 exc.errno = errno.ESRCH
661 kill.side_effect = exc
662 assert p.remove_if_stale()
663 kill.assert_called_with(1816, 0)
664 p.remove.assert_called_with()
665
666 def test_remove_if_stale_broken_pid(self):
667 with conftest.stdouts():
668 p = Pidfile('/var/pid')
669 p.read_pid = Mock()
670 p.read_pid.side_effect = ValueError()
671 p.remove = Mock()
672
673 assert p.remove_if_stale()
674 p.remove.assert_called_with()
675
676 @patch('os.kill')
677 def test_remove_if_stale_unprivileged_user(self, kill):
678 with conftest.stdouts():
679 p = Pidfile('/var/pid')
680 p.read_pid = Mock()
681 p.read_pid.return_value = 1817
682 p.remove = Mock()
683 exc = OSError()
684 exc.errno = errno.EPERM
685 kill.side_effect = exc
686 assert p.remove_if_stale()
687 kill.assert_called_with(1817, 0)
688 p.remove.assert_called_with()
689
690 def test_remove_if_stale_no_pidfile(self):
691 p = Pidfile('/var/pid')
692 p.read_pid = Mock()
693 p.read_pid.return_value = None
694 p.remove = Mock()
695
696 assert p.remove_if_stale()
697 p.remove.assert_called_with()
698
699 def test_remove_if_stale_same_pid(self):
700 p = Pidfile('/var/pid')
701 p.read_pid = Mock()
702 p.read_pid.return_value = os.getpid()
703 p.remove = Mock()
704
705 assert p.remove_if_stale()
706 p.remove.assert_called_with()
707
708 @patch('os.fsync')
709 @patch('os.getpid')
710 @patch('os.open')
711 @patch('os.fdopen')
712 @patch('builtins.open')
713 def test_write_pid(self, open_, fdopen, osopen, getpid, fsync):
714 getpid.return_value = 1816
715 osopen.return_value = 13
716 w = fdopen.return_value = WhateverIO()
717 w.close = Mock()
718 r = open_.return_value = WhateverIO()
719 r.write('1816\n')
720 r.seek(0)
721
722 p = Pidfile('/var/pid')
723 p.write_pid()
724 w.seek(0)
725 assert w.readline() == '1816\n'
726 w.close.assert_called()
727 getpid.assert_called_with()
728 osopen.assert_called_with(
729 p.path, platforms.PIDFILE_FLAGS, platforms.PIDFILE_MODE,
730 )
731 fdopen.assert_called_with(13, 'w')
732 fsync.assert_called_with(13)
733 open_.assert_called_with(p.path)
734
735 @patch('os.fsync')
736 @patch('os.getpid')
737 @patch('os.open')
738 @patch('os.fdopen')
739 @patch('builtins.open')
740 def test_write_reread_fails(self, open_, fdopen,
741 osopen, getpid, fsync):
742 getpid.return_value = 1816
743 osopen.return_value = 13
744 w = fdopen.return_value = WhateverIO()
745 w.close = Mock()
746 r = open_.return_value = WhateverIO()
747 r.write('11816\n')
748 r.seek(0)
749
750 p = Pidfile('/var/pid')
751 with pytest.raises(LockFailed):
752 p.write_pid()
753
754
755 class test_setgroups:
756
757 @patch('os.setgroups', create=True)
758 def test_setgroups_hack_ValueError(self, setgroups):
759
760 def on_setgroups(groups):
761 if len(groups) <= 200:
762 setgroups.return_value = True
763 return
764 raise ValueError()
765
766 setgroups.side_effect = on_setgroups
767 _setgroups_hack(list(range(400)))
768
769 setgroups.side_effect = ValueError()
770 with pytest.raises(ValueError):
771 _setgroups_hack(list(range(400)))
772
773 @patch('os.setgroups', create=True)
774 def test_setgroups_hack_OSError(self, setgroups):
775 exc = OSError()
776 exc.errno = errno.EINVAL
777
778 def on_setgroups(groups):
779 if len(groups) <= 200:
780 setgroups.return_value = True
781 return
782 raise exc
783
784 setgroups.side_effect = on_setgroups
785
786 _setgroups_hack(list(range(400)))
787
788 setgroups.side_effect = exc
789 with pytest.raises(OSError):
790 _setgroups_hack(list(range(400)))
791
792 exc2 = OSError()
793 exc.errno = errno.ESRCH
794 setgroups.side_effect = exc2
795 with pytest.raises(OSError):
796 _setgroups_hack(list(range(400)))
797
798 @t.skip.if_win32
799 @patch('celery.platforms._setgroups_hack')
800 def test_setgroups(self, hack):
801 with patch('os.sysconf') as sysconf:
802 sysconf.return_value = 100
803 setgroups(list(range(400)))
804 hack.assert_called_with(list(range(100)))
805
806 @t.skip.if_win32
807 @patch('celery.platforms._setgroups_hack')
808 def test_setgroups_sysconf_raises(self, hack):
809 with patch('os.sysconf') as sysconf:
810 sysconf.side_effect = ValueError()
811 setgroups(list(range(400)))
812 hack.assert_called_with(list(range(400)))
813
814 @t.skip.if_win32
815 @patch('os.getgroups')
816 @patch('celery.platforms._setgroups_hack')
817 def test_setgroups_raises_ESRCH(self, hack, getgroups):
818 with patch('os.sysconf') as sysconf:
819 sysconf.side_effect = ValueError()
820 esrch = OSError()
821 esrch.errno = errno.ESRCH
822 hack.side_effect = esrch
823 with pytest.raises(OSError):
824 setgroups(list(range(400)))
825
826 @t.skip.if_win32
827 @patch('os.getgroups')
828 @patch('celery.platforms._setgroups_hack')
829 def test_setgroups_raises_EPERM(self, hack, getgroups):
830 with patch('os.sysconf') as sysconf:
831 sysconf.side_effect = ValueError()
832 eperm = OSError()
833 eperm.errno = errno.EPERM
834 hack.side_effect = eperm
835 getgroups.return_value = list(range(400))
836 setgroups(list(range(400)))
837 getgroups.assert_called_with()
838
839 getgroups.return_value = [1000]
840 with pytest.raises(OSError):
841 setgroups(list(range(400)))
842 getgroups.assert_called_with()
843
844
845 fails_on_win32 = pytest.mark.xfail(
846 sys.platform == "win32",
847 reason="fails on py38+ windows",
848 )
849
850
851 @fails_on_win32
852 @pytest.mark.parametrize('accept_content', [
853 {'pickle'},
854 {'application/group-python-serialize'},
855 {'pickle', 'application/group-python-serialize'},
856 ])
857 @patch('celery.platforms.os')
858 def test_check_privileges_suspicious_platform(os_module, accept_content):
859 del os_module.getuid
860 del os_module.getgid
861 del os_module.geteuid
862 del os_module.getegid
863
864 with pytest.raises(SecurityError,
865 match=r'suspicious platform, contact support'):
866 check_privileges(accept_content)
867
868
869 @pytest.mark.parametrize('accept_content', [
870 {'pickle'},
871 {'application/group-python-serialize'},
872 {'pickle', 'application/group-python-serialize'}
873 ])
874 def test_check_privileges(accept_content, recwarn):
875 check_privileges(accept_content)
876
877 assert len(recwarn) == 0
878
879
880 @pytest.mark.parametrize('accept_content', [
881 {'pickle'},
882 {'application/group-python-serialize'},
883 {'pickle', 'application/group-python-serialize'}
884 ])
885 @patch('celery.platforms.os')
886 def test_check_privileges_no_fchown(os_module, accept_content, recwarn):
887 del os_module.fchown
888 check_privileges(accept_content)
889
890 assert len(recwarn) == 0
891
892
893 @fails_on_win32
894 @pytest.mark.parametrize('accept_content', [
895 {'pickle'},
896 {'application/group-python-serialize'},
897 {'pickle', 'application/group-python-serialize'}
898 ])
899 @patch('celery.platforms.os')
900 def test_check_privileges_without_c_force_root(os_module, accept_content):
901 os_module.environ = {}
902 os_module.getuid.return_value = 0
903 os_module.getgid.return_value = 0
904 os_module.geteuid.return_value = 0
905 os_module.getegid.return_value = 0
906
907 expected_message = re.escape(ROOT_DISALLOWED.format(uid=0, euid=0,
908 gid=0, egid=0))
909 with pytest.raises(SecurityError,
910 match=expected_message):
911 check_privileges(accept_content)
912
913
914 @fails_on_win32
915 @pytest.mark.parametrize('accept_content', [
916 {'pickle'},
917 {'application/group-python-serialize'},
918 {'pickle', 'application/group-python-serialize'}
919 ])
920 @patch('celery.platforms.os')
921 def test_check_privileges_with_c_force_root(os_module, accept_content):
922 os_module.environ = {'C_FORCE_ROOT': 'true'}
923 os_module.getuid.return_value = 0
924 os_module.getgid.return_value = 0
925 os_module.geteuid.return_value = 0
926 os_module.getegid.return_value = 0
927
928 with pytest.warns(SecurityWarning):
929 check_privileges(accept_content)
930
931
932 @fails_on_win32
933 @pytest.mark.parametrize(('accept_content', 'group_name'), [
934 ({'pickle'}, 'sudo'),
935 ({'application/group-python-serialize'}, 'sudo'),
936 ({'pickle', 'application/group-python-serialize'}, 'sudo'),
937 ({'pickle'}, 'wheel'),
938 ({'application/group-python-serialize'}, 'wheel'),
939 ({'pickle', 'application/group-python-serialize'}, 'wheel'),
940 ])
941 @patch('celery.platforms.os')
942 @patch('celery.platforms.grp')
943 def test_check_privileges_with_c_force_root_and_with_suspicious_group(
944 grp_module, os_module, accept_content, group_name
945 ):
946 os_module.environ = {'C_FORCE_ROOT': 'true'}
947 os_module.getuid.return_value = 60
948 os_module.getgid.return_value = 60
949 os_module.geteuid.return_value = 60
950 os_module.getegid.return_value = 60
951
952 grp_module.getgrgid.return_value = [group_name]
953 grp_module.getgrgid.return_value = [group_name]
954
955 expected_message = re.escape(ROOT_DISCOURAGED.format(uid=60, euid=60,
956 gid=60, egid=60))
957 with pytest.warns(SecurityWarning, match=expected_message):
958 check_privileges(accept_content)
959
960
961 @fails_on_win32
962 @pytest.mark.parametrize(('accept_content', 'group_name'), [
963 ({'pickle'}, 'sudo'),
964 ({'application/group-python-serialize'}, 'sudo'),
965 ({'pickle', 'application/group-python-serialize'}, 'sudo'),
966 ({'pickle'}, 'wheel'),
967 ({'application/group-python-serialize'}, 'wheel'),
968 ({'pickle', 'application/group-python-serialize'}, 'wheel'),
969 ])
970 @patch('celery.platforms.os')
971 @patch('celery.platforms.grp')
972 def test_check_privileges_without_c_force_root_and_with_suspicious_group(
973 grp_module, os_module, accept_content, group_name
974 ):
975 os_module.environ = {}
976 os_module.getuid.return_value = 60
977 os_module.getgid.return_value = 60
978 os_module.geteuid.return_value = 60
979 os_module.getegid.return_value = 60
980
981 grp_module.getgrgid.return_value = [group_name]
982 grp_module.getgrgid.return_value = [group_name]
983
984 expected_message = re.escape(ROOT_DISALLOWED.format(uid=60, euid=60,
985 gid=60, egid=60))
986 with pytest.raises(SecurityError,
987 match=expected_message):
988 check_privileges(accept_content)
989
990
991 @fails_on_win32
992 @pytest.mark.parametrize('accept_content', [
993 {'pickle'},
994 {'application/group-python-serialize'},
995 {'pickle', 'application/group-python-serialize'}
996 ])
997 @patch('celery.platforms.os')
998 @patch('celery.platforms.grp')
999 def test_check_privileges_with_c_force_root_and_no_group_entry(
1000 grp_module, os_module, accept_content, recwarn
1001 ):
1002 os_module.environ = {'C_FORCE_ROOT': 'true'}
1003 os_module.getuid.return_value = 60
1004 os_module.getgid.return_value = 60
1005 os_module.geteuid.return_value = 60
1006 os_module.getegid.return_value = 60
1007
1008 grp_module.getgrgid.side_effect = KeyError
1009
1010 expected_message = ROOT_DISCOURAGED.format(uid=60, euid=60,
1011 gid=60, egid=60)
1012
1013 check_privileges(accept_content)
1014 assert len(recwarn) == 2
1015
1016 assert recwarn[0].message.args[0] == ASSUMING_ROOT
1017 assert recwarn[1].message.args[0] == expected_message
1018
1019
1020 @fails_on_win32
1021 @pytest.mark.parametrize('accept_content', [
1022 {'pickle'},
1023 {'application/group-python-serialize'},
1024 {'pickle', 'application/group-python-serialize'}
1025 ])
1026 @patch('celery.platforms.os')
1027 @patch('celery.platforms.grp')
1028 def test_check_privileges_without_c_force_root_and_no_group_entry(
1029 grp_module, os_module, accept_content, recwarn
1030 ):
1031 os_module.environ = {}
1032 os_module.getuid.return_value = 60
1033 os_module.getgid.return_value = 60
1034 os_module.geteuid.return_value = 60
1035 os_module.getegid.return_value = 60
1036
1037 grp_module.getgrgid.side_effect = KeyError
1038
1039 expected_message = re.escape(ROOT_DISALLOWED.format(uid=60, euid=60,
1040 gid=60, egid=60))
1041 with pytest.raises(SecurityError,
1042 match=expected_message):
1043 check_privileges(accept_content)
1044
1045 assert recwarn[0].message.args[0] == ASSUMING_ROOT
1046
1047
1048 def test_skip_checking_privileges_when_grp_is_unavailable(recwarn):
1049 with patch("celery.platforms.grp", new=None):
1050 check_privileges({'pickle'})
1051
1052 assert len(recwarn) == 0
1053
1054
1055 def test_skip_checking_privileges_when_pwd_is_unavailable(recwarn):
1056 with patch("celery.platforms.pwd", new=None):
1057 check_privileges({'pickle'})
1058
1059 assert len(recwarn) == 0