]> git.k1024.org Git - pylibacl.git/blob - tests/test_acls.py
Try to make the acl_copy_ext_failure test better behaved
[pylibacl.git] / tests / test_acls.py
1 #
2 #
3
4 """Unittests for the posix1e module"""
5
6 #  Copyright (C) 2002-2009, 2012, 2014, 2015 Iustin Pop <iustin@k1024.org>
7 #
8 #  This library is free software; you can redistribute it and/or
9 #  modify it under the terms of the GNU Lesser General Public
10 #  License as published by the Free Software Foundation; either
11 #  version 2.1 of the License, or (at your option) any later version.
12 #
13 #  This library is distributed in the hope that it will be useful,
14 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 #  Lesser General Public License for more details.
17 #
18 #  You should have received a copy of the GNU Lesser General Public
19 #  License along with this library; if not, write to the Free Software
20 #  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 #  02110-1301  USA
22
23
24 import unittest
25 import os
26 import tempfile
27 import sys
28 import platform
29 import re
30 import errno
31 import operator
32 import pytest  # type: ignore
33 import contextlib
34 import pathlib
35 import io
36
37 import posix1e
38 from posix1e import *
39
40 TEST_DIR = os.environ.get("TEST_DIR", ".")
41
42 BASIC_ACL_TEXT = "u::rw,g::r,o::-"
43 TEXT_0755 = "u::rwx,g::rx,o::rx"
44
45 # Permset permission information
46 PERMSETS = [
47     (ACL_READ, "read", Permset.read),
48     (ACL_WRITE, "write", Permset.write),
49     (ACL_EXECUTE, "execute", Permset.execute),
50 ]
51
52 PERMSETS_IDS = [p[1] for p in PERMSETS]
53
54 ALL_TAGS = [
55   (posix1e.ACL_USER, "user"),
56   (posix1e.ACL_GROUP, "group"),
57   (posix1e.ACL_USER_OBJ, "user object"),
58   (posix1e.ACL_GROUP_OBJ, "group object"),
59   (posix1e.ACL_MASK, "mask"),
60   (posix1e.ACL_OTHER, "other"),
61 ]
62
63 ALL_TAG_VALUES = [i[0] for i in ALL_TAGS]
64 ALL_TAG_DESCS = [i[1] for i in ALL_TAGS]
65
66 # Fixtures and helpers
67
68 def ignore_ioerror(errnum, fn, *args, **kwargs):
69     """Call a function while ignoring some IOErrors.
70
71     This is needed as some OSes (e.g. FreeBSD) return failure (EINVAL)
72     when doing certain operations on an invalid ACL.
73
74     """
75     try:
76         fn(*args, **kwargs)
77     except IOError as err:
78         if err.errno == errnum:
79             return
80         raise
81
82 def assert_acl_eq(a, b):
83     if HAS_ACL_CHECK:
84         assert a == b
85     assert str(a) == str(b)
86
87 @pytest.fixture
88 def testdir():
89     """per-test temp dir based in TEST_DIR"""
90     with tempfile.TemporaryDirectory(dir=TEST_DIR) as dname:
91         yield dname
92
93 def get_file(path):
94     fh, fname = tempfile.mkstemp(".test", "xattr-", path)
95     return fh, fname
96
97 @contextlib.contextmanager
98 def get_file_name(path):
99     fh, fname = get_file(path)
100     os.close(fh)
101     yield fname
102
103 @contextlib.contextmanager
104 def get_file_fd(path):
105     fd = get_file(path)[0]
106     yield fd
107     os.close(fd)
108
109 @contextlib.contextmanager
110 def get_file_object(path):
111     fd = get_file(path)[0]
112     with os.fdopen(fd) as f:
113         yield f
114
115 @contextlib.contextmanager
116 def get_dir(path):
117     yield tempfile.mkdtemp(".test", "xattr-", path)
118
119 def get_symlink(path, dangling=True):
120     """create a symlink"""
121     fh, fname = get_file(path)
122     os.close(fh)
123     if dangling:
124         os.unlink(fname)
125     sname = fname + ".symlink"
126     os.symlink(fname, sname)
127     return fname, sname
128
129 @contextlib.contextmanager
130 def get_valid_symlink(path):
131     yield get_symlink(path, dangling=False)[1]
132
133 @contextlib.contextmanager
134 def get_dangling_symlink(path):
135     yield get_symlink(path, dangling=True)[1]
136
137 @contextlib.contextmanager
138 def get_file_and_symlink(path):
139     yield get_symlink(path, dangling=False)
140
141 @contextlib.contextmanager
142 def get_file_and_fobject(path):
143     fh, fname = get_file(path)
144     with os.fdopen(fh) as fo:
145         yield fname, fo
146
147 # Wrappers that build upon existing values
148
149 def as_wrapper(call, fn, closer=None):
150     @contextlib.contextmanager
151     def f(path):
152         with call(path) as r:
153             val = fn(r)
154             yield val
155             if closer is not None:
156                 closer(val)
157     return f
158
159 def as_bytes(call):
160     return as_wrapper(call, lambda r: r.encode())
161
162 def as_fspath(call):
163     return as_wrapper(call, pathlib.PurePath)
164
165 def as_iostream(call):
166     opener = lambda f: io.open(f, "r")
167     closer = lambda r: r.close()
168     return as_wrapper(call, opener, closer)
169
170 NOT_BEFORE_36 = pytest.mark.xfail(condition="sys.version_info < (3,6)",
171                                   strict=True)
172 NOT_PYPY = pytest.mark.xfail(condition="platform.python_implementation() == 'PyPy'",
173                                   strict=False)
174
175 require_acl_from_mode = pytest.mark.skipif("not HAS_ACL_FROM_MODE")
176 require_acl_check = pytest.mark.skipif("not HAS_ACL_CHECK")
177 require_acl_entry = pytest.mark.skipif("not HAS_ACL_ENTRY")
178 require_extended_check = pytest.mark.skipif("not HAS_EXTENDED_CHECK")
179 require_equiv_mode = pytest.mark.skipif("not HAS_EQUIV_MODE")
180 require_copy_ext = pytest.mark.skipif("not HAS_COPY_EXT")
181
182 # Note: ACLs are valid only for files/directories, not symbolic links
183 # themselves, so we only create valid symlinks.
184 FILE_P = [
185     get_file_name,
186     as_bytes(get_file_name),
187     pytest.param(as_fspath(get_file_name),
188                  marks=[NOT_BEFORE_36, NOT_PYPY]),
189     get_dir,
190     as_bytes(get_dir),
191     pytest.param(as_fspath(get_dir),
192                  marks=[NOT_BEFORE_36, NOT_PYPY]),
193     get_valid_symlink,
194     as_bytes(get_valid_symlink),
195     pytest.param(as_fspath(get_valid_symlink),
196                  marks=[NOT_BEFORE_36, NOT_PYPY]),
197 ]
198
199 FILE_D = [
200     "file name",
201     "file name (bytes)",
202     "file name (path)",
203     "directory",
204     "directory (bytes)",
205     "directory (path)",
206     "file via symlink",
207     "file via symlink (bytes)",
208     "file via symlink (path)",
209 ]
210
211 FD_P = [
212     get_file_fd,
213     get_file_object,
214     as_iostream(get_file_name),
215 ]
216
217 FD_D = [
218     "file FD",
219     "file object",
220     "file io stream",
221 ]
222
223 DIR_D = [
224     "directory",
225     "directory (bytes)",
226     "directory (path object)",
227 ]
228
229 DIR_P = [
230     get_dir,
231     as_bytes(get_dir),
232     pytest.param(as_fspath(get_dir),
233                  marks=[NOT_BEFORE_36, NOT_PYPY]),
234 ]
235
236 ALL_P = FILE_P + FD_P
237 ALL_D = FILE_D + FD_D
238
239 @pytest.fixture(params=FILE_P, ids=FILE_D)
240 def file_subject(testdir, request):
241     with request.param(testdir) as value:
242         yield value
243
244 @pytest.fixture(params=FD_P, ids=FD_D)
245 def fd_subject(testdir, request):
246     with request.param(testdir) as value:
247         yield value
248
249 @pytest.fixture(params=DIR_P, ids=DIR_D)
250 def dir_subject(testdir, request):
251     with request.param(testdir) as value:
252         yield value
253
254 @pytest.fixture(params=ALL_P, ids=ALL_D)
255 def subject(testdir, request):
256     with request.param(testdir) as value:
257         yield value
258
259
260 class TestLoad:
261     """Load/create tests"""
262     def test_from_file(self, file_subject):
263         """Test loading ACLs from a file/directory"""
264         acl = posix1e.ACL(file=file_subject)
265         assert acl.valid()
266
267     def test_from_dir(self, dir_subject):
268         """Test loading ACLs from a directory"""
269         acl2 = posix1e.ACL(filedef=dir_subject)
270         # default ACLs might or might not be valid; missing ones are
271         # not valid, so we don't test acl2 for validity
272
273     def test_from_fd(self, fd_subject):
274         """Test loading ACLs from a file descriptor"""
275         acl = posix1e.ACL(fd=fd_subject)
276         assert acl.valid()
277
278     def test_from_nonexisting(self, testdir):
279         _, fname = get_file(testdir)
280         with pytest.raises(IOError):
281             posix1e.ACL(file="fname"+".no-such-file")
282         with pytest.raises(IOError):
283             posix1e.ACL(filedef="fname"+".no-such-file")
284
285     def test_from_invalid_fd(self, testdir):
286         fd, _ = get_file(testdir)
287         os.close(fd)
288         with pytest.raises(IOError):
289             posix1e.ACL(fd=fd)
290
291     def test_from_empty_invalid(self):
292         """Test creating an empty ACL"""
293         acl1 = posix1e.ACL()
294         assert not acl1.valid()
295
296     def test_from_text(self):
297         """Test creating an ACL from text"""
298         acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
299         assert acl1.valid()
300
301     # This is acl_check, but should actually be have_linux...
302     @require_acl_check
303     def test_from_acl(self):
304         """Test creating an ACL from an existing ACL"""
305         acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
306         acl2 = posix1e.ACL(acl=acl1)
307         assert acl1 == acl2
308
309     def test_from_acl_via_str(self):
310         # This is needed for not HAVE_LINUX cases.
311         acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
312         acl2 = posix1e.ACL(acl=acl1)
313         assert str(acl1) == str(acl2)
314
315     def test_invalid_creation_params(self, testdir):
316         """Test that creating an ACL from multiple objects fails"""
317         fd, _ = get_file(testdir)
318         with pytest.raises(ValueError):
319           posix1e.ACL(text=BASIC_ACL_TEXT, fd=fd)
320
321     def test_invalid_value_creation(self):
322         """Test that creating an ACL from wrong specification fails"""
323         with pytest.raises(EnvironmentError):
324           posix1e.ACL(text="foobar")
325         with pytest.raises(TypeError):
326           posix1e.ACL(foo="bar")
327
328     def test_uninit(self):
329         """Checks that uninit is actually empty init"""
330         acl = posix1e.ACL.__new__(posix1e.ACL)
331         assert not acl.valid()
332         e = acl.append()
333         e.permset
334         acl.delete_entry(e)
335
336     def test_double_init(self):
337         acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
338         assert acl1.valid()
339         acl1.__init__(text=BASIC_ACL_TEXT) # type: ignore
340         assert acl1.valid()
341         acl2 = ACL(text=TEXT_0755)
342         assert acl1 != acl2
343         acl1.__init__(acl=acl2)  # type: ignore
344         assert_acl_eq(acl1, acl2)
345
346     def test_reinit_failure_noop(self):
347         a = posix1e.ACL(text=TEXT_0755)
348         b = posix1e.ACL(acl=a)
349         assert_acl_eq(a, b)
350         with pytest.raises(IOError):
351             a.__init__(text='foobar')
352         assert_acl_eq(a, b)
353
354     @pytest.mark.xfail(reason="Unreliable test, re-init doesn't always invalidate children")
355     def test_double_init_breaks_children(self):
356         acl = posix1e.ACL()
357         e = acl.append()
358         e.permset.write = True
359         acl.__init__() # type: ignore
360         with pytest.raises(EnvironmentError):
361             e.permset.write = False
362
363
364 class TestAclExtensions:
365     """ACL extensions checks"""
366
367     @require_acl_from_mode
368     def test_from_mode(self):
369         """Test loading ACLs from an octal mode"""
370         acl1 = posix1e.ACL(mode=0o644)
371         assert acl1.valid()
372
373     @require_acl_check
374     def test_acl_check(self):
375         """Test the acl_check method"""
376         acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
377         assert not acl1.check()
378         acl2 = posix1e.ACL()
379         c = acl2.check()
380         assert c == (ACL_MISS_ERROR, 0)
381         assert isinstance(c, tuple)
382         assert c[0] == ACL_MISS_ERROR
383         e = acl2.append()
384         c = acl2.check()
385         assert c == (ACL_ENTRY_ERROR, 0)
386
387     def test_applyto(self, subject):
388         """Test the apply_to function"""
389         # TODO: add read/compare with before, once ACL can be init'ed
390         # from any source.
391         basic_acl = posix1e.ACL(text=BASIC_ACL_TEXT)
392         basic_acl.applyto(subject)
393         enhanced_acl = posix1e.ACL(text="u::rw,g::-,o::-,u:root:rw,mask::r")
394         assert enhanced_acl.valid()
395         enhanced_acl.applyto(subject)
396
397     def test_apply_to_with_wrong_object(self):
398         acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
399         assert acl1.valid()
400         with pytest.raises(TypeError):
401           acl1.applyto(object())
402         with pytest.raises(TypeError):
403           acl1.applyto(object(), object()) # type: ignore
404
405     def test_apply_to_fail(self, testdir):
406         acl1 = posix1e.ACL(text=BASIC_ACL_TEXT)
407         assert acl1.valid()
408         fd, fname = get_file(testdir)
409         os.close(fd)
410         with pytest.raises(IOError):
411           acl1.applyto(fd)
412         with pytest.raises(IOError, match="no-such-file"):
413           acl1.applyto(fname+".no-such-file")
414
415     @require_extended_check
416     def test_applyto_extended(self, subject):
417         """Test the acl_extended function"""
418         basic_acl = posix1e.ACL(text=BASIC_ACL_TEXT)
419         basic_acl.applyto(subject)
420         assert not has_extended(subject)
421         enhanced_acl = posix1e.ACL(text="u::rw,g::-,o::-,u:root:rw,mask::r")
422         assert enhanced_acl.valid()
423         enhanced_acl.applyto(subject)
424         assert has_extended(subject)
425
426     @require_extended_check
427     @pytest.mark.parametrize(
428         "gen", [ get_file_and_symlink, get_file_and_fobject ])
429     def test_applyto_extended_mixed(self, testdir, gen):
430         """Test the acl_extended function"""
431         with gen(testdir) as (a, b):
432             basic_acl = posix1e.ACL(text=BASIC_ACL_TEXT)
433             basic_acl.applyto(a)
434             for item in a, b:
435                 assert not has_extended(item)
436             enhanced_acl = posix1e.ACL(text="u::rw,g::-,o::-,u:root:rw,mask::r")
437             assert enhanced_acl.valid()
438             enhanced_acl.applyto(b)
439             for item in a, b:
440                 assert has_extended(item)
441
442     @require_extended_check
443     def test_extended_fail(self, testdir):
444         fd, fname = get_file(testdir)
445         os.close(fd)
446         with pytest.raises(IOError):
447           has_extended(fd)
448         with pytest.raises(IOError, match="no-such-file"):
449           has_extended(fname+".no-such-file")
450
451     @require_extended_check
452     def test_extended_arg_handling(self):
453       with pytest.raises(TypeError):
454         has_extended() # type: ignore
455       with pytest.raises(TypeError):
456         has_extended(object()) # type: ignore
457
458     @require_equiv_mode
459     def test_equiv_mode(self):
460         """Test the equiv_mode function"""
461         if HAS_ACL_FROM_MODE:
462             for mode in 0o644, 0o755:
463                 acl = posix1e.ACL(mode=mode)
464                 assert acl.equiv_mode() == mode
465         acl = posix1e.ACL(text="u::rw,g::r,o::r")
466         assert acl.equiv_mode() == 0o644
467         acl = posix1e.ACL(text="u::rx,g::-,o::-")
468         assert acl.equiv_mode() == 0o500
469
470     @require_equiv_mode
471     @pytest.mark.xfail(reason="It seems equiv mode always passes, even for empty ACLs")
472     def test_equiv_mode_invalid(self):
473         """Test equiv_mode on invalid ACLs"""
474         a = posix1e.ACL()
475         with pytest.raises(EnvironmentError):
476             a.equiv_mode()
477
478     @require_acl_check
479     def test_to_any_text(self):
480         acl = posix1e.ACL(text=BASIC_ACL_TEXT)
481         assert b"u::" in \
482           acl.to_any_text(options=posix1e.TEXT_ABBREVIATE)
483         assert b"user::" in acl.to_any_text()
484
485     @require_acl_check
486     def test_to_any_text_wrong_args(self):
487         acl = posix1e.ACL(text=BASIC_ACL_TEXT)
488         with pytest.raises(TypeError):
489           acl.to_any_text(foo="bar") # type: ignore
490
491
492     @require_acl_check
493     def test_rich_compare(self):
494         acl1 = posix1e.ACL(text="u::rw,g::r,o::r")
495         acl2 = posix1e.ACL(acl=acl1)
496         acl3 = posix1e.ACL(text="u::rw,g::rw,o::r")
497         assert acl1 == acl2
498         assert acl1 != acl3
499         with pytest.raises(TypeError):
500           acl1 < acl2 # type: ignore
501         with pytest.raises(TypeError):
502           acl1 >= acl3 # type: ignore
503         assert acl1 != True # type: ignore
504         assert not (acl1 == 1) # type: ignore
505         with pytest.raises(TypeError):
506           acl1 > True # type: ignore
507
508     @require_acl_entry
509     def test_acl_iterator(self):
510         acl = posix1e.ACL(text=BASIC_ACL_TEXT)
511         for entry in acl:
512             assert entry.parent is acl
513
514     @require_copy_ext
515     def test_acl_copy_ext(self):
516         a = posix1e.ACL(text=BASIC_ACL_TEXT)
517         b = posix1e.ACL()
518         c = posix1e.ACL(acl=b)
519         assert a != b
520         assert b == c
521         state = a.__getstate__()
522         b.__setstate__(state)
523         assert a == b
524         assert b != c
525
526     @require_copy_ext
527     def test_acl_copy_ext_failure(self):
528         a = posix1e.ACL()
529         state = a.__getstate__()
530         # This is a dangerous test. The acl_copy_int() C function gets
531         # a void * buffer, and then casts that to an ACL structure,
532         # irrespective of buffer length; this can lead to segfaults
533         # (via unallocated memory indexing)
534         #
535         # To mitigate this, pass same buffer size as returned from the
536         # state, just nulled out - in the Linux version of the
537         # library, the first byte is the structure size and is tested
538         # for correct size, and a null byte will cause failure.
539         nulled = b'\x00' * len(state)
540         with pytest.raises(IOError):
541             a.__setstate__(nulled)
542
543     @require_copy_ext
544     def test_acl_copy_ext_args(self):
545         a = posix1e.ACL()
546         with pytest.raises(TypeError):
547             a.__setstate__(None)
548
549     @require_copy_ext
550     def test_acl_init_copy_ext(self):
551         a = posix1e.ACL(text=BASIC_ACL_TEXT)
552         b = posix1e.ACL()
553         c = posix1e.ACL(data=a.__getstate__())
554         assert c != b
555         assert c == a
556
557     @require_copy_ext
558     def test_acl_init_copy_ext_invalid(self):
559         with pytest.raises(IOError):
560             posix1e.ACL(data=b"foobar")
561
562
563 class TestWrite:
564     """Write tests"""
565
566     def test_delete_default(self, testdir):
567         """Test removing the default ACL"""
568         with get_dir(testdir) as dname:
569           posix1e.delete_default(dname)
570
571     def test_delete_default_fail(self, testdir):
572         """Test removing the default ACL"""
573         with get_file_name(testdir) as fname:
574             with pytest.raises(IOError, match="no-such-file"):
575                 posix1e.delete_default(fname+".no-such-file")
576
577     @NOT_PYPY
578     def test_delete_default_wrong_arg(self):
579         with pytest.raises(TypeError):
580           posix1e.delete_default(object()) # type: ignore
581
582     def test_reapply(self, testdir):
583         """Test re-applying an ACL"""
584         fd, fname = get_file(testdir)
585         acl1 = posix1e.ACL(fd=fd)
586         acl1.applyto(fd)
587         acl1.applyto(fname)
588         with get_dir(testdir) as dname:
589           acl2 = posix1e.ACL(file=fname)
590           acl2.applyto(dname)
591
592
593
594 @require_acl_entry
595 class TestModification:
596     """ACL modification tests"""
597
598     def checkRef(self, obj):
599         """Checks if a given obj has a 'sane' refcount"""
600         if platform.python_implementation() == "PyPy":
601             return
602         ref_cnt = sys.getrefcount(obj)
603         # FIXME: hardcoded value for the max ref count... but I've
604         # seen it overflow on bad reference counting, so it's better
605         # to be safe
606         if ref_cnt < 2 or ref_cnt > 1024:
607             pytest.fail("Wrong reference count, expected 2-1024 and got %d" %
608                         ref_cnt)
609
610     def test_str(self):
611         """Test str() of an ACL."""
612         acl = posix1e.ACL(text=BASIC_ACL_TEXT)
613         str_acl = str(acl)
614         self.checkRef(str_acl)
615
616     def test_append(self):
617         """Test append a new Entry to the ACL"""
618         acl = posix1e.ACL()
619         e = acl.append()
620         e.tag_type = posix1e.ACL_OTHER
621         ignore_ioerror(errno.EINVAL, acl.calc_mask)
622         str_format = str(e)
623         self.checkRef(str_format)
624         e2 = acl.append(e)
625         ignore_ioerror(errno.EINVAL, acl.calc_mask)
626         assert not acl.valid()
627
628     def test_wrong_append(self):
629         """Test append a new Entry to the ACL based on wrong object type"""
630         acl = posix1e.ACL()
631         with pytest.raises(TypeError):
632           acl.append(object()) # type: ignore
633
634     @pytest.mark.xfail(reason="Behaviour not conform to specification")
635     def test_append_invalid_source(self):
636         a = posix1e.ACL()
637         b = posix1e.ACL()
638         f = b.append()
639         b.delete_entry(f)
640         with pytest.raises(EnvironmentError):
641             f.permset.write = True
642         with pytest.raises(EnvironmentError):
643             e = a.append(f)
644
645     def test_entry_creation(self):
646         acl = posix1e.ACL()
647         e = posix1e.Entry(acl)
648         ignore_ioerror(errno.EINVAL, acl.calc_mask)
649         str_format = str(e)
650         self.checkRef(str_format)
651
652     def test_entry_failed_creation(self):
653         # Checks for partial initialisation and deletion on error
654         # path.
655         with pytest.raises(TypeError):
656           posix1e.Entry(object()) # type: ignore
657
658     def test_entry_reinitialisations(self):
659         a = posix1e.ACL()
660         b = posix1e.ACL()
661         e = posix1e.Entry(a)
662         e.__init__(a) # type: ignore
663         with pytest.raises(ValueError, match="different parent"):
664             e.__init__(b) # type: ignore
665
666     @NOT_PYPY
667     def test_entry_reinit_leaks_refcount(self):
668         acl = posix1e.ACL()
669         e = acl.append()
670         ref = sys.getrefcount(acl)
671         e.__init__(acl) # type: ignore
672         assert ref == sys.getrefcount(acl), "Uh-oh, ref leaks..."
673
674     def test_delete(self):
675         """Test delete Entry from the ACL"""
676         acl = posix1e.ACL()
677         e = acl.append()
678         e.tag_type = posix1e.ACL_OTHER
679         ignore_ioerror(errno.EINVAL, acl.calc_mask)
680         acl.delete_entry(e)
681         ignore_ioerror(errno.EINVAL, acl.calc_mask)
682
683     def test_double_delete(self):
684         """Test delete Entry from the ACL"""
685         # This is not entirely valid/correct, since the entry object
686         # itself is invalid after the first deletion, so we're
687         # actually testing deleting an invalid object, not a
688         # non-existing entry...
689         acl = posix1e.ACL()
690         e = acl.append()
691         e.tag_type = posix1e.ACL_OTHER
692         ignore_ioerror(errno.EINVAL, acl.calc_mask)
693         acl.delete_entry(e)
694         ignore_ioerror(errno.EINVAL, acl.calc_mask)
695         with pytest.raises(EnvironmentError):
696           acl.delete_entry(e)
697
698     def test_delete_unowned(self):
699         """Test delete Entry from the ACL"""
700         a = posix1e.ACL()
701         b = posix1e.ACL()
702         e = a.append()
703         e.tag_type = posix1e.ACL_OTHER
704         with pytest.raises(ValueError, match="un-owned entry"):
705             b.delete_entry(e)
706
707     # This currently fails as this deletion seems to be accepted :/
708     @pytest.mark.xfail(reason="Entry deletion is unreliable")
709     def testDeleteInvalidEntry(self):
710         """Test delete foreign Entry from the ACL"""
711         acl1 = posix1e.ACL()
712         acl2 = posix1e.ACL()
713         e = acl1.append()
714         e.tag_type = posix1e.ACL_OTHER
715         ignore_ioerror(errno.EINVAL, acl1.calc_mask)
716         with pytest.raises(EnvironmentError):
717           acl2.delete_entry(e)
718
719     def test_delete_invalid_object(self):
720         """Test delete a non-Entry from the ACL"""
721         acl = posix1e.ACL()
722         with pytest.raises(TypeError):
723           acl.delete_entry(object()) # type: ignore
724
725     def test_double_entries(self):
726         """Test double entries"""
727         acl = posix1e.ACL(text=BASIC_ACL_TEXT)
728         assert acl.valid()
729         for tag_type in (posix1e.ACL_USER_OBJ, posix1e.ACL_GROUP_OBJ,
730                          posix1e.ACL_OTHER):
731             e = acl.append()
732             e.tag_type = tag_type
733             e.permset.clear()
734             assert not acl.valid(), ("ACL containing duplicate entries"
735                                      " should not be valid")
736             acl.delete_entry(e)
737
738     def test_multiple_good_entries(self):
739         """Test multiple valid entries"""
740         acl = posix1e.ACL(text=BASIC_ACL_TEXT)
741         assert acl.valid()
742         for tag_type in (posix1e.ACL_USER,
743                          posix1e.ACL_GROUP):
744             for obj_id in range(5):
745                 e = acl.append()
746                 e.tag_type = tag_type
747                 e.qualifier = obj_id
748                 e.permset.clear()
749                 acl.calc_mask()
750                 assert acl.valid(), ("ACL should be able to hold multiple"
751                                      " user/group entries")
752
753     def test_multiple_bad_entries(self):
754         """Test multiple invalid entries"""
755         for tag_type in (posix1e.ACL_USER,
756                          posix1e.ACL_GROUP):
757             acl = posix1e.ACL(text=BASIC_ACL_TEXT)
758             assert acl.valid()
759             e1 = acl.append()
760             e1.tag_type = tag_type
761             e1.qualifier = 0
762             e1.permset.clear()
763             acl.calc_mask()
764             assert acl.valid(), ("ACL should be able to add a"
765                                  " user/group entry")
766             e2 = acl.append()
767             e2.tag_type = tag_type
768             e2.qualifier = 0
769             e2.permset.clear()
770             ignore_ioerror(errno.EINVAL, acl.calc_mask)
771             assert not acl.valid(), ("ACL should not validate when"
772                                      " containing two duplicate entries")
773             acl.delete_entry(e1)
774             # FreeBSD trips over itself here and can't delete the
775             # entry, even though it still exists.
776             ignore_ioerror(errno.EINVAL, acl.delete_entry, e2)
777
778     def test_copy(self):
779         acl = ACL()
780         e1 = acl.append()
781         e1.tag_type = ACL_USER
782         p1 = e1.permset
783         p1.clear()
784         p1.read = True
785         p1.write = True
786         e2 = acl.append()
787         e2.tag_type = ACL_GROUP
788         p2 = e2.permset
789         p2.clear()
790         p2.read = True
791         assert not p2.write
792         e2.copy(e1)
793         assert p2.write
794         assert e1.tag_type == e2.tag_type
795
796     def test_copy_wrong_arg(self):
797         acl = ACL()
798         e = acl.append()
799         with pytest.raises(TypeError):
800           e.copy(object()) # type: ignore
801
802     def test_set_permset(self):
803         acl = ACL()
804         e1 = acl.append()
805         e1.tag_type = ACL_USER
806         p1 = e1.permset
807         p1.clear()
808         p1.read = True
809         p1.write = True
810         e2 = acl.append()
811         e2.tag_type = ACL_GROUP
812         p2 = e2.permset
813         p2.clear()
814         p2.read = True
815         assert not p2.write
816         e2.permset = p1
817         assert e2.permset.write
818         assert e2.tag_type == ACL_GROUP
819
820     def test_set_permset_wrong_arg(self):
821         acl = ACL()
822         e = acl.append()
823         with pytest.raises(TypeError):
824           e.permset = object() # type: ignore
825
826     def test_permset_creation(self):
827         acl = ACL()
828         e = acl.append()
829         p1 = e.permset
830         p2 = Permset(e)
831         #assert p1 == p2
832
833     def test_permset_creation_wrong_arg(self):
834         with pytest.raises(TypeError):
835           Permset(object()) # type: ignore
836
837     def test_permset_reinitialisations(self):
838         a = posix1e.ACL()
839         e = posix1e.Entry(a)
840         f = posix1e.Entry(a)
841         p = e.permset
842         p.__init__(e) # type: ignore
843         with pytest.raises(ValueError, match="different parent"):
844             p.__init__(f) # type: ignore
845
846     @NOT_PYPY
847     def test_permset_reinit_leaks_refcount(self):
848         acl = posix1e.ACL()
849         e = acl.append()
850         p = e.permset
851         ref = sys.getrefcount(e)
852         p.__init__(e) # type: ignore
853         assert ref == sys.getrefcount(e), "Uh-oh, ref leaks..."
854
855     @pytest.mark.parametrize("perm, txt, accessor",
856                              PERMSETS, ids=PERMSETS_IDS)
857     def test_permset(self, perm, txt, accessor):
858         """Test permissions"""
859         del accessor
860         acl = posix1e.ACL()
861         e = acl.append()
862         ps = e.permset
863         ps.clear()
864         str_ps = str(ps)
865         self.checkRef(str_ps)
866         assert not ps.test(perm), ("Empty permission set should not"
867                                    " have permission '%s'" % txt)
868         ps.add(perm)
869         assert ps.test(perm), ("Permission '%s' should exist"
870                                " after addition" % txt)
871         str_ps = str(ps)
872         self.checkRef(str_ps)
873         ps.delete(perm)
874         assert not ps.test(perm), ("Permission '%s' should not exist"
875                                    " after deletion" % txt)
876         ps.add(perm)
877         assert ps.test(perm), ("Permission '%s' should exist"
878                                " after addition" % txt)
879         ps.clear()
880         assert not ps.test(perm), ("Permission '%s' should not exist"
881                                    " after clearing" % txt)
882
883
884
885     @pytest.mark.parametrize("perm, txt, accessor",
886                              PERMSETS, ids=PERMSETS_IDS)
887     def test_permset_via_accessors(self, perm, txt, accessor):
888         """Test permissions"""
889         acl = posix1e.ACL()
890         e = acl.append()
891         ps = e.permset
892         ps.clear()
893         def getter():
894             return accessor.__get__(ps) # type: ignore
895         def setter(value):
896             return accessor.__set__(ps, value) # type: ignore
897         str_ps = str(ps)
898         self.checkRef(str_ps)
899         assert not getter(), ("Empty permission set should not"
900                               " have permission '%s'" % txt)
901         setter(True)
902         assert ps.test(perm), ("Permission '%s' should exist"
903                                " after addition" % txt)
904         assert getter(), ("Permission '%s' should exist"
905                           " after addition" % txt)
906         str_ps = str(ps)
907         self.checkRef(str_ps)
908         setter(False)
909         assert not ps.test(perm), ("Permission '%s' should not exist"
910                                    " after deletion" % txt)
911         assert not getter(), ("Permission '%s' should not exist"
912                                   " after deletion" % txt)
913         setter(True)
914         assert getter()
915         ps.clear()
916         assert not getter()
917
918     def test_permset_invalid_type(self):
919         acl = posix1e.ACL()
920         e = acl.append()
921         ps = e.permset
922         ps.clear()
923         with pytest.raises(TypeError):
924           ps.add("foobar") # type: ignore
925         with pytest.raises(TypeError):
926           ps.delete("foobar") # type: ignore
927         with pytest.raises(TypeError):
928           ps.test("foobar") # type: ignore
929         with pytest.raises(ValueError):
930           ps.write = object() # type: ignore
931
932     @pytest.mark.parametrize("tag", [ACL_USER, ACL_GROUP],
933                              ids=["ACL_USER", "ACL_GROUP"])
934     def test_qualifier_values(self, tag):
935         """Tests qualifier correct store/retrieval"""
936         acl = posix1e.ACL()
937         e = acl.append()
938         qualifier = 1
939         e.tag_type = tag
940         while True:
941             regex = re.compile("(user|group) with (u|g)id %d" % qualifier)
942             try:
943                 e.qualifier = qualifier
944             except OverflowError:
945                 # reached overflow condition, break
946                 break
947             assert e.qualifier == qualifier
948             assert regex.search(str(e)) is not None
949             qualifier *= 2
950
951     def test_qualifier_overflow(self):
952         """Tests qualifier overflow handling"""
953         acl = posix1e.ACL()
954         e = acl.append()
955         # the uid_t/gid_t are unsigned, so they can hold slightly more
956         # than sys.maxsize*2 (on Linux).
957         qualifier = (sys.maxsize + 1) * 2
958         for tag in [posix1e.ACL_USER, posix1e.ACL_GROUP]:
959             e.tag_type = tag
960             with pytest.raises(OverflowError):
961                 e.qualifier = qualifier
962
963     def test_qualifier_underflow(self):
964         """Tests negative qualifier handling"""
965         # Note: this presumes that uid_t/gid_t in C are unsigned...
966         acl = posix1e.ACL()
967         e = acl.append()
968         for tag in [posix1e.ACL_USER, posix1e.ACL_GROUP]:
969             e.tag_type = tag
970             for qualifier in [-10, -5, -1]:
971                 with pytest.raises(OverflowError):
972                     e.qualifier = qualifier
973
974     def test_invalid_qualifier(self):
975         """Tests invalid qualifier handling"""
976         acl = posix1e.ACL()
977         e = acl.append()
978         with pytest.raises(TypeError):
979           e.qualifier = object() # type: ignore
980         with pytest.raises((TypeError, AttributeError)):
981           del e.qualifier
982
983     def test_qualifier_on_wrong_tag(self):
984         """Tests qualifier setting on wrong tag"""
985         acl = posix1e.ACL()
986         e = acl.append()
987         e.tag_type = posix1e.ACL_OTHER
988         with pytest.raises(TypeError):
989           e.qualifier = 1
990         with pytest.raises(TypeError):
991           e.qualifier
992
993     @pytest.mark.parametrize("tag", ALL_TAG_VALUES, ids=ALL_TAG_DESCS)
994     def test_tag_types(self, tag):
995         """Tests tag type correct set/get"""
996         acl = posix1e.ACL()
997         e = acl.append()
998         e.tag_type = tag
999         assert e.tag_type == tag
1000         # check we can show all tag types without breaking
1001         assert str(e)
1002
1003     @pytest.mark.parametrize("src_tag", ALL_TAG_VALUES, ids=ALL_TAG_DESCS)
1004     @pytest.mark.parametrize("dst_tag", ALL_TAG_VALUES, ids=ALL_TAG_DESCS)
1005     def test_tag_overwrite(self, src_tag, dst_tag):
1006         """Tests tag type correct set/get"""
1007         acl = posix1e.ACL()
1008         e = acl.append()
1009         e.tag_type = src_tag
1010         assert e.tag_type == src_tag
1011         assert str(e)
1012         e.tag_type = dst_tag
1013         assert e.tag_type == dst_tag
1014         assert str(e)
1015
1016     def test_invalid_tags(self):
1017         """Tests tag type incorrect set/get"""
1018         acl = posix1e.ACL()
1019         e = acl.append()
1020         with pytest.raises(TypeError):
1021           e.tag_type = object() # type: ignore
1022         e.tag_type = posix1e.ACL_USER_OBJ
1023         # For some reason, PyPy raises AttributeError. Strange...
1024         with pytest.raises((TypeError, AttributeError)):
1025           del e.tag_type
1026
1027     def test_tag_wrong_overwrite(self):
1028         acl = posix1e.ACL()
1029         e = acl.append()
1030         e.tag_type = posix1e.ACL_USER_OBJ
1031         tag = max(ALL_TAG_VALUES) + 1
1032         with pytest.raises(EnvironmentError):
1033           e.tag_type = tag
1034         # Check tag is still valid.
1035         assert e.tag_type == posix1e.ACL_USER_OBJ
1036
1037 if __name__ == "__main__":
1038     unittest.main()