File: test_folder_traversal.py

package info (click to toggle)
python-b2sdk 2.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,020 kB
  • sloc: python: 30,902; sh: 13; makefile: 8
file content (795 lines) | stat: -rw-r--r-- 31,470 bytes parent folder | download
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
######################################################################
#
# File: test/unit/scan/test_folder_traversal.py
#
# Copyright 2023 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
from __future__ import annotations

import codecs
import os
import pathlib
import platform
import re
import shlex
import sys
from unittest.mock import MagicMock, patch

import pytest

from b2sdk._internal.scan.folder import LocalFolder
from b2sdk._internal.scan.policies import ScanPoliciesManager
from b2sdk._internal.scan.report import ProgressReport
from b2sdk._internal.utils import fix_windows_path_limit


class TestFolderTraversal:
    def test_flat_folder(self, tmp_path):
        # Create a directory structure below with initial scanning point at tmp_path/dir:
        # tmp_path
        # └── dir
        #     ├── file1.txt
        #     ├── file2.txt
        #     └── file3.txt

        (tmp_path / 'dir').mkdir(parents=True)

        (tmp_path / 'dir' / 'file1.txt').write_text('content1')
        (tmp_path / 'dir' / 'file2.txt').write_text('content2')
        (tmp_path / 'dir' / 'file3.txt').write_text('content3')

        folder = LocalFolder(str(tmp_path / 'dir'))
        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'dir' / 'file1.txt')),
            fix_windows_path_limit(str(tmp_path / 'dir' / 'file2.txt')),
            fix_windows_path_limit(str(tmp_path / 'dir' / 'file3.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows',
        reason="Windows doesn't allow / or \\ in filenames",
    )
    def test_invalid_name(self, tmp_path):
        # Create a directory structure below with initial scanning point at tmp_path/dir:
        # tmp_path
        # └── dir
        #     ├── file1.txt
        #     ├── subdir
        #     │   └── file2.txt
        #     ├── file\bad.txt
        #     └── file[DEL]bad.txt

        (tmp_path / 'dir' / 'subdir').mkdir(parents=True)

        (tmp_path / 'dir' / 'file1.txt').write_text('content1')
        (tmp_path / 'dir' / 'subdir' / 'file2.txt').write_text('content2')
        (tmp_path / 'dir' / 'file\\bad.txt').write_text('bad1')
        (tmp_path / 'dir' / 'file\x7fbad.txt').write_text('bad2')

        reporter = ProgressReport(sys.stdout, False)
        folder = LocalFolder(str(tmp_path / 'dir'))
        local_paths = folder.all_files(reporter=reporter)
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert reporter.has_errors_or_warnings()
        assert isinstance(reporter.warnings, list)
        assert sorted(reporter.warnings) == [
            f"WARNING: '{tmp_path}/dir/file\\bad.txt' path contains invalid name (file names must not contain '\\'). Skipping.",
            f"WARNING: '{tmp_path}/dir/file\\x7fbad.txt' path contains invalid name (file names must not contain DEL). Skipping.",
        ]
        reporter.close()

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'dir' / 'file1.txt')),
            fix_windows_path_limit(str(tmp_path / 'dir' / 'subdir' / 'file2.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows'
        and (platform.python_implementation() == 'PyPy' or sys.version_info >= (3, 13)),
        reason=(
            'PyPy on Windows force-decodes non-UTF-8 filenames, which makes it impossible to test this case. '
            'Python 3.13 does so similarly on Windows.'
        ),
    )
    def test_invalid_unicode_filename(self, tmp_path):
        # Create a directory structure below with initial scanning point at tmp_path/dir:
        # tmp_path
        # └── dir
        #     ├── file1.txt
        #     └── XXX (invalid utf-8 filename)

        (tmp_path / 'dir').mkdir(parents=True)
        (tmp_path / 'dir' / 'file1.txt').write_text('content1')

        foreign_encoding = 'euc_jp'
        # test sanity check
        assert (
            codecs.lookup(foreign_encoding).name != codecs.lookup(sys.getfilesystemencoding()).name
        )

        invalid_utf8_path = os.path.join(bytes(tmp_path), b'dir', 'てすと'.encode(foreign_encoding))
        try:
            with open(invalid_utf8_path, 'wb') as f:
                f.write(b'content2')
        except (OSError, UnicodeDecodeError):
            pytest.skip('Cannot create invalid UTF-8 filename on this platform')

        reporter = ProgressReport(sys.stdout, False)
        folder = LocalFolder(str(tmp_path / 'dir'))
        local_paths = folder.all_files(reporter=reporter)
        absolute_paths = [path.absolute_path for path in list(local_paths)]
        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'dir' / 'file1.txt')),
        ]

        assert reporter.has_errors_or_warnings()
        assert re.match(
            r"WARNING: '.+/dir/.+' path contains invalid name "
            r'\(file name must be valid Unicode, check locale\)\. Skipping\.',
            reporter.warnings[0],
        )
        assert len(reporter.warnings) == 1

        reporter.close()

    @pytest.mark.skipif(
        platform.system() == 'Windows',
        reason="Windows doesn't allow / or \\ in filenames",
    )
    def test_invalid_directory_name(self, tmp_path):
        # Create a directory structure below with initial scanning point at tmp_path/dir:
        # tmp_path
        # └── dir
        #     ├── file1.txt
        #     └── dir\bad
        #         └── file2.txt

        (tmp_path / 'dir').mkdir(parents=True)
        (tmp_path / 'dir' / 'file1.txt').write_text('content1')
        (tmp_path / 'dir' / 'dir\\bad').mkdir(parents=True)
        (tmp_path / 'dir' / 'dir\\bad' / 'file2.txt').write_text('content2')

        reporter = ProgressReport(sys.stdout, False)
        folder = LocalFolder(str(tmp_path / 'dir'))
        local_paths = folder.all_files(reporter=reporter)
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert reporter.has_errors_or_warnings()
        assert reporter.warnings == [
            f"WARNING: '{tmp_path}/dir/dir\\bad' path contains invalid name (file names must not contain '\\'). Skipping."
        ]
        reporter.close()

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'dir' / 'file1.txt')),
        ]

    def test_folder_with_subfolders(self, tmp_path):
        # Create a directory structure below with initial scanning point at tmp_path:
        # tmp_path
        # ├── dir1
        # │   ├── file1.txt
        # │   └── file2.txt
        # └── dir2
        #     ├── file3.txt
        #     └── file4.txt

        d1 = tmp_path / 'dir1'
        d1.mkdir()
        (d1 / 'file1.txt').write_text('content1')
        (d1 / 'file2.txt').write_text('content2')

        d2 = tmp_path / 'dir2'
        d2.mkdir()
        (d2 / 'file3.txt').write_text('content3')
        (d2 / 'file4.txt').write_text('content4')

        folder = LocalFolder(str(tmp_path))
        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(d1 / 'file1.txt')),
            fix_windows_path_limit(str(d1 / 'file2.txt')),
            fix_windows_path_limit(str(d2 / 'file3.txt')),
            fix_windows_path_limit(str(d2 / 'file4.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    def test_folder_with_symlink_to_file(self, tmp_path):
        # Create a directory structure below with initial scanning point at tmp_path:
        # tmp_path
        # ├── dir
        # │   └── file.txt
        # └── symlink_file.txt -> dir/file.txt

        (tmp_path / 'dir').mkdir()

        file = tmp_path / 'dir' / 'file.txt'
        file.write_text('content')

        symlink_file = tmp_path / 'symlink_file.txt'
        symlink_file.symlink_to(file)

        folder = LocalFolder(str(tmp_path))
        local_paths = folder.all_files(reporter=MagicMock())

        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(file)),
            fix_windows_path_limit(str(symlink_file)),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    @pytest.mark.timeout(5)
    def test_folder_with_circular_symlink(self, tmp_path):
        # Create a directory structure below with initial scanning point at tmp_path:
        # tmp_path
        # ├── dir
        # │   └── file.txt
        # └── symlink_dir -> dir

        (tmp_path / 'dir').mkdir()
        (tmp_path / 'dir' / 'file1.txt').write_text('content1')
        symlink_dir = tmp_path / 'dir' / 'symlink_dir'
        symlink_dir.symlink_to(tmp_path / 'dir', target_is_directory=True)

        folder = LocalFolder(str(tmp_path))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'dir' / 'file1.txt')),
            fix_windows_path_limit(str(tmp_path / 'dir' / 'symlink_dir' / 'file1.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    @pytest.mark.timeout(5)
    def test_folder_with_symlink_to_parent(self, tmp_path):
        # Create a directory structure below with the scanning point at tmp_path/parent/child/:
        #   tmp_path
        #   ├── parent
        #   │   ├── child
        #   │   │   ├── file4.txt
        #   │   │   └── grandchild
        #   │   │       ├── file5.txt
        #   │   │       └── symlink_dir -> ../../.. (symlink to tmp_path/parent)
        #   │   └── file3.txt
        #   ├── file1.txt
        #   └── file2.txt

        (tmp_path / 'parent' / 'child' / 'grandchild').mkdir(parents=True)
        (tmp_path / 'file1.txt').write_text('content1')
        (tmp_path / 'file2.txt').write_text('content2')
        (tmp_path / 'parent' / 'file3.txt').write_text('content3')
        (tmp_path / 'parent' / 'child' / 'file4.txt').write_text('content4')
        (tmp_path / 'parent' / 'child' / 'grandchild' / 'file5.txt').write_text('content5')
        symlink_dir = tmp_path / 'parent' / 'child' / 'grandchild' / 'symlink_dir'
        symlink_dir.symlink_to(tmp_path / 'parent', target_is_directory=True)

        folder = LocalFolder(str(tmp_path / 'parent' / 'child'))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'parent' / 'child' / 'file4.txt')),
            fix_windows_path_limit(str(tmp_path / 'parent' / 'child' / 'grandchild' / 'file5.txt')),
            fix_windows_path_limit(
                str(
                    tmp_path
                    / 'parent'
                    / 'child'
                    / 'grandchild'
                    / 'symlink_dir'
                    / 'child'
                    / 'file4.txt'
                )
            ),
            fix_windows_path_limit(
                str(
                    tmp_path
                    / 'parent'
                    / 'child'
                    / 'grandchild'
                    / 'symlink_dir'
                    / 'child'
                    / 'grandchild'
                    / 'file5.txt'
                )
            ),
            fix_windows_path_limit(
                str(tmp_path / 'parent' / 'child' / 'grandchild' / 'symlink_dir' / 'file3.txt')
            ),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    @pytest.mark.timeout(5)
    def test_root_short_loop(self, tmp_path):
        # Create a symlink to the tmp_path directory itself
        # tmp_path
        # └── tmp_path_symlink -> tmp_path

        tmp_path_symlink = tmp_path / 'tmp_path_symlink'
        tmp_path_symlink.symlink_to(tmp_path, target_is_directory=True)

        folder = LocalFolder(str(tmp_path_symlink))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == []

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    @pytest.mark.timeout(5)
    def test_root_parent_loop(self, tmp_path):
        # Create a symlink that points to the parent of the initial scanning point
        # tmp_path
        # └── start
        #     ├── file.txt
        #     └── symlink -> tmp_path

        (tmp_path / 'start').mkdir()
        (tmp_path / 'start' / 'file.txt').write_text('content')
        (tmp_path / 'start' / 'symlink').symlink_to(tmp_path, target_is_directory=True)

        folder = LocalFolder(str(tmp_path / 'start'))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'start' / 'file.txt')),
            fix_windows_path_limit(str(tmp_path / 'start' / 'symlink' / 'start' / 'file.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    def test_symlink_that_points_deeper(self, tmp_path):
        # Create a directory structure with a symlink that points to a deeper directory
        # tmp_path
        # ├── a
        # │   └── a.txt
        # └── b
        #     ├── c
        #     │   └── c.txt
        #     └── d
        #         ├── d.txt
        #         └── e
        #             └── e.txt
        # ├── f
        # │   └── f.txt
        # └── symlink -> b/d/e

        (tmp_path / 'a').mkdir()
        (tmp_path / 'a' / 'a.txt').write_text('a')
        (tmp_path / 'b' / 'c').mkdir(parents=True)
        (tmp_path / 'b' / 'c' / 'c.txt').write_text('c')
        (tmp_path / 'b' / 'd' / 'e').mkdir(parents=True)
        (tmp_path / 'b' / 'd' / 'd.txt').write_text('d')
        (tmp_path / 'b' / 'd' / 'e' / 'e.txt').write_text('e')
        (tmp_path / 'f').mkdir()
        (tmp_path / 'f' / 'f.txt').write_text('f')
        (tmp_path / 'symlink').symlink_to(tmp_path / 'b' / 'd' / 'e', target_is_directory=True)

        folder = LocalFolder(str(tmp_path))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'a' / 'a.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'c' / 'c.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'd' / 'd.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'd' / 'e' / 'e.txt')),
            fix_windows_path_limit(str(tmp_path / 'f' / 'f.txt')),
            fix_windows_path_limit(str(tmp_path / 'symlink' / 'e.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    def test_symlink_that_points_up(self, tmp_path):
        # Create a directory structure with a symlink that points to a upper directory
        # tmp_path
        # ├── a
        # │   └── a.txt
        # └── b
        #     ├── c
        #     │   └── c.txt
        #     └── d
        #         ├── d.txt
        #         └── e
        #             ├── symlink -> ../../a
        #             └── e.txt

        (tmp_path / 'a').mkdir()
        (tmp_path / 'a' / 'a.txt').write_text('a')
        (tmp_path / 'b' / 'c').mkdir(parents=True)
        (tmp_path / 'b' / 'c' / 'c.txt').write_text('c')
        (tmp_path / 'b' / 'd' / 'e').mkdir(parents=True)
        (tmp_path / 'b' / 'd' / 'd.txt').write_text('d')
        (tmp_path / 'b' / 'd' / 'e' / 'e.txt').write_text('e')
        (tmp_path / 'b' / 'd' / 'e' / 'symlink').symlink_to(
            tmp_path / 'a', target_is_directory=True
        )

        folder = LocalFolder(str(tmp_path))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'a' / 'a.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'c' / 'c.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'd' / 'd.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'd' / 'e' / 'e.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'd' / 'e' / 'symlink' / 'a.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    @pytest.mark.timeout(5)
    def test_elaborate_infinite_loop(self, tmp_path):
        # Create a directory structure with an elaborate infinite loop of symlinks
        # tmp_path
        # ├── a
        # │   └── a.txt
        # ├── b -> c
        # ├── c -> d
        # ├── d -> e
        # ├── e -> b
        # └── f
        #     └── f.txt

        (tmp_path / 'a').mkdir()
        (tmp_path / 'a' / 'a.txt').write_text('a')
        (tmp_path / 'b').symlink_to('c')
        (tmp_path / 'c').symlink_to('d')
        (tmp_path / 'd').symlink_to('e')
        (tmp_path / 'e').symlink_to('b')
        (tmp_path / 'f').mkdir()
        (tmp_path / 'f' / 'f.txt').write_text('f')

        folder = LocalFolder(str(tmp_path))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'a' / 'a.txt')),
            fix_windows_path_limit(str(tmp_path / 'f' / 'f.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    def test_valid_symlink_pattern_where_the_link_goes_down_and_up(self, tmp_path):
        # tmp_path
        # ├── a
        # │   └── a.txt
        # ├── b -> c/d
        # ├── c
        # │   └── d
        # │       └── b.txt
        # ├── d -> e
        # ├── e
        # │   └── e.txt
        # └── f
        #     └── f.txt

        (tmp_path / 'a').mkdir()
        (tmp_path / 'a' / 'a.txt').write_text('a')
        (tmp_path / 'b').symlink_to(tmp_path / 'c' / 'd', target_is_directory=True)
        (tmp_path / 'c').mkdir()
        (tmp_path / 'c' / 'd').mkdir()
        (tmp_path / 'c' / 'd' / 'b.txt').write_text('b')
        (tmp_path / 'd').symlink_to(tmp_path / 'e', target_is_directory=True)
        (tmp_path / 'e').mkdir()
        (tmp_path / 'e' / 'e.txt').write_text('e')
        (tmp_path / 'f').mkdir()
        (tmp_path / 'f' / 'f.txt').write_text('f')

        folder = LocalFolder(str(tmp_path))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'a' / 'a.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'b.txt')),
            fix_windows_path_limit(str(tmp_path / 'c' / 'd' / 'b.txt')),
            fix_windows_path_limit(str(tmp_path / 'd' / 'e.txt')),
            fix_windows_path_limit(str(tmp_path / 'e' / 'e.txt')),
            fix_windows_path_limit(str(tmp_path / 'f' / 'f.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    def test_valid_symlink_pattern_where_the_link_goes_up_and_down(self, tmp_path):
        # Create a directory structure with a valid symlink pattern where the link goes up and down
        # tmp_path
        # ├── a
        # │   └── a.txt
        # ├── b
        # │   └── c -> ../d
        # ├── d
        # │   └── e
        # │       └── f
        # │           └── f.txt
        # └── t.txt

        (tmp_path / 'a').mkdir()
        (tmp_path / 'a' / 'a.txt').write_text('a')
        (tmp_path / 'b').mkdir()
        (tmp_path / 'b' / 'c').symlink_to(tmp_path / 'd', target_is_directory=True)
        (tmp_path / 'd').mkdir()
        (tmp_path / 'd' / 'e').mkdir()
        (tmp_path / 'd' / 'e' / 'f').mkdir()
        (tmp_path / 'd' / 'e' / 'f' / 'f.txt').write_text('f')
        (tmp_path / 't.txt').write_text('t')

        folder = LocalFolder(str(tmp_path))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'a' / 'a.txt')),
            fix_windows_path_limit(str(tmp_path / 'b' / 'c' / 'e' / 'f' / 'f.txt')),
            fix_windows_path_limit(str(tmp_path / 'd' / 'e' / 'f' / 'f.txt')),
            fix_windows_path_limit(str(tmp_path / 't.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    @pytest.mark.timeout(5)
    def test_loop_that_goes_down_and_up(self, tmp_path):
        # Create a directory structure with a loop that goes down and up
        # tmp_path
        # ├── a
        # │   └── a.txt
        # ├── b -> c/d
        # ├── c
        # │   └── d -> ../e
        # ├── e -> b
        # └── f
        #     └── f.txt

        (tmp_path / 'a').mkdir()
        (tmp_path / 'a' / 'a.txt').write_text('a')
        (tmp_path / 'b').symlink_to(tmp_path / 'c' / 'd', target_is_directory=True)
        (tmp_path / 'c').mkdir()
        (tmp_path / 'c' / 'd').symlink_to(tmp_path / 'e', target_is_directory=True)
        (tmp_path / 'e').symlink_to('b')
        (tmp_path / 'f').mkdir()
        (tmp_path / 'f' / 'f.txt').write_text('f')

        folder = LocalFolder(str(tmp_path))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'a' / 'a.txt')),
            fix_windows_path_limit(str(tmp_path / 'f' / 'f.txt')),
        ]

    @pytest.mark.skipif(
        platform.system() == 'Windows' and platform.python_implementation() == 'PyPy',
        reason='Symlinks not supported on PyPy/Windows',
    )
    @pytest.mark.timeout(5)
    def test_loop_that_goes_up_and_down(self, tmp_path):
        # Create a directory structure with a loop that goes up and down
        # tmp_path
        # ├── a
        # │   └── a.txt
        # ├── b
        # │   └── c -> ../d
        # ├── d
        # │   └── e
        # │       └── f -> ../../b/c
        # └── g
        #     └── g.txt

        (tmp_path / 'a').mkdir()
        (tmp_path / 'a' / 'a.txt').write_text('a')
        (tmp_path / 'b').mkdir()
        (tmp_path / 'b' / 'c').symlink_to(tmp_path / 'd', target_is_directory=True)
        (tmp_path / 'd').mkdir()
        (tmp_path / 'd' / 'e').mkdir()
        (tmp_path / 'd' / 'e' / 'f').symlink_to(tmp_path / 'b' / 'c', target_is_directory=True)
        (tmp_path / 'g').mkdir()
        (tmp_path / 'g' / 'g.txt').write_text('g')

        folder = LocalFolder(str(tmp_path))

        local_paths = folder.all_files(reporter=MagicMock())
        absolute_paths = [path.absolute_path for path in list(local_paths)]

        assert absolute_paths == [
            fix_windows_path_limit(str(tmp_path / 'a' / 'a.txt')),
            fix_windows_path_limit(str(tmp_path / 'g' / 'g.txt')),
        ]

    def test_folder_all_files__dir_excluded_by_regex(self, tmp_path):
        """
        bar$ regex should exclude bar directory and all files inside it
        """
        d1_dir = tmp_path / 'd1'
        d1_dir.mkdir()
        (d1_dir / 'file1.txt').touch()

        bar_dir = tmp_path / 'bar'
        bar_dir.mkdir()
        (bar_dir / 'file2.txt').touch()

        scan_policy = ScanPoliciesManager(exclude_dir_regexes=['bar$'])

        folder = LocalFolder(tmp_path)
        local_paths = folder.all_files(reporter=None, policies_manager=scan_policy)
        absolute_paths = [path.absolute_path for path in local_paths]

        assert absolute_paths == [
            fix_windows_path_limit(str(d1_dir / 'file1.txt')),
        ]

    def test_excluded_no_access_check(self, tmp_path):
        """Test that a directory/file is not checked for access if it is excluded."""
        # Create directories and files
        excluded_dir = tmp_path / 'excluded_dir'
        excluded_dir.mkdir()
        excluded_file = excluded_dir / 'excluded_file.txt'
        excluded_file.touch()
        included_dir = tmp_path / 'included_dir'
        included_dir.mkdir()
        (included_dir / 'excluded_file.txt').touch()

        # Setup exclusion regex that matches the excluded directory/file name
        scan_policy = ScanPoliciesManager(
            exclude_dir_regexes=[r'excluded_dir$'], exclude_file_regexes=[r'.*excluded_file.txt']
        )
        reporter = ProgressReport(sys.stdout, False)

        # Patch os.access to monitor if it is called on the excluded file
        with patch('os.access', MagicMock(return_value=True)) as mocked_access:
            folder = LocalFolder(str(tmp_path))
            list(folder.all_files(reporter=reporter, policies_manager=scan_policy))

            # Verify os.access was not called for the excluded directory/file
            mocked_access.assert_not_called()

        reporter.close()

    @pytest.mark.skipif(
        platform.system() == 'Windows',
        reason='Unix-only filesystem permissions are tested',
    )
    def test_dir_without_exec_permission(self, tmp_path, fs_perm_tool):
        """Test that a excluded directory/file without permissions emits warnings."""
        no_perm_dir = tmp_path / 'no_perm_dir'
        no_perm_dir.mkdir()
        (no_perm_dir / 'file.txt').touch()
        (no_perm_dir / 'file2.txt').touch()
        # chmod -x no_perm_dir
        no_perm_dir.chmod(0o600)

        scan_policy = ScanPoliciesManager()
        reporter = ProgressReport(sys.stdout, False)

        folder = LocalFolder(str(tmp_path))
        local_paths = folder.all_files(reporter=reporter, policies_manager=scan_policy)
        absolute_paths = [path.absolute_path for path in local_paths]
        assert not absolute_paths

        # Check that no access warnings are issued for the excluded directory/file
        assert set(reporter.warnings) == {
            f'WARNING: {tmp_path/"no_perm_dir/file.txt"} could not be accessed (no permissions to read?)',
            f'WARNING: {tmp_path/"no_perm_dir/file2.txt"} could not be accessed (no permissions to read?)',
        }

        reporter.close()

    def test_without_permissions(self, tmp_path, fs_perm_tool):
        """Test that a excluded directory/file without permissions emits warnings."""
        no_perm_dir = tmp_path / 'no_perm_dir'
        no_perm_dir.mkdir()
        (no_perm_dir / 'file.txt').touch()

        included_dir = tmp_path / 'included_dir'
        included_dir.mkdir()
        (included_dir / 'no_perm_file.txt').touch()
        (included_dir / 'included_file.txt').touch()

        # Modify directory permissions to simulate lack of access
        fs_perm_tool.deny_access(included_dir / 'no_perm_file.txt')
        fs_perm_tool.deny_access(no_perm_dir)

        scan_policy = ScanPoliciesManager()
        reporter = ProgressReport(sys.stdout, False)

        folder = LocalFolder(str(tmp_path))
        local_paths = folder.all_files(reporter=reporter, policies_manager=scan_policy)
        absolute_paths = [pathlib.Path(path.absolute_path) for path in local_paths]

        # Check that only included_dir/included_file.txt was return
        assert {path.name for path in absolute_paths} == {'included_file.txt'}

        def s(p):
            # shlex.quote works differently depending if its on windows or unix
            return shlex.quote(str(p))

        # Check that no access warnings are issued for the excluded directory/file
        assert set(reporter.warnings) == {
            f'WARNING: {s(tmp_path / "no_perm_dir")} could not be accessed (no permissions to read?)',
            f'WARNING: {s(tmp_path / "included_dir/no_perm_file.txt")} could not be accessed (no permissions to read?)',
        }

        reporter.close()

    def test_excluded_without_permissions(self, tmp_path, fs_perm_tool):
        """Test that a excluded directory/file without permissions is not processed and no warning is issued."""
        no_perm_dir = tmp_path / 'no_perm_dir'
        no_perm_dir.mkdir()
        (no_perm_dir / 'file.txt').touch()

        included_dir = tmp_path / 'included_dir'
        included_dir.mkdir()
        (included_dir / 'no_perm_file.txt').touch()
        (included_dir / 'included_file.txt').touch()

        # Modify directory permissions to simulate lack of access
        fs_perm_tool.deny_access(included_dir / 'no_perm_file.txt')
        fs_perm_tool.deny_access(no_perm_dir)

        scan_policy = ScanPoliciesManager(
            exclude_dir_regexes=[r'no_perm_dir$'], exclude_file_regexes=[r'.*no_perm_file.txt']
        )
        reporter = ProgressReport(sys.stdout, False)

        folder = LocalFolder(str(tmp_path))
        local_paths = folder.all_files(reporter=reporter, policies_manager=scan_policy)
        absolute_paths = [path.absolute_path for path in local_paths]

        # Check that only included_dir/included_file.txt was return
        assert any('included_file.txt' in path for path in absolute_paths)

        # Check that no access warnings are issued for the excluded directory/file
        assert not reporter.warnings

        reporter.close()