Skip to content

AccessControllable

delete_permissions Flow Diagram

The following sequence diagram illustrates the complete flow and function calls of the delete_permissions method:

sequenceDiagram
    participant User as User/Client
    participant Entity as Entity (File/Folder/Project)
    participant Tracker as BenefactorTracker
    participant SynClient as Synapse Client
    participant API as Synapse API
    participant Logger as Logger

    User->>Entity: delete_permissions(params)

    Note over Entity: Parameter Validation & Setup
    Entity->>Entity: Validate entity.id exists
    Entity->>SynClient: get_client()

    alt Project Entity
        Entity->>Logger: warn("Project ACL cannot be deleted")
        Entity->>Entity: set include_self=False
    end

    Entity->>Entity: _normalize_target_entity_types()
    Entity->>Tracker: create BenefactorTracker()

    alt Recursive or Container Content Processing
        Entity->>Entity: _collect_entities()
        Note over Entity: Gather all entities to process

        Entity->>Tracker: track_entity_benefactor(entity_ids)

        loop For each entity_id
            Tracker->>API: get_entity_benefactor(entity_id)
            API-->>Tracker: benefactor_result
        end

        Note over Tracker: Build benefactor relationships
        Tracker->>Tracker: Update entity_benefactors mapping
        Tracker->>Tracker: Update benefactor_children mapping
    end

    alt Dry Run Mode
        Entity->>Entity: _build_and_log_dry_run_tree()
        Entity->>Logger: Log what would be deleted
        Entity-->>User: Return (no actual deletion)
    else Actual Deletion

        alt Include Self
            Entity->>Entity: _delete_current_entity_acl()

            Entity->>Tracker: track_entity_benefactor([self.id])
            Tracker->>API: get_entity_benefactor(self.id)
            API-->>Tracker: benefactor_result

            Entity->>Tracker: will_acl_deletion_affect_others(self.id)
            Tracker-->>Entity: boolean result

            alt Will Affect Others
                Entity->>Logger: info("Deleting ACL will affect X entities")
            end

            Entity->>API: delete_entity_acl(self.id)

            alt Success
                API-->>Entity: Success
                Entity->>Logger: debug("Deleted ACL for entity")
                Entity->>Tracker: mark_acl_deleted(self.id)
                Tracker->>Tracker: Update benefactor relationships
                Tracker-->>Entity: affected_entities list

                alt Has Affected Entities
                    Entity->>Logger: info("ACL deletion caused X entities to inherit from new benefactor")
                end
            else HTTP Error
                API-->>Entity: SynapseHTTPError
                alt Already Inherits (403)
                    Entity->>Logger: debug("Entity already inherits permissions")
                else Other Error
                    Entity->>Entity: raise exception
                end
            end
        end

        alt Process Container Contents
            Entity->>Entity: _process_container_contents()

            alt Process Files
                loop For each file
                    Entity->>Entity: file.delete_permissions_async(recursive=False)
                    Note right of Entity: Recursive call for each file
                end
            end

            alt Process Folders
                Entity->>Entity: _process_folder_permission_deletion()

                loop For each folder
                    alt Recursive Mode
                        Entity->>Entity: folder.delete_permissions_async(recursive=True)
                    else Direct Mode
                        Entity->>Entity: folder.delete_permissions_async(recursive=False)
                    end
                    Note right of Entity: Recursive calls for folders
                end
            end
        end
    end

    Entity-->>User: Complete

    Note over User,Logger: Key Features:
    Note over User,Logger: • Async operations with asyncio.gather()
    Note over User,Logger: • Benefactor relationship tracking
    Note over User,Logger: • Recursive processing capabilities
    Note over User,Logger: • Dry run mode for preview
    Note over User,Logger: • Error handling for inheritance conflicts
    Note over User,Logger: • Cascading permission updates

Key Components:

  • Entity: The primary object (File, Folder, Project) whose permissions are being deleted
  • BenefactorTracker: Manages benefactor relationships and tracks cascading changes
  • Synapse Client: Handles API communication and logging
  • Synapse API: REST endpoints for ACL operations (delete_entity_acl, get_entity_benefactor)
  • Logger: Records operations, warnings, and debug information

Flow Highlights:

  1. Validation Phase: Parameter validation and client setup
  2. Collection Phase: Gathering entities for recursive operations
  3. Tracking Phase: Parallel benefactor relationship discovery
  4. Preview Phase: Dry run mode shows what would be deleted
  5. Deletion Phase: Actual ACL deletions with error handling
  6. Cascading Phase: Updates benefactor relationships for affected entities

synapseclient.models.mixins.AccessControllable

Bases: AccessControllableSynchronousProtocol

Mixin for objects that can be controlled by an Access Control List (ACL).

In order to use this mixin, the class must have an id attribute.

Source code in synapseclient/models/mixins/access_control.py
 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
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
@async_to_sync
class AccessControllable(AccessControllableSynchronousProtocol):
    """
    Mixin for objects that can be controlled by an Access Control List (ACL).

    In order to use this mixin, the class must have an `id` attribute.
    """

    id: Optional[str] = None
    """The unique immutable ID for this entity. A new ID will be generated for new Files.
    Once issued, this ID is guaranteed to never change or be re-issued."""

    files: List["File"] = None
    folders: List["Folder"] = None
    tables: List["Table"] = None
    # links: List["Link"] = None
    entityviews: List["EntityView"] = None
    # dockerrepos: List["DockerRepo"] = None
    submissionviews: List["SubmissionView"] = None
    datasets: List["Dataset"] = None
    datasetcollections: List["DatasetCollection"] = None
    materializedviews: List["MaterializedView"] = None
    virtualtables: List["VirtualTable"] = None

    async def get_permissions_async(
        self,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "Permissions":
        """
        Get the [permissions][synapseclient.core.models.permission.Permissions]
        that the caller has on an Entity.

        Arguments:
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            A Permissions object


        Example: Using this function:
            Getting permissions for a Synapse Entity

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            async def main():
                permissions = await File(id="syn123").get_permissions_async()

            asyncio.run(main())
            ```

            Getting access types list from the Permissions object

            ```
            permissions.access_types
            ```
        """
        from synapseclient.core.models.permission import Permissions

        permissions_dict = await get_entity_permissions(
            entity_id=self.id,
            synapse_client=synapse_client,
        )
        return Permissions.from_dict(data=permissions_dict)

    async def get_acl_async(
        self,
        principal_id: int = None,
        check_benefactor: bool = True,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> List[str]:
        """
        Get the [ACL][synapseclient.core.models.permission.Permissions.access_types]
        that a user or group has on an Entity.

        Note: If the entity does not have local sharing settings, or ACL set directly
        on it, this will look up the ACL on the benefactor of the entity. The
        benefactor is the entity that the current entity inherits its permissions from.
        The benefactor is usually the parent entity, but it can be any ancestor in the
        hierarchy. For example, a newly created Project will be its own benefactor,
        while a new FileEntity's benefactor will start off as its containing Project or
        Folder. If the entity already has local sharing settings, the benefactor would
        be itself.

        Arguments:
            principal_id: Identifier of a user or group (defaults to PUBLIC users)
            check_benefactor: If True (default), check the benefactor for the entity
                to get the ACL. If False, only check the entity itself.
                This is useful for checking the ACL of an entity that has local sharing
                settings, but you want to check the ACL of the entity itself and not
                the benefactor it may inherit from.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            An array containing some combination of
                ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
                'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
                or an empty array
        """
        return await get_entity_acl_list(
            entity_id=self.id,
            principal_id=str(principal_id) if principal_id is not None else None,
            check_benefactor=check_benefactor,
            synapse_client=synapse_client,
        )

    async def set_permissions_async(
        self,
        principal_id: int = None,
        access_type: List[str] = None,
        modify_benefactor: bool = False,
        warn_if_inherits: bool = True,
        overwrite: bool = True,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> Dict[str, Union[str, list]]:
        """
        Sets permission that a user or group has on an Entity.
        An Entity may have its own ACL or inherit its ACL from a benefactor.

        Arguments:
            principal_id: Identifier of a user or group. `273948` is for all
                registered Synapse users and `273949` is for public access.
                None implies public access.
            access_type: Type of permission to be granted. One or more of CREATE,
                READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS.

                **Defaults to ['READ', 'DOWNLOAD']**
            modify_benefactor: Set as True when modifying a benefactor's ACL. The term
                'benefactor' is used to indicate which Entity an Entity inherits its
                ACL from. For example, a newly created Project will be its own
                benefactor, while a new FileEntity's benefactor will start off as its
                containing Project. If the entity already has local sharing settings
                the benefactor would be itself. It may also be the immediate parent,
                somewhere in the parent tree, or the project itself.
            warn_if_inherits: When `modify_benefactor` is True, this does not have any
                effect. When `modify_benefactor` is False, and `warn_if_inherits` is
                True, a warning log message is produced if the benefactor for the
                entity you passed into the function is not itself, i.e., it's the
                parent folder, or another entity in the parent tree.
            overwrite: By default this function overwrites existing permissions for
                the specified user. Set this flag to False to add new permissions
                non-destructively.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            An Access Control List object matching <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/AccessControlList.html>.

        Example: Setting permissions
            Grant all registered users download access

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            async def main():
                await File(id="syn123").set_permissions_async(principal_id=273948, access_type=['READ','DOWNLOAD'])

            asyncio.run(main())
            ```

            Grant the public view access

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            async def main():
                await File(id="syn123").set_permissions_async(principal_id=273949, access_type=['READ'])

            asyncio.run(main())
            ```
        """
        if access_type is None:
            access_type = ["READ", "DOWNLOAD"]

        return await set_entity_permissions(
            entity_id=self.id,
            principal_id=str(principal_id) if principal_id is not None else None,
            access_type=access_type,
            modify_benefactor=modify_benefactor,
            warn_if_inherits=warn_if_inherits,
            overwrite=overwrite,
            synapse_client=synapse_client,
        )

    async def delete_permissions_async(
        self,
        include_self: bool = True,
        include_container_content: bool = False,
        recursive: bool = False,
        target_entity_types: Optional[List[str]] = None,
        dry_run: bool = False,
        show_acl_details: bool = True,
        show_files_in_containers: bool = True,
        *,
        synapse_client: Optional[Synapse] = None,
        _benefactor_tracker: Optional[BenefactorTracker] = None,
    ) -> None:
        """
        Delete the entire Access Control List (ACL) for a given Entity. This is not
        scoped to a specific user or group, but rather removes all permissions
        associated with the Entity. After this operation, the Entity will inherit
        permissions from its benefactor, which is typically its parent entity or
        the Project it belongs to.

        In order to remove permissions for a specific user or group, you
        should use the `set_permissions_async` method with the `access_type` set to
        an empty list.

        By default, Entities such as FileEntity and Folder inherit their permission from
        their containing Project. For such Entities the Project is the Entity's 'benefactor'.
        This permission inheritance can be overridden by creating an ACL for the Entity.
        When this occurs the Entity becomes its own benefactor and all permission are
        determined by its own ACL.

        If the ACL of an Entity is deleted, then its benefactor will automatically be set
        to its parent's benefactor.

        **Special notice for Projects:** The ACL for a Project cannot be deleted, you
        must individually update or revoke the permissions for each user or group.

        Arguments:
            include_self: If True (default), delete the ACL of the current entity.
                If False, skip deleting the ACL of the current entity.
            include_container_content: If True, delete ACLs from contents directly within
                containers (files and folders inside self). This must be set to
                True for recursive to have any effect. Defaults to False.
            recursive: If True and the entity is a container (e.g., Project or Folder),
                recursively process child containers. Note that this must be used with
                include_container_content=True to have any effect. Setting recursive=True
                with include_container_content=False will raise a ValueError.
                Only works on classes that support the `sync_from_synapse_async` method.
            target_entity_types: Specify which entity types to process when deleting ACLs.
                Allowed values are "folder", "file", "project", "table", "entityview",
                "materializedview", "virtualtable", "dataset", "datasetcollection",
                "submissionview" (case-insensitive). If None, defaults to ["folder", "file"].
                This does not affect the entity type of the current entity, which is always
                processed if `include_self=True`.
            dry_run: If True, log the changes that would be made instead of actually
                performing the deletions. When enabled, all ACL deletion operations are
                simulated and logged at info level. Defaults to False.
            show_acl_details: When dry_run=True, controls whether current ACL details are
                displayed for entities that will have their permissions changed. If True (default),
                shows detailed ACL information. If False, hides ACL details for cleaner output.
                Has no effect when dry_run=False.
            show_files_in_containers: When dry_run=True, controls whether files within containers
                are displayed in the preview. If True (default), shows all files. If False, hides
                files when their only change is benefactor inheritance (but still shows files with
                local ACLs being deleted). Has no effect when dry_run=False.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.
            _benefactor_tracker: Internal use tracker for managing benefactor relationships.
                Used for recursive functionality to track which entities will be affected

        Returns:
            None

        Raises:
            ValueError: If the entity does not have an ID or if an invalid entity type is provided.
            SynapseHTTPError: If there are permission issues or if the entity already inherits permissions.
            Exception: For any other errors that may occur during the process.

        Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to
        call this method.

        Example: Delete permissions for a single entity
            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            async def main():
                await File(id="syn123").delete_permissions_async()

            asyncio.run(main())
            ```

        Example: Delete permissions recursively for a folder and all its children
            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import Folder

            syn = Synapse()
            syn.login()

            async def main():
                # Delete permissions for this folder only (does not affect children)
                await Folder(id="syn123").delete_permissions_async()

                # Delete permissions for all files and folders directly within this folder,
                # but not the folder itself
                await Folder(id="syn123").delete_permissions_async(
                    include_self=False,
                    include_container_content=True
                )

                # Delete permissions for all items in the entire hierarchy (folders and their files)
                # Both recursive and include_container_content must be True
                await Folder(id="syn123").delete_permissions_async(
                    recursive=True,
                    include_container_content=True
                )

                # Delete permissions only for folder entities within this folder recursively
                # and their contents
                await Folder(id="syn123").delete_permissions_async(
                    recursive=True,
                    include_container_content=True,
                    target_entity_types=["folder"]
                )

                # Delete permissions only for files within this folder and all subfolders
                await Folder(id="syn123").delete_permissions_async(
                    include_self=False,
                    recursive=True,
                    include_container_content=True,
                    target_entity_types=["file"]
                )

                # Delete permissions for specific entity types (e.g., tables and views)
                await Folder(id="syn123").delete_permissions_async(
                    recursive=True,
                    include_container_content=True,
                    target_entity_types=["table", "entityview", "materializedview"]
                )

                # Dry run example: Log what would be deleted without making changes
                await Folder(id="syn123").delete_permissions_async(
                    recursive=True,
                    include_container_content=True,
                    dry_run=True
                )
            asyncio.run(main())
            ```
        """
        if not self.id:
            raise ValueError("The entity must have an ID to delete permissions.")

        client = Synapse.get_client(synapse_client=synapse_client)

        if include_self and self.__class__.__name__.lower() == "project":
            client.logger.warning(
                "The ACL for a Project cannot be deleted, you must individually update or "
                "revoke the permissions for each user or group. Continuing without deleting "
                "the Project's ACL."
            )
            include_self = False

        normalized_types = self._normalize_target_entity_types(target_entity_types)

        is_top_level = not _benefactor_tracker
        benefactor_tracker = _benefactor_tracker or BenefactorTracker()

        should_process_children = (recursive or include_container_content) and hasattr(
            self, "sync_from_synapse_async"
        )
        all_entities = [self] if include_self else []

        custom_message = "Deleting ACLs [Dry Run]..." if dry_run else "Deleting ACLs..."
        with shared_download_progress_bar(
            file_size=1, synapse_client=client, custom_message=custom_message, unit=None
        ) as progress_bar:
            if progress_bar:
                progress_bar.update(1)  # Initial setup complete

            if should_process_children:
                if recursive and not include_container_content:
                    raise ValueError(
                        "When recursive=True, include_container_content must also be True. "
                        "Setting recursive=True with include_container_content=False has no effect."
                    )

                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()

                all_entities = await self._collect_entities(
                    client=client,
                    target_entity_types=normalized_types,
                    include_container_content=include_container_content,
                    recursive=recursive,
                    progress_bar=progress_bar,
                )
                if progress_bar:
                    progress_bar.update(1)

                entity_ids = [entity.id for entity in all_entities if entity.id]
                if entity_ids:
                    if progress_bar:
                        progress_bar.total += 1
                        progress_bar.refresh()
                    await benefactor_tracker.track_entity_benefactor(
                        entity_ids=entity_ids,
                        synapse_client=client,
                        progress_bar=progress_bar,
                    )
                else:
                    if progress_bar:
                        progress_bar.total += 1
                        progress_bar.refresh()
                        progress_bar.update(1)

            if is_top_level:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()
                await self._build_and_log_run_tree(
                    client=client,
                    benefactor_tracker=benefactor_tracker,
                    collected_entities=all_entities,
                    include_self=include_self,
                    show_acl_details=show_acl_details,
                    show_files_in_containers=show_files_in_containers,
                    progress_bar=progress_bar,
                    dry_run=dry_run,
                )

            if dry_run:
                return

            if include_self:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()
                await self._delete_current_entity_acl(
                    client=client,
                    benefactor_tracker=benefactor_tracker,
                    progress_bar=progress_bar,
                )

            if should_process_children:
                if include_container_content:
                    if progress_bar:
                        progress_bar.total += 1
                        progress_bar.refresh()
                    await self._process_container_contents(
                        client=client,
                        target_entity_types=normalized_types,
                        benefactor_tracker=benefactor_tracker,
                        progress_bar=progress_bar,
                        recursive=recursive,
                        include_container_content=include_container_content,
                    )
                    if progress_bar:
                        progress_bar.update(1)  # Process container contents complete

    def _normalize_target_entity_types(
        self, target_entity_types: Optional[List[str]]
    ) -> List[str]:
        """
        Normalize and validate the target entity types.

        Arguments:
            target_entity_types: A list of entity types to validate. If None, returns default types.

        Returns:
            List[str]: A normalized list (lowercase) of valid entity types.
        """
        default_types = ["folder", "file"]

        if target_entity_types is None:
            return default_types

        normalized_types = [t.lower() for t in target_entity_types]

        return normalized_types

    async def _delete_current_entity_acl(
        self,
        client: Synapse,
        benefactor_tracker: BenefactorTracker,
        progress_bar: Optional[tqdm] = None,
    ) -> None:
        """
        Delete the ACL for the current entity with benefactor relationship tracking.

        Arguments:
            client: The Synapse client instance to use for API calls.
            benefactor_tracker: Tracker for managing benefactor relationships.
            progress_bar: Progress bar to update after operation.

        Returns:
            None
        """

        await benefactor_tracker.track_entity_benefactor(
            entity_ids=[self.id], synapse_client=client, progress_bar=progress_bar
        )

        try:
            await delete_entity_acl(entity_id=self.id, synapse_client=client)
            client.logger.debug(f"Deleted ACL for entity {self.id}")

            if benefactor_tracker:
                affected_entities = benefactor_tracker.mark_acl_deleted(self.id)
                if affected_entities:
                    client.logger.info(
                        f"ACL deletion for entity {self.id} caused {len(affected_entities)} "
                        f"entities to inherit from a new benefactor: {affected_entities}"
                    )

            if progress_bar:
                progress_bar.update(1)

        except SynapseHTTPError as e:
            if (
                e.response.status_code == 403
                and "Resource already inherits its permissions." in e.response.text
            ):
                client.logger.debug(
                    f"Entity {self.id} already inherits permissions from its parent."
                )
                if progress_bar:
                    progress_bar.update(1)
            else:
                raise

    async def _process_container_contents(
        self,
        client: Synapse,
        target_entity_types: List[str],
        benefactor_tracker: BenefactorTracker,
        progress_bar: Optional[tqdm] = None,
        recursive: bool = False,
        include_container_content: bool = True,
    ) -> None:
        """
        Process the contents of a container entity, optionally recursively.

        Arguments:
            client: The Synapse client instance to use for API calls.
            target_entity_types: A list of normalized entity types to process.
            benefactor_tracker: Tracker for managing benefactor relationships.
            progress_bar: Optional progress bar to update as tasks complete.
            recursive: If True, process folders recursively; if False, process only direct contents.
            include_container_content: Whether to include the content of containers in processing.

        Returns:
            None
        """
        for entity_type, plural_attr in ENTITY_TYPE_MAPPING.items():
            if entity_type in target_entity_types and hasattr(self, plural_attr):
                entities = getattr(self, plural_attr, [])

                if benefactor_tracker and entities:
                    track_tasks = [
                        benefactor_tracker.track_entity_benefactor(
                            entity_ids=[entity.id],
                            synapse_client=client,
                            progress_bar=progress_bar,
                        )
                        for entity in entities
                    ]

                    if progress_bar and track_tasks:
                        progress_bar.total += len(track_tasks)
                        progress_bar.refresh()

                    for completed_task in asyncio.as_completed(track_tasks):
                        await completed_task
                        if progress_bar:
                            progress_bar.update(1)

                async def process_single_entity(entity, target_type):
                    await entity.delete_permissions_async(
                        recursive=False,
                        include_self=True,
                        target_entity_types=[target_type],
                        dry_run=False,
                        _benefactor_tracker=benefactor_tracker,
                        synapse_client=client,
                    )

                entity_tasks = [
                    process_single_entity(entity, entity_type) for entity in entities
                ]

                if progress_bar and entity_tasks:
                    progress_bar.total += len(entity_tasks)
                    progress_bar.refresh()

                for completed_task in asyncio.as_completed(entity_tasks):
                    await completed_task
                    if progress_bar:
                        progress_bar.update(1)

        if hasattr(self, "folders"):
            await self._process_folder_permission_deletion(
                client=client,
                recursive=recursive,
                benefactor_tracker=benefactor_tracker,
                progress_bar=progress_bar,
                target_entity_types=target_entity_types,
                include_container_content=include_container_content,
            )

    async def _process_folder_permission_deletion(
        self,
        client: Synapse,
        recursive: bool,
        benefactor_tracker: BenefactorTracker,
        target_entity_types: List[str],
        progress_bar: Optional[tqdm] = None,
        include_container_content: bool = False,
    ) -> None:
        """
        Process folder permission deletion either directly or recursively.

        Arguments:
            client: The Synapse client instance to use for API calls.
            recursive: If True, process folders recursively; if False, process only direct folders.
            benefactor_tracker: Tracker for managing benefactor relationships.
                Only used for non-recursive processing.
            target_entity_types: A list of normalized entity types to process.
            progress_bar: Optional progress bar to update as tasks complete.
            include_container_content: Whether to include the content of containers in processing.
                Only used for recursive processing.

        Returns:
            None

        Raises:
            Exception: For any errors that may occur during processing, which are caught and logged.
        """
        if not recursive and benefactor_tracker:
            track_tasks = [
                benefactor_tracker.track_entity_benefactor(
                    entity_ids=[folder.id],
                    synapse_client=client,
                    progress_bar=progress_bar,
                )
                for folder in self.folders
            ]

            if progress_bar and track_tasks:
                progress_bar.total += len(track_tasks)
                progress_bar.refresh()

            for completed_task in asyncio.as_completed(track_tasks):
                await completed_task
                if progress_bar:
                    progress_bar.update(1)  # Each tracking task complete

        async def process_single_folder(folder):
            should_delete_folder_acl = (
                "folder" in target_entity_types and include_container_content
            )

            await folder.delete_permissions_async(
                include_self=should_delete_folder_acl,
                recursive=recursive,
                # This is needed to ensure we do not delete children ACLs when not
                # recursive, but still allow us to delete the ACL on the folder
                include_container_content=include_container_content and recursive,
                target_entity_types=target_entity_types,
                dry_run=False,
                _benefactor_tracker=benefactor_tracker,
                synapse_client=client,
            )

        folder_tasks = [process_single_folder(folder) for folder in self.folders]

        if progress_bar and folder_tasks:
            progress_bar.total += len(folder_tasks)
            progress_bar.refresh()

        for completed_task in asyncio.as_completed(folder_tasks):
            await completed_task
            if progress_bar:
                progress_bar.update(1)  # Each folder task complete

    async def list_acl_async(
        self,
        recursive: bool = False,
        include_container_content: bool = False,
        target_entity_types: Optional[List[str]] = None,
        log_tree: bool = False,
        *,
        synapse_client: Optional[Synapse] = None,
        _progress_bar: Optional[tqdm] = None,  # Internal parameter for recursive calls
    ) -> AclListResult:
        """
        List the Access Control Lists (ACLs) for this entity and optionally its children.

        This function returns the local sharing settings for the entity and optionally
        its children. It provides a mapping of all ACLs for the given container/entity.

        **Important Note:** This function returns the LOCAL sharing settings only, not
        the effective permissions that each Synapse User ID/Team has on the entities.
        More permissive permissions could be granted via a Team that the user has access
        to that has permissions on the entity, or through inheritance from parent entities.

        Arguments:
            recursive: If True and the entity is a container (e.g., Project or Folder),
                recursively process child containers. Note that this must be used with
                include_container_content=True to have any effect. Setting recursive=True
                with include_container_content=False will raise a ValueError.
                Only works on classes that support the `sync_from_synapse_async` method.
            include_container_content: If True, include ACLs from contents directly within
                containers (files and folders inside self). This must be set to
                True for recursive to have any effect. Defaults to False.
            target_entity_types: Specify which entity types to process when listing ACLs.
                Allowed values are "folder", "file", "project", "table", "entityview",
                "materializedview", "virtualtable", "dataset", "datasetcollection",
                "submissionview" (case-insensitive). If None, defaults to ["folder", "file"].
            log_tree: If True, logs the ACL results to console in ASCII tree format showing
                entity hierarchies and their ACL permissions in a tree-like structure.
                Defaults to False.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.
            _progress_bar: Internal parameter. Progress bar instance to use for updates
                when called recursively. Should not be used by external callers.

        Returns:
            An AclListResult object containing a structured representation of ACLs where:
            - entity_acls: A list of EntityAcl objects, each representing one entity's ACL
            - Each EntityAcl contains acl_entries (a list of AclEntry objects)
            - Each AclEntry contains the principal_id and their list of permissions

        Raises:
            ValueError: If the entity does not have an ID or if an invalid entity type is provided.
            SynapseHTTPError: If there are permission issues accessing ACLs.
            Exception: For any other errors that may occur during the process.

        Example: List ACLs for a single entity
            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            async def main():
                acl_result = await File(id="syn123").list_acl_async()
                print(acl_result)

                # Access entity ACLs (entity_acls is a list, not a dict)
                for entity_acl in acl_result.all_entity_acls:
                    if entity_acl.entity_id == "syn123":
                        # Access individual ACL entries
                        for acl_entry in entity_acl.acl_entries:
                            if acl_entry.principal_id == "273948":
                                print(f"Principal 273948 has permissions: {acl_entry.permissions}")

                # I can also access the ACL for the file itself
                print(acl_result.entity_acl)

                print(acl_result)

            asyncio.run(main())
            ```

        Example: List ACLs recursively for a folder and all its children
            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import Folder

            syn = Synapse()
            syn.login()

            async def main():
                acl_result = await Folder(id="syn123").list_acl_async(
                    recursive=True,
                    include_container_content=True
                )

                # Access each entity's ACL (entity_acls is a list)
                for entity_acl in acl_result.all_entity_acls:
                    print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")

                # I can also access the ACL for the folder itself
                print(acl_result.entity_acl)

                # List ACLs for only folder entities
                folder_acl_result = await Folder(id="syn123").list_acl_async(
                    recursive=True,
                    include_container_content=True,
                    target_entity_types=["folder"]
                )

                # List ACLs for specific entity types (e.g., tables and views)
                table_view_acl_result = await Folder(id="syn123").list_acl_async(
                    recursive=True,
                    include_container_content=True,
                    target_entity_types=["table", "entityview", "materializedview"]
                )

            asyncio.run(main())
            ```

        Example: List ACLs with ASCII tree visualization
            When `log_tree=True`, the ACLs will be logged in a tree format. Additionally,
            the `ascii_tree` attribute of the AclListResult will contain the ASCII tree
            representation of the ACLs.

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import Folder

            syn = Synapse()
            syn.login()

            async def main():
                acl_result = await Folder(id="syn123").list_acl_async(
                    recursive=True,
                    include_container_content=True,
                    log_tree=True, # Enable ASCII tree logging
                )

                # The ASCII tree representation of the ACLs will also be available
                # in acl_result.ascii_tree
                print(acl_result.ascii_tree)

            asyncio.run(main())
            ```
        """
        if not self.id:
            raise ValueError("The entity must have an ID to list ACLs.")

        normalized_types = self._normalize_target_entity_types(target_entity_types)
        client = Synapse.get_client(synapse_client=synapse_client)

        all_acls: Dict[str, Dict[str, List[str]]] = {}
        all_entities = []

        # Only update progress bar for self ACL if we're the top-level call (not recursive)
        # When _progress_bar is passed, it means this is a recursive call and the parent
        # is managing progress updates
        update_progress_for_self = _progress_bar is None
        acl = await self._get_current_entity_acl(
            client=client,
            progress_bar=_progress_bar if update_progress_for_self else None,
        )
        if acl is not None:
            all_acls[self.id] = acl
        all_entities.append(self)

        should_process_children = (recursive or include_container_content) and hasattr(
            self, "sync_from_synapse_async"
        )

        if should_process_children and (recursive and not include_container_content):
            raise ValueError(
                "When recursive=True, include_container_content must also be True. "
                "Setting recursive=True with include_container_content=False has no effect."
            )

        if should_process_children and _progress_bar is None:
            with shared_download_progress_bar(
                file_size=1,
                synapse_client=client,
                custom_message="Collecting ACLs...",
                unit=None,
            ) as progress_bar:
                await self._process_children_with_progress(
                    client=client,
                    normalized_types=normalized_types,
                    include_container_content=include_container_content,
                    recursive=recursive,
                    all_entities=all_entities,
                    all_acls=all_acls,
                    progress_bar=progress_bar,
                )
                # Ensure progress bar reaches 100% completion
                if progress_bar:
                    remaining = (
                        progress_bar.total - progress_bar.n
                        if progress_bar.total > progress_bar.n
                        else 0
                    )
                    if remaining > 0:
                        progress_bar.update(remaining)
        elif should_process_children:
            await self._process_children_with_progress(
                client=client,
                normalized_types=normalized_types,
                include_container_content=include_container_content,
                recursive=recursive,
                all_entities=all_entities,
                all_acls=all_acls,
                progress_bar=_progress_bar,
            )
        current_acl = all_acls.get(self.id)
        acl_result = AclListResult.from_dict(
            all_acl_dict=all_acls, current_acl_dict=current_acl
        )

        if log_tree:
            logged_tree = await self._log_acl_tree(acl_result, all_entities, client)
            acl_result.ascii_tree = logged_tree

        return acl_result

    async def _get_current_entity_acl(
        self, client: Synapse, progress_bar: Optional[tqdm] = None
    ) -> Optional[Dict[str, List[str]]]:
        """
        Get the ACL for the current entity.

        Arguments:
            client: The Synapse client instance to use for API calls.
            progress_bar: Progress bar to update after operation.

        Returns:
            A dictionary mapping principal IDs to permission lists, or None if no ACL exists.
        """
        try:
            acl_response = await get_entity_acl(
                entity_id=self.id, synapse_client=client
            )
            result = self._parse_acl_response(acl_response)
            if progress_bar:
                progress_bar.update(1)
            return result
        except SynapseHTTPError as e:
            if e.response.status_code == 404:
                client.logger.debug(
                    f"Entity {self.id} inherits permissions from its parent (no local ACL)."
                )
                if progress_bar:
                    progress_bar.update(1)
                return None
            else:
                raise

    def _parse_acl_response(self, acl_response: Dict[str, Any]) -> Dict[str, List[str]]:
        """
        Parse the ACL response from the API into the expected format.

        Arguments:
            acl_response: The raw ACL response from the API.

        Returns:
            A dictionary mapping principal IDs to permission lists.
        """
        parsed_acl = {}

        if "resourceAccess" in acl_response:
            for resource_access in acl_response["resourceAccess"]:
                principal_id = str(resource_access.get("principalId", ""))
                access_types = resource_access.get("accessType", [])
                if principal_id and access_types:
                    parsed_acl[principal_id] = access_types

        return parsed_acl

    async def _collect_entities(
        self,
        client: Synapse,
        target_entity_types: List[str],
        progress_bar: Optional[tqdm] = None,
        include_container_content: bool = False,
        recursive: bool = False,
        collect_acls: bool = False,
        collect_self: bool = False,
        all_acls: Optional[Dict[str, Dict[str, List[str]]]] = None,
    ) -> List[
        Union[
            "File",
            "Folder",
            "EntityView",
            "Table",
            "MaterializedView",
            "VirtualTable",
            "Dataset",
            "DatasetCollection",
            "SubmissionView",
        ]
    ]:
        """
        Unified method to collect entities, their ACLs, or both based on parameters.

        This method replaces multiple specialized collection methods with a single,
        configurable approach that can:
        1. Collect entity objects
        2. Collect ACLs from entities (collect_acls=True)
        3. Handle both direct container contents and recursive collection
        4. Filter by entity types

        Arguments:
            client: The Synapse client instance to use for API calls.
            target_entity_types: A list of normalized entity types to process.
            progress_bar: Progress bar instance to update as tasks complete.
            include_container_content: Whether to include the content of containers.
            recursive: Whether to process recursively.
            collect_acls: Whether to collect ACLs from entities.
            collect_self: If True, include the current entity in the results.
            all_acls: Dictionary to accumulate ACL results if collecting ACLs.

        Returns:
            Returns a list of entity objects
        """
        entities = []

        if collect_self:
            entities.append(self)

            if collect_acls and all_acls is not None:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()

                entity_acls = await self.list_acl_async(
                    recursive=False,
                    include_container_content=False,
                    target_entity_types=target_entity_types,
                    synapse_client=client,
                    _progress_bar=progress_bar,
                )
                all_acls.update(entity_acls.to_dict())

                if progress_bar:
                    progress_bar.update(1)

        should_process_children = (recursive or include_container_content) and hasattr(
            self, "sync_from_synapse_async"
        )
        if should_process_children:
            if not self._synced_from_synapse:
                await self.sync_from_synapse_async(
                    recursive=False,
                    download_file=False,
                    include_activity=False,
                    synapse_client=client,
                )

            if include_container_content:
                for entity_type, plural_attr in ENTITY_TYPE_MAPPING.items():
                    if entity_type in target_entity_types and hasattr(
                        self, plural_attr
                    ):
                        entities_list = getattr(self, plural_attr, [])

                        if collect_acls and all_acls is not None and progress_bar:
                            progress_bar.total += len(entities_list)
                            progress_bar.refresh()

                        if collect_acls and all_acls is not None:
                            entity_acl_tasks = []
                            for entity in entities_list:
                                entities.append(entity)
                                entity_acl_tasks.append(
                                    entity.list_acl_async(
                                        recursive=False,
                                        include_container_content=False,
                                        target_entity_types=[entity_type],
                                        synapse_client=client,
                                        _progress_bar=progress_bar,
                                    )
                                )

                            for completed_task in asyncio.as_completed(
                                entity_acl_tasks
                            ):
                                entity_acls = await completed_task
                                all_acls.update(entity_acls.to_dict())
                                if progress_bar:
                                    progress_bar.update(1)
                        else:
                            for entity in entities_list:
                                entities.append(entity)

            if recursive and hasattr(self, "folders"):
                collect_tasks = []
                for folder in self.folders:
                    collect_tasks.append(
                        folder._collect_entities(
                            client=client,
                            target_entity_types=target_entity_types,
                            include_container_content=include_container_content,
                            recursive=recursive,
                            collect_acls=collect_acls,
                            collect_self=False,
                            all_acls=all_acls,
                            progress_bar=progress_bar,
                        )
                    )

                for completed_task in asyncio.as_completed(collect_tasks):
                    result = await completed_task
                    if result is not None:
                        entities.extend(result)

        return entities

    async def _build_and_log_run_tree(
        self,
        client: Synapse,
        benefactor_tracker: BenefactorTracker,
        progress_bar: Optional[tqdm] = None,
        collected_entities: List["AccessControllable"] = None,
        include_self: bool = True,
        show_acl_details: bool = True,
        show_files_in_containers: bool = True,
        dry_run: bool = True,
    ) -> None:
        """
        Build and log comprehensive tree showing ACL deletion impacts.

        Creates a detailed visualization of which entities will have ACLs deleted,
        how inheritance will change, and which permissions will be affected.
        The tree uses visual indicators to show current vs future state.

        Arguments:
            client: The Synapse client instance to use for API calls.
            benefactor_tracker: Tracker containing all entity relationships.
            progress_bar: Optional progress bar to update during dry run analysis.
            collected_entities: List of entity objects that have been collected.
            include_self: Whether to include self in the deletion analysis.
            show_acl_details: Whether to display current ACL details for entities that will change.
            show_files_in_containers: Whether to show files within containers.
        """
        tree_data = await self._build_tree_data(
            client=client, collected_entities=collected_entities
        )
        if not tree_data["entities_by_id"]:
            client.logger.info(
                "[DRY RUN] No entities available for deletion impact analysis."
            )
            return

        tree_output = await self._format_dry_run_tree_async(
            tree_data["tree_structure"],
            benefactor_tracker,
            include_self,
            tree_data["entities_by_id"],
            show_acl_details=show_acl_details,
            show_files_in_containers=show_files_in_containers,
            synapse_client=client,
        )

        if dry_run:
            client.logger.info("=== DRY RUN: Permission Deletion Impact Analysis ===")
        else:
            client.logger.info("=== Permission Deletion Impact Analysis ===")
        client.logger.info(tree_output)

        if dry_run:
            client.logger.info("=== End of Dry Run Analysis ===")
        else:
            client.logger.info("=== End of Permission Deletion Analysis ===")

        if progress_bar:
            remaining = (
                progress_bar.total - progress_bar.n
                if progress_bar.total > progress_bar.n
                else 0
            )
            if remaining > 0:
                progress_bar.update(remaining)
            else:
                progress_bar.update(1)

    async def _build_tree_data(
        self,
        client: Synapse,
        collected_entities: List["AccessControllable"] = None,
    ) -> Dict[str, Any]:
        """
        Build comprehensive tree data including entities and ACL structure.

        Consolidates entity preparation, ACL fetching, and tree structure building
        into a single operation that can be reused by different tree formatting functions.

        Arguments:
            client: The Synapse client instance to use for API calls.
            collected_entities: List of entity objects that have been collected.
            benefactor_tracker: Optional tracker for managing benefactor relationships.

        Returns:
            Dictionary containing entities_by_id, acl_result, and tree_structure.
        """
        entities_by_id = self._prepare_entities_for_tree(
            collected_entities=collected_entities
        )
        acl_result = await self._build_acl_result_from_entities(
            entities_by_id=entities_by_id, client=client
        )
        tree_structure = await self._build_acl_tree_structure(
            acl_result, list(entities_by_id.values())
        )

        return {
            "entities_by_id": entities_by_id,
            "acl_result": acl_result,
            "tree_structure": tree_structure,
        }

    def _prepare_entities_for_tree(
        self,
        collected_entities: List[
            Union[
                "File",
                "Folder",
                "EntityView",
                "Table",
                "MaterializedView",
                "VirtualTable",
                "Dataset",
                "DatasetCollection",
                "SubmissionView",
            ]
        ] = None,
    ) -> Dict[
        str,
        Union[
            "File",
            "Folder",
            "EntityView",
            "Table",
            "MaterializedView",
            "VirtualTable",
            "Dataset",
            "DatasetCollection",
            "SubmissionView",
        ],
    ]:
        """
        Prepare entity dictionary for tree building operations.

        Arguments:
            collected_entities: List of entity objects that have been collected.

        Returns:
            Dictionary mapping entity IDs to entity objects.
        """
        if collected_entities:
            entities_by_id = {
                entity.id: entity
                for entity in collected_entities
                if hasattr(entity, "id") and entity.id
            }
            if hasattr(self, "id") and self.id and self.id not in entities_by_id:
                entities_by_id[self.id] = self
        else:
            entities_by_id = {}
            if hasattr(self, "id") and self.id:
                entities_by_id[self.id] = self

        return entities_by_id

    async def _build_acl_result_from_entities(
        self,
        entities_by_id: Dict[
            str,
            Union[
                "File",
                "Folder",
                "EntityView",
                "Table",
                "MaterializedView",
                "VirtualTable",
                "Dataset",
                "DatasetCollection",
                "SubmissionView",
            ],
        ],
        client: Synapse,
    ) -> AclListResult:
        """
        Build AclListResult from a dictionary of entities by fetching their ACL information.

        Arguments:
            entities_by_id: Dictionary mapping entity IDs to entity objects.
            client: The Synapse client instance to use for API calls.

        Returns:
            AclListResult containing ACL information for all entities.
        """
        from synapseclient.core.models.acl import AclEntry, EntityAcl

        async def fetch_entity_acl(entity_id: str) -> Optional[EntityAcl]:
            """Helper function to fetch ACL for a single entity."""
            try:
                acl_response = await get_entity_acl(
                    entity_id=entity_id, synapse_client=client
                )
                acl_info = self._parse_acl_response(acl_response)

                acl_entries = []
                for principal_id, permissions in acl_info.items():
                    acl_entries.append(
                        AclEntry(
                            principal_id=int(principal_id), permissions=permissions
                        )
                    )

                return EntityAcl(entity_id=entity_id, acl_entries=acl_entries)

            except SynapseHTTPError as e:
                if e.response.status_code != 404:
                    raise
                return None

        entity_ids = list(entities_by_id.keys())
        acl_tasks = [fetch_entity_acl(entity_id) for entity_id in entity_ids]

        entity_acls = []
        for completed_task in asyncio.as_completed(acl_tasks):
            try:
                result = await completed_task
                if result is not None:
                    entity_acls.append(result)
            except SynapseHTTPError as e:
                if e.response.status_code != 404:
                    raise
                continue
            except Exception as e:
                raise e

        return AclListResult(all_entity_acls=entity_acls)

    async def _fetch_user_group_info_from_tree(
        self, tree_structure: Dict[str, Any], synapse_client: "Synapse"
    ) -> Dict[str, str]:
        """
        Fetch user and group information for all principals found in a tree structure.

        Extracts all principal IDs from ACL entries within the tree structure and
        fetches their corresponding user/group names in a single batch operation.

        Arguments:
            tree_structure: Tree structure containing entity metadata with ACL information.
            synapse_client: Synapse client for API calls.

        Returns:
            Dictionary mapping principal IDs to user/group names.
        """
        entity_metadata = tree_structure.get("entity_metadata", {})
        return await self._fetch_user_group_info(entity_metadata, synapse_client)

    async def _fetch_user_group_info(
        self, entity_metadata: Dict[str, Any], synapse_client: "Synapse"
    ) -> Dict[str, str]:
        """
        Fetch user and group information for all principals found in ACLs.

        Scans through entity metadata to collect all unique principal IDs from
        ACL entries, then fetches their user/group information in a single batch call.

        Arguments:
            entity_metadata: Dictionary containing entity metadata with ACL information.
            synapse_client: Synapse client for API calls.

        Returns:
            Dictionary mapping principal IDs to user/group names.
        """
        all_principal_ids = self._extract_principal_ids_from_metadata(entity_metadata)

        if not all_principal_ids:
            return {}

        user_group_header_batch = await get_user_group_headers_batch(
            list(all_principal_ids), synapse_client=synapse_client
        )

        if not user_group_header_batch:
            return {}

        return {
            user_group_header["ownerId"]: user_group_header["userName"]
            for user_group_header in user_group_header_batch
        }

    def _extract_principal_ids_from_metadata(
        self, entity_metadata: Dict[str, Any]
    ) -> Set[str]:
        """
        Extract all unique principal IDs from entity metadata ACL entries.

        Arguments:
            entity_metadata: Dictionary containing entity metadata with ACL information.

        Returns:
            Set of principal ID strings found in the metadata.
        """
        all_principal_ids = set()
        for entity_id, metadata in entity_metadata.items():
            acl = metadata.get("acl")
            if acl and hasattr(acl, "acl_entries") and acl.acl_entries:
                for acl_entry in acl.acl_entries:
                    if acl_entry.principal_id:
                        all_principal_ids.add(str(acl_entry.principal_id))
        return all_principal_ids

    async def _format_dry_run_tree_async(
        self,
        tree_structure: Dict[str, Any],
        benefactor_tracker: BenefactorTracker,
        include_self: bool = True,
        entities_by_id: Optional[
            Dict[
                str,
                Union[
                    "File",
                    "Folder",
                    "EntityView",
                    "Table",
                    "MaterializedView",
                    "VirtualTable",
                    "Dataset",
                    "DatasetCollection",
                    "SubmissionView",
                ],
            ]
        ] = None,
        show_acl_details: bool = True,
        show_files_in_containers: bool = True,
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> str:
        """
        Format tree structure for dry run analysis showing ACL deletion impacts.

        Creates a comprehensive visualization showing which entities will have ACLs deleted,
        how inheritance will change, and which permissions will be affected. Uses icons
        and status indicators to clearly show current vs future state.

        Arguments:
            tree_structure: The tree structure dictionary from _build_acl_tree_structure.
            benefactor_tracker: Tracker containing benefactor relationships.
            include_self: Whether to include self in the deletion analysis.
            entities_by_id: Dictionary mapping entity IDs to entity objects.
            show_acl_details: Whether to display current ACL details for entities that will change.
            show_files_in_containers: Whether to show files within containers.
            synapse_client: Synapse client for API calls.

        Returns:
            Formatted ASCII tree string showing deletion impact analysis.
        """
        entity_metadata = tree_structure["entity_metadata"]
        children_map = tree_structure["children_map"]
        root_entities = tree_structure["root_entities"]

        user_group_info_map = await self._fetch_user_group_info_from_tree(
            tree_structure, synapse_client
        )

        await self._augment_tree_with_missing_entities(
            entity_metadata,
            children_map,
            benefactor_tracker,
            include_self,
            entities_by_id,
            synapse_client,
        )

        lines = self._build_dry_run_tree_lines(
            entity_metadata,
            children_map,
            root_entities,
            benefactor_tracker,
            include_self,
            show_acl_details,
            show_files_in_containers,
            user_group_info_map,
        )

        return "\n".join(lines)

    async def _augment_tree_with_missing_entities(
        self,
        entity_metadata: Dict[str, Any],
        children_map: Dict[str, List[str]],
        benefactor_tracker: BenefactorTracker,
        include_self: bool,
        entities_by_id: Optional[
            Dict[
                str,
                Union[
                    "File",
                    "Folder",
                    "EntityView",
                    "Table",
                    "MaterializedView",
                    "VirtualTable",
                    "Dataset",
                    "DatasetCollection",
                    "SubmissionView",
                ],
            ]
        ],
        synapse_client: Optional["Synapse"],
    ) -> None:
        """
        Add missing entity information needed for comprehensive tree display.

        Fetches metadata for entities that are affected by ACL deletions but not
        already present in the tree structure, ensuring complete impact visualization.

        Arguments:
            entity_metadata: Dictionary to augment with missing entity information.
            children_map: Dictionary mapping parent entities to their children.
            benefactor_tracker: Tracker containing benefactor relationships.
            include_self: Whether to include self in the deletion analysis.
            entities_by_id: Dictionary mapping entity IDs to entity objects.
            synapse_client: Synapse client for API calls.
        """
        all_missing_entity_ids = set()
        for entity_id in entity_metadata.keys():
            metadata = entity_metadata[entity_id]
            has_local_acl = metadata.get("acl") is not None
            is_self_entity = hasattr(self, "id") and entity_id == self.id
            will_be_deleted = has_local_acl and (not is_self_entity or include_self)

            if will_be_deleted:
                affected_children = benefactor_tracker.benefactor_children.get(
                    entity_id, []
                )
                children = children_map.get(entity_id, [])
                children_not_in_tree = [
                    child_id
                    for child_id in affected_children
                    if child_id not in children
                ]
                all_missing_entity_ids.update(children_not_in_tree)

        if all_missing_entity_ids:
            missing_entity_details = await self._fetch_missing_entity_details(
                list(all_missing_entity_ids),
                entity_metadata,
                entities_by_id,
                synapse_client,
            )
            entity_metadata.update(missing_entity_details)

    async def _fetch_missing_entity_details(
        self,
        entity_ids: List[str],
        entity_metadata: Dict[str, Any],
        entities_by_id: Optional[
            Dict[
                str,
                Union[
                    "File",
                    "Folder",
                    "EntityView",
                    "Table",
                    "MaterializedView",
                    "VirtualTable",
                    "Dataset",
                    "DatasetCollection",
                    "SubmissionView",
                ],
            ]
        ],
        synapse_client: Optional["Synapse"],
    ) -> Dict[str, Dict[str, str]]:
        """
        Fetch entity details for entities not already in metadata.

        Arguments:
            entity_ids: List of entity IDs to fetch details for.
            entity_metadata: Existing entity metadata to check against.
            entities_by_id: Dictionary mapping entity IDs to entity objects.
            synapse_client: Synapse client for API calls.

        Returns:
            Dictionary mapping entity IDs to their metadata.
        """
        missing_entities = {}
        tasks = []
        entity_id_to_task = {}

        for entity_id in entity_ids:
            if entity_id not in entity_metadata:
                if entities_by_id and entity_id in entities_by_id:
                    entity = entities_by_id[entity_id]
                    missing_entities[entity_id] = {
                        "name": getattr(entity, "name", f"Entity {entity_id}"),
                        "type": entity.__class__.__name__,
                        "parent_id": getattr(entity, "parent_id", None),
                        "acl": None,
                    }
                else:
                    task = get_entity_benefactor(
                        entity_id=entity_id, synapse_client=synapse_client
                    )
                    tasks.append(task)
                    entity_id_to_task[entity_id] = task

        if not tasks:
            return missing_entities

        for completed_task in asyncio.as_completed(tasks):
            header = await completed_task

            entity_id = None
            for eid, task in entity_id_to_task.items():
                if task == completed_task:
                    entity_id = eid
                    break

            if entity_id:
                entity_type = self._normalize_entity_type(header.type)
                missing_entities[entity_id] = {
                    "name": header.name or f"Entity {entity_id}",
                    "type": entity_type,
                    "parent_id": None,
                    "acl": None,
                }

        return missing_entities

    def _normalize_entity_type(self, entity_type: str) -> str:
        """
        Normalize entity type string to a readable format.

        Arguments:
            entity_type: Raw entity type string from API.

        Returns:
            Normalized entity type string.
        """
        if not entity_type:
            return "Unknown"

        if entity_type.startswith("org.sagebionetworks.repo.model."):
            entity_type = entity_type.split(".")[-1]
            if entity_type == "FileEntity":
                return "File"

        return entity_type

    def _build_dry_run_tree_lines(
        self,
        entity_metadata: Dict[str, Any],
        children_map: Dict[str, List[str]],
        root_entities: List[str],
        benefactor_tracker: BenefactorTracker,
        include_self: bool,
        show_acl_details: bool,
        show_files_in_containers: bool,
        user_group_info_map: Dict[str, str],
    ) -> List[str]:
        """
        Build the lines for the dry run tree display.

        Creates the actual tree visualization with all status indicators,
        benefactor changes, and impact analysis.

        Arguments:
            entity_metadata: Dictionary containing entity metadata with ACL information.
            children_map: Dictionary mapping parent entities to their children.
            root_entities: List of root entity IDs for the tree.
            benefactor_tracker: Tracker containing benefactor relationships.
            include_self: Whether to include self in the deletion analysis.
            show_acl_details: Whether to display current ACL details.
            show_files_in_containers: Whether to show files within containers.
            user_group_info_map: Dictionary mapping principal IDs to user/group names.

        Returns:
            List of strings representing the tree lines.
        """
        lines = []

        def find_ultimate_benefactor_for_affected(entity_id: str) -> str:
            """Recursively find the ultimate benefactor for an affected entity."""
            parent_id = entity_metadata.get(entity_id, {}).get("parent_id")
            if not parent_id:
                return entity_id

            if parent_id in entity_metadata:
                parent_metadata = entity_metadata[parent_id]
                parent_has_local_acl = parent_metadata.get("acl") is not None
                parent_is_self = hasattr(self, "id") and parent_id == self.id
                parent_will_be_deleted = parent_has_local_acl and (
                    not parent_is_self or include_self
                )

                if parent_will_be_deleted:
                    return find_ultimate_benefactor_for_affected(parent_id)
                else:
                    if parent_has_local_acl:
                        return parent_id
                    else:
                        return find_ultimate_benefactor_for_affected(parent_id)
            else:
                return parent_id

        def format_entity_with_benefactor_info(entity_id: str) -> str:
            """Format entity information with benefactor and impact details."""
            metadata = entity_metadata[entity_id]
            name = metadata["name"]
            entity_type = metadata["type"]

            current_benefactor = benefactor_tracker.entity_benefactors.get(
                entity_id, entity_id
            )
            affected_children = benefactor_tracker.benefactor_children.get(
                entity_id, []
            )

            has_local_acl = metadata.get("acl") is not None
            is_self_entity = hasattr(self, "id") and entity_id == self.id
            will_be_deleted = has_local_acl and (not is_self_entity or include_self)

            base_info = f"{name} ({entity_id}) [{entity_type}]"

            if will_be_deleted:
                status_info = " ⚠️  WILL DELETE LOCAL ACL"
                ultimate_benefactor = find_ultimate_benefactor_for_affected(entity_id)
                if ultimate_benefactor and ultimate_benefactor != entity_id:
                    status_info += f" → Will inherit from {ultimate_benefactor}"
                if affected_children:
                    status_info += f" → Affects {len(affected_children)} children"
            elif has_local_acl and is_self_entity and not include_self:
                status_info = " 🚫 LOCAL ACL WILL NOT BE DELETED"
            else:
                will_benefactor_change = False
                new_benefactor = current_benefactor

                for ancestor_id in entity_metadata.keys():
                    ancestor_metadata = entity_metadata[ancestor_id]
                    ancestor_has_local_acl = ancestor_metadata.get("acl") is not None
                    ancestor_is_self = hasattr(self, "id") and ancestor_id == self.id
                    ancestor_will_be_deleted = ancestor_has_local_acl and (
                        not ancestor_is_self or include_self
                    )

                    if (
                        ancestor_will_be_deleted
                        and entity_id
                        in benefactor_tracker.benefactor_children.get(ancestor_id, [])
                    ):
                        will_benefactor_change = True
                        new_benefactor = find_ultimate_benefactor_for_affected(
                            entity_id
                        )
                        break

                if will_benefactor_change:
                    status_info = f" 📍 Will inherit from {new_benefactor} (currently {current_benefactor})"
                else:
                    if current_benefactor != entity_id:
                        status_info = f" ↗️  Inherits from {current_benefactor}"
                    else:
                        status_info = " 🔒 No local ACL"

            return base_info + status_info

        def format_principal_with_impact(
            entity_id: str, principal_id: str, permissions: List[str]
        ) -> Optional[str]:
            """Format principal information with permission impact."""
            permission_list = permissions if permissions else ["None"]

            team_name = user_group_info_map.get(str(principal_id))
            if team_name:
                principal_info = f"{team_name} ({principal_id})"
            else:
                principal_info = f"Principal {principal_id}"

            is_self_entity = hasattr(self, "id") and entity_id == self.id
            will_be_deleted = not is_self_entity or include_self

            if will_be_deleted:
                return f"🔑 {principal_info}: {permission_list} → WILL BE REMOVED"
            else:
                return None

        def is_entity_relevant(entity_id: str) -> bool:
            """Determine if an entity should be included in the trimmed tree."""
            metadata = entity_metadata[entity_id]
            has_local_acl = metadata.get("acl") is not None
            is_self_entity = hasattr(self, "id") and entity_id == self.id
            will_be_deleted = has_local_acl and (not is_self_entity or include_self)
            entity_type = metadata.get("type", "").lower()

            if will_be_deleted:
                return True

            will_benefactor_change = False
            for ancestor_id in entity_metadata.keys():
                ancestor_metadata = entity_metadata[ancestor_id]
                ancestor_has_local_acl = ancestor_metadata.get("acl") is not None
                ancestor_is_self = hasattr(self, "id") and ancestor_id == self.id
                ancestor_will_be_deleted = ancestor_has_local_acl and (
                    not ancestor_is_self or include_self
                )

                if (
                    ancestor_will_be_deleted
                    and entity_id
                    in benefactor_tracker.benefactor_children.get(ancestor_id, [])
                ):
                    will_benefactor_change = True
                    break

            if not show_files_in_containers and "file" in entity_type:
                if will_be_deleted:
                    return True
                else:
                    return False

            if will_benefactor_change:
                return True

            return False

        def get_relevant_children(entity_id: str) -> List[str]:
            """Get only the children that are relevant for the trimmed tree."""
            all_children = children_map.get(entity_id, [])
            relevant_children = []

            for child_id in all_children:
                if is_entity_relevant(child_id):
                    relevant_children.append(child_id)
                elif has_relevant_descendants(child_id):
                    relevant_children.append(child_id)

            return relevant_children

        def has_relevant_descendants(entity_id: str) -> bool:
            """Check if an entity has any relevant descendants."""
            children = children_map.get(entity_id, [])
            for child_id in children:
                if is_entity_relevant(child_id) or has_relevant_descendants(child_id):
                    return True
            return False

        def build_tree_recursive(
            entity_id: str,
            prefix: str = "",
            is_last: bool = True,
            is_root: bool = False,
        ) -> None:
            """Recursively build the enhanced dry run tree."""
            if is_root:
                lines.append(f"{format_entity_with_benefactor_info(entity_id)}")
                extension_prefix = ""
            else:
                current_prefix = "└── " if is_last else "├── "
                lines.append(
                    f"{prefix}{current_prefix}{format_entity_with_benefactor_info(entity_id)}"
                )
                extension_prefix = prefix + ("    " if is_last else "│   ")

            metadata = entity_metadata[entity_id]
            acl = metadata.get("acl")
            acl_principals = []

            if (
                show_acl_details
                and acl
                and hasattr(acl, "acl_entries")
                and acl.acl_entries
            ):
                for acl_entry in acl.acl_entries:
                    principal_id = acl_entry.principal_id
                    permissions = acl_entry.permissions if acl_entry.permissions else []
                    acl_principals.append((principal_id, permissions))

                for i, (principal_id, permissions) in enumerate(acl_principals):
                    is_last_principal = (
                        i == len(acl_principals) - 1
                    ) and not get_relevant_children(entity_id)
                    principal_prefix = "└── " if is_last_principal else "├── "
                    formatted_principal = format_principal_with_impact(
                        entity_id, principal_id, permissions
                    )
                    if formatted_principal:
                        lines.append(
                            f"{extension_prefix}{principal_prefix}{formatted_principal}"
                        )

            affected_children = benefactor_tracker.benefactor_children.get(
                entity_id, []
            )
            relevant_children = get_relevant_children(entity_id)

            metadata = entity_metadata[entity_id]
            has_local_acl = metadata.get("acl") is not None
            is_self_entity = hasattr(self, "id") and entity_id == self.id
            will_be_deleted = has_local_acl and (not is_self_entity or include_self)

            if will_be_deleted and affected_children:
                children_not_in_tree = [
                    child_id
                    for child_id in affected_children
                    if child_id not in relevant_children
                    and is_entity_relevant(child_id)
                ]

                if children_not_in_tree:
                    all_children = relevant_children + children_not_in_tree
                    all_children.sort(
                        key=lambda child_id: entity_metadata.get(child_id, {}).get(
                            "name", f"Entity {child_id}"
                        )
                    )

                    for i, child_id in enumerate(all_children):
                        is_last_child = i == len(all_children) - 1

                        if child_id in children_not_in_tree:
                            child_metadata = entity_metadata.get(child_id, {})
                            child_name = child_metadata.get(
                                "name", f"Entity {child_id}"
                            )
                            child_type = child_metadata.get("type", "Unknown")
                            change_prefix = "└── " if is_last_child else "├── "

                            new_benefactor = find_ultimate_benefactor_for_affected(
                                child_id
                            )
                            current_benefactor = (
                                benefactor_tracker.entity_benefactors.get(
                                    child_id, child_id
                                )
                            )

                            lines.append(
                                f"{extension_prefix}{change_prefix}{child_name} ({child_id}) "
                                f"[{child_type}] 📍 Will inherit from {new_benefactor} (currently {current_benefactor})"
                            )
                        else:
                            build_tree_recursive(
                                child_id, extension_prefix, is_last_child, False
                            )
                    return

            if relevant_children:
                relevant_children.sort(
                    key=lambda child_id: entity_metadata[child_id]["name"]
                )
                for i, child_id in enumerate(relevant_children):
                    is_last_child = i == len(relevant_children) - 1
                    build_tree_recursive(
                        child_id, extension_prefix, is_last_child, False
                    )

        entities_with_acls = 0
        total_affected_children = 0
        for entity_id in entity_metadata.keys():
            metadata = entity_metadata[entity_id]
            has_local_acl = metadata.get("acl") is not None
            is_self_entity = hasattr(self, "id") and entity_id == self.id
            will_be_deleted = has_local_acl and (not is_self_entity or include_self)

            if will_be_deleted:
                entities_with_acls += 1
                affected_children_count = len(
                    benefactor_tracker.benefactor_children.get(entity_id, [])
                )
                total_affected_children += affected_children_count

        lines.append(
            f"📊 Summary: {entities_with_acls} entities with local ACLs to delete, "
            f"{total_affected_children + entities_with_acls} entities will change inheritance"
        )

        lines.append("")
        lines.append("🔍 Legend:")
        lines.append("  ⚠️  = Local ACL will be deleted")
        lines.append("  🚫 = Local ACL will NOT be deleted")
        lines.append("  ↗️ = Currently inherits permissions")
        lines.append("  🔒 = No local ACL (inherits from parent)")
        lines.append("  🔑 = Permission that will be removed")
        lines.append("  📍 = New inheritance after deletion")
        lines.append("")

        relevant_roots = [
            root_id
            for root_id in root_entities
            if is_entity_relevant(root_id) or has_relevant_descendants(root_id)
        ]

        if len(relevant_roots) == 1:
            build_tree_recursive(relevant_roots[0], "", True, True)
        else:
            relevant_roots.sort(
                key=lambda entity_id: entity_metadata[entity_id]["name"] or ""
            )
            for i, root_id in enumerate(relevant_roots):
                is_last_root = i == len(relevant_roots) - 1
                build_tree_recursive(root_id, "", is_last_root, True)

        return lines

    async def _log_acl_tree(
        self,
        acl_result: AclListResult,
        entities: List[Union["File", "Folder"]],
        client: Synapse,
    ) -> str:
        """
        Generate and log an ASCII tree representation of ACL results.

        Creates a hierarchical tree structure from the ACL results and displays
        entity hierarchies with their ACL permissions in a tree-like format using
        ASCII characters. This provides a clear view of the current permission
        structure across the entity hierarchy.

        Arguments:
            acl_result: The ACL list result containing entity ACL information.
            entities: List of entity objects that have been processed.
            client: The Synapse client instance for API calls and logging.
        """
        if not acl_result or not acl_result.all_entity_acls:
            client.logger.info("No ACL results to display in tree format.")
            return

        tree_structure = await self._build_acl_tree_structure(acl_result, entities)
        tree_output = await self._format_ascii_tree_async(
            tree_structure, synapse_client=client
        )

        client.logger.info("ACL Tree Structure:")
        client.logger.info(tree_output)
        return tree_output

    async def _build_acl_tree_structure(
        self, acl_result: AclListResult, entities: List[Union["File", "Folder"]]
    ) -> Dict[str, Any]:
        """
        Build a hierarchical tree structure from ACL results.

        Creates a comprehensive tree structure that includes entity metadata,
        parent-child relationships, and ACL information. This structure can be
        used by different formatting functions to display trees in various ways.

        Arguments:
            acl_result: The ACL list result containing entity ACL information.
            entities: List of entity objects to use for metadata instead of API calls.

        Returns:
            Dictionary containing entity_metadata, children_map, and root_entities.
        """
        entity_metadata = {}
        children_map = {}
        all_entity_ids = set()

        for entity_acl in acl_result.all_entity_acls:
            if entity_acl.entity_id:
                all_entity_ids.add(entity_acl.entity_id)

        entities_by_id = {}
        if entities:
            for entity in entities:
                if hasattr(entity, "id") and entity.id:
                    entities_by_id[entity.id] = entity
                    all_entity_ids.add(entity.id)

        for entity_id in all_entity_ids:
            if entity_id in entities_by_id:
                entity = entities_by_id[entity_id]
                entity_metadata[entity_id] = {
                    "name": getattr(entity, "name", f"Entity {entity_id}"),
                    "type": entity.__class__.__name__,
                    "parent_id": getattr(entity, "parent_id", None),
                    "acl": next(
                        (
                            acl
                            for acl in acl_result.all_entity_acls
                            if acl.entity_id == entity_id
                        ),
                        None,
                    ),
                }
            else:
                entity_metadata[entity_id] = {
                    "name": f"Entity {entity_id}",
                    "type": "Unknown",
                    "parent_id": None,
                    "acl": next(
                        (
                            acl
                            for acl in acl_result.all_entity_acls
                            if acl.entity_id == entity_id
                        ),
                        None,
                    ),
                }

        entities_needing_parents = set(all_entity_ids)
        while entities_needing_parents:
            current_entity_id = entities_needing_parents.pop()
            if current_entity_id in entity_metadata:
                parent_id = entity_metadata[current_entity_id]["parent_id"]
                if parent_id and parent_id not in entity_metadata:
                    if parent_id in entities_by_id:
                        parent_entity = entities_by_id[parent_id]
                        entity_metadata[parent_id] = {
                            "name": getattr(
                                parent_entity, "name", f"Entity {parent_id}"
                            ),
                            "type": parent_entity.__class__.__name__,
                            "parent_id": getattr(parent_entity, "parent_id", None),
                            "acl": None,
                        }
                        all_entity_ids.add(parent_id)
                        entities_needing_parents.add(parent_id)

        for entity_id in all_entity_ids:
            if entity_id in entity_metadata:
                parent_id = entity_metadata[entity_id]["parent_id"]
                if parent_id and parent_id in entity_metadata:
                    if parent_id not in children_map:
                        children_map[parent_id] = []
                    children_map[parent_id].append(entity_id)

        root_entities = []
        for entity_id in all_entity_ids:
            parent_id = entity_metadata[entity_id]["parent_id"]
            if not parent_id or parent_id not in all_entity_ids:
                root_entities.append(entity_id)

        if not root_entities:
            root_entities = list(all_entity_ids)

        if hasattr(self, "id") and self.id in all_entity_ids:
            if self.id in root_entities:
                root_entities.remove(self.id)
            root_entities.insert(0, self.id)

        return {
            "entity_metadata": entity_metadata,
            "children_map": children_map,
            "root_entities": root_entities,
        }

    async def _format_ascii_tree_async(
        self,
        tree_structure: Dict[str, Any],
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> str:
        """
        Format the tree structure as ASCII art with ACL status icons.

        Creates a visual tree representation showing entity hierarchies with
        ACL status indicators. Uses ASCII art characters to show parent-child
        relationships and displays permission information for each entity.

        Arguments:
            tree_structure: The tree structure dictionary.
            synapse_client: Synapse client for fetching user/group information.

        Returns:
            A string containing the ASCII tree representation with ACL status indicators.
        """
        entity_metadata = tree_structure["entity_metadata"]
        children_map = tree_structure["children_map"]
        root_entities = tree_structure["root_entities"]

        user_group_info_map = await self._fetch_user_group_info_from_tree(
            tree_structure,
            synapse_client or Synapse.get_client(synapse_client=synapse_client),
        )

        lines = []
        lines.append("🔍 Legend:")
        lines.append("  🔒 = No local ACL (inherits from parent)")
        lines.append("  🔑 = Local ACL (custom permissions)")
        lines.append("")

        def get_acl_status_icon(entity_id: str) -> str:
            """Get the appropriate ACL status icon for an entity."""
            metadata = entity_metadata[entity_id]
            acl = metadata.get("acl")
            return (
                "🔑"
                if (acl and hasattr(acl, "acl_entries") and acl.acl_entries)
                else "🔒"
            )

        def should_show_entity(entity_id: str) -> bool:
            """Determine if an entity should be shown in the tree."""
            metadata = entity_metadata[entity_id]
            acl = metadata.get("acl")

            if acl and hasattr(acl, "acl_entries") and acl.acl_entries:
                return True

            children = children_map.get(entity_id, [])
            return any(should_show_entity(child_id) for child_id in children)

        def format_entity_info(entity_id: str) -> str:
            """Format entity information with ACL status icon."""
            metadata = entity_metadata[entity_id]
            name = metadata["name"]
            entity_type = metadata["type"]
            acl_icon = get_acl_status_icon(entity_id)
            return f"{acl_icon} {name} ({entity_id}) [{entity_type}]"

        def format_principal_info(principal_id: str, permissions: List[str]) -> str:
            """Format principal information with permissions."""
            permission_list = permissions if permissions else ["None"]
            team_name = user_group_info_map.get(str(principal_id))

            if team_name:
                return (
                    f"   └── {team_name} ({principal_id}): {', '.join(permission_list)}"
                )
            else:
                return f"   └── Principal {principal_id}: {', '.join(permission_list)}"

        def build_tree_recursive(
            entity_id: str, prefix: str = "", is_last: bool = True
        ) -> None:
            """Recursively build the ASCII tree."""
            if not should_show_entity(entity_id):
                return

            current_prefix = "└── " if is_last else "├── "
            lines.append(f"{prefix}{current_prefix}{format_entity_info(entity_id)}")

            metadata = entity_metadata[entity_id]
            acl = metadata.get("acl")

            if acl and hasattr(acl, "acl_entries") and acl.acl_entries:
                extension_prefix = prefix + ("    " if is_last else "│   ")
                for acl_entry in acl.acl_entries:
                    principal_id = acl_entry.principal_id
                    permissions = acl_entry.permissions if acl_entry.permissions else []
                    lines.append(
                        f"{extension_prefix}{format_principal_info(principal_id, permissions)}"
                    )

            children = children_map.get(entity_id, [])
            if children:
                visible_children = [
                    child_id for child_id in children if should_show_entity(child_id)
                ]
                visible_children.sort(
                    key=lambda child_id: entity_metadata[child_id]["name"]
                )
                extension_prefix = prefix + ("    " if is_last else "│   ")

                for i, child_id in enumerate(visible_children):
                    is_last_child = i == len(visible_children) - 1
                    build_tree_recursive(child_id, extension_prefix, is_last_child)

        visible_roots = [
            root_id for root_id in root_entities if should_show_entity(root_id)
        ]

        if not visible_roots:
            lines.append("No entities with local ACLs found.")
            return "\n".join(lines)

        if len(visible_roots) == 1:
            build_tree_recursive(visible_roots[0])
        else:
            visible_roots.sort(key=lambda entity_id: entity_metadata[entity_id]["name"])
            for i, root_id in enumerate(visible_roots):
                is_last_root = i == len(visible_roots) - 1
                build_tree_recursive(root_id, "", is_last_root)

        return "\n".join(lines)

    async def _process_children_with_progress(
        self,
        client: Synapse,
        normalized_types: List[str],
        include_container_content: bool,
        recursive: bool,
        all_entities: List,
        all_acls: Dict[str, Dict[str, List[str]]],
        progress_bar: Optional[tqdm] = None,
    ) -> None:
        """
        Process children entities with optional progress tracking.

        Arguments:
            client: The Synapse client instance
            normalized_types: List of normalized entity types to process
            include_container_content: Whether to include container content
            recursive: Whether to process recursively
            all_entities: List to append entities to
            all_acls: Dictionary to store ACL results
            progress_bar: Progress bar for tracking
        """
        operations_completed = 0

        if not self._synced_from_synapse:
            if progress_bar:
                progress_bar.total += 1
                progress_bar.refresh()

            await self.sync_from_synapse_async(
                recursive=False,
                download_file=False,
                include_activity=False,
                synapse_client=client,
            )

            operations_completed += 1
            if progress_bar:
                progress_bar.update(1)

        if progress_bar:
            progress_bar.total += 1
            progress_bar.refresh()

        child_entities = await self._collect_entities(
            client=client,
            target_entity_types=normalized_types,
            include_container_content=include_container_content,
            recursive=recursive,
            collect_acls=True,
            collect_self=False,
            all_acls=all_acls,
            progress_bar=progress_bar,
        )

        operations_completed += 1
        if progress_bar:
            progress_bar.update(1)

        for entity in child_entities:
            if entity != self:
                all_entities.append(entity)

Attributes

id class-attribute instance-attribute

id: Optional[str] = None

The unique immutable ID for this entity. A new ID will be generated for new Files. Once issued, this ID is guaranteed to never change or be re-issued.

Functions

get_permissions_async async

get_permissions_async(*, synapse_client: Optional[Synapse] = None) -> Permissions

Get the permissions that the caller has on an Entity.

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Permissions

A Permissions object

Using this function:

Getting permissions for a Synapse Entity

import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    permissions = await File(id="syn123").get_permissions_async()

asyncio.run(main())

Getting access types list from the Permissions object

permissions.access_types
Source code in synapseclient/models/mixins/access_control.py
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
async def get_permissions_async(
    self,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Permissions":
    """
    Get the [permissions][synapseclient.core.models.permission.Permissions]
    that the caller has on an Entity.

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        A Permissions object


    Example: Using this function:
        Getting permissions for a Synapse Entity

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            permissions = await File(id="syn123").get_permissions_async()

        asyncio.run(main())
        ```

        Getting access types list from the Permissions object

        ```
        permissions.access_types
        ```
    """
    from synapseclient.core.models.permission import Permissions

    permissions_dict = await get_entity_permissions(
        entity_id=self.id,
        synapse_client=synapse_client,
    )
    return Permissions.from_dict(data=permissions_dict)

get_acl_async async

get_acl_async(principal_id: int = None, check_benefactor: bool = True, *, synapse_client: Optional[Synapse] = None) -> List[str]

Get the ACL that a user or group has on an Entity.

Note: If the entity does not have local sharing settings, or ACL set directly on it, this will look up the ACL on the benefactor of the entity. The benefactor is the entity that the current entity inherits its permissions from. The benefactor is usually the parent entity, but it can be any ancestor in the hierarchy. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project or Folder. If the entity already has local sharing settings, the benefactor would be itself.

PARAMETER DESCRIPTION
principal_id

Identifier of a user or group (defaults to PUBLIC users)

TYPE: int DEFAULT: None

check_benefactor

If True (default), check the benefactor for the entity to get the ACL. If False, only check the entity itself. This is useful for checking the ACL of an entity that has local sharing settings, but you want to check the ACL of the entity itself and not the benefactor it may inherit from.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
List[str]

An array containing some combination of ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE', 'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS'] or an empty array

Source code in synapseclient/models/mixins/access_control.py
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
async def get_acl_async(
    self,
    principal_id: int = None,
    check_benefactor: bool = True,
    *,
    synapse_client: Optional[Synapse] = None,
) -> List[str]:
    """
    Get the [ACL][synapseclient.core.models.permission.Permissions.access_types]
    that a user or group has on an Entity.

    Note: If the entity does not have local sharing settings, or ACL set directly
    on it, this will look up the ACL on the benefactor of the entity. The
    benefactor is the entity that the current entity inherits its permissions from.
    The benefactor is usually the parent entity, but it can be any ancestor in the
    hierarchy. For example, a newly created Project will be its own benefactor,
    while a new FileEntity's benefactor will start off as its containing Project or
    Folder. If the entity already has local sharing settings, the benefactor would
    be itself.

    Arguments:
        principal_id: Identifier of a user or group (defaults to PUBLIC users)
        check_benefactor: If True (default), check the benefactor for the entity
            to get the ACL. If False, only check the entity itself.
            This is useful for checking the ACL of an entity that has local sharing
            settings, but you want to check the ACL of the entity itself and not
            the benefactor it may inherit from.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        An array containing some combination of
            ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
            'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
            or an empty array
    """
    return await get_entity_acl_list(
        entity_id=self.id,
        principal_id=str(principal_id) if principal_id is not None else None,
        check_benefactor=check_benefactor,
        synapse_client=synapse_client,
    )

set_permissions_async async

set_permissions_async(principal_id: int = None, access_type: List[str] = None, modify_benefactor: bool = False, warn_if_inherits: bool = True, overwrite: bool = True, *, synapse_client: Optional[Synapse] = None) -> Dict[str, Union[str, list]]

Sets permission that a user or group has on an Entity. An Entity may have its own ACL or inherit its ACL from a benefactor.

PARAMETER DESCRIPTION
principal_id

Identifier of a user or group. 273948 is for all registered Synapse users and 273949 is for public access. None implies public access.

TYPE: int DEFAULT: None

access_type

Type of permission to be granted. One or more of CREATE, READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS.

Defaults to ['READ', 'DOWNLOAD']

TYPE: List[str] DEFAULT: None

modify_benefactor

Set as True when modifying a benefactor's ACL. The term 'benefactor' is used to indicate which Entity an Entity inherits its ACL from. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project. If the entity already has local sharing settings the benefactor would be itself. It may also be the immediate parent, somewhere in the parent tree, or the project itself.

TYPE: bool DEFAULT: False

warn_if_inherits

When modify_benefactor is True, this does not have any effect. When modify_benefactor is False, and warn_if_inherits is True, a warning log message is produced if the benefactor for the entity you passed into the function is not itself, i.e., it's the parent folder, or another entity in the parent tree.

TYPE: bool DEFAULT: True

overwrite

By default this function overwrites existing permissions for the specified user. Set this flag to False to add new permissions non-destructively.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Dict[str, Union[str, list]]
Setting permissions

Grant all registered users download access

import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    await File(id="syn123").set_permissions_async(principal_id=273948, access_type=['READ','DOWNLOAD'])

asyncio.run(main())

Grant the public view access

import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    await File(id="syn123").set_permissions_async(principal_id=273949, access_type=['READ'])

asyncio.run(main())
Source code in synapseclient/models/mixins/access_control.py
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
async def set_permissions_async(
    self,
    principal_id: int = None,
    access_type: List[str] = None,
    modify_benefactor: bool = False,
    warn_if_inherits: bool = True,
    overwrite: bool = True,
    *,
    synapse_client: Optional[Synapse] = None,
) -> Dict[str, Union[str, list]]:
    """
    Sets permission that a user or group has on an Entity.
    An Entity may have its own ACL or inherit its ACL from a benefactor.

    Arguments:
        principal_id: Identifier of a user or group. `273948` is for all
            registered Synapse users and `273949` is for public access.
            None implies public access.
        access_type: Type of permission to be granted. One or more of CREATE,
            READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS.

            **Defaults to ['READ', 'DOWNLOAD']**
        modify_benefactor: Set as True when modifying a benefactor's ACL. The term
            'benefactor' is used to indicate which Entity an Entity inherits its
            ACL from. For example, a newly created Project will be its own
            benefactor, while a new FileEntity's benefactor will start off as its
            containing Project. If the entity already has local sharing settings
            the benefactor would be itself. It may also be the immediate parent,
            somewhere in the parent tree, or the project itself.
        warn_if_inherits: When `modify_benefactor` is True, this does not have any
            effect. When `modify_benefactor` is False, and `warn_if_inherits` is
            True, a warning log message is produced if the benefactor for the
            entity you passed into the function is not itself, i.e., it's the
            parent folder, or another entity in the parent tree.
        overwrite: By default this function overwrites existing permissions for
            the specified user. Set this flag to False to add new permissions
            non-destructively.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        An Access Control List object matching <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/AccessControlList.html>.

    Example: Setting permissions
        Grant all registered users download access

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            await File(id="syn123").set_permissions_async(principal_id=273948, access_type=['READ','DOWNLOAD'])

        asyncio.run(main())
        ```

        Grant the public view access

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            await File(id="syn123").set_permissions_async(principal_id=273949, access_type=['READ'])

        asyncio.run(main())
        ```
    """
    if access_type is None:
        access_type = ["READ", "DOWNLOAD"]

    return await set_entity_permissions(
        entity_id=self.id,
        principal_id=str(principal_id) if principal_id is not None else None,
        access_type=access_type,
        modify_benefactor=modify_benefactor,
        warn_if_inherits=warn_if_inherits,
        overwrite=overwrite,
        synapse_client=synapse_client,
    )

delete_permissions_async async

delete_permissions_async(include_self: bool = True, include_container_content: bool = False, recursive: bool = False, target_entity_types: Optional[List[str]] = None, dry_run: bool = False, show_acl_details: bool = True, show_files_in_containers: bool = True, *, synapse_client: Optional[Synapse] = None, _benefactor_tracker: Optional[BenefactorTracker] = None) -> None

Delete the entire Access Control List (ACL) for a given Entity. This is not scoped to a specific user or group, but rather removes all permissions associated with the Entity. After this operation, the Entity will inherit permissions from its benefactor, which is typically its parent entity or the Project it belongs to.

In order to remove permissions for a specific user or group, you should use the set_permissions_async method with the access_type set to an empty list.

By default, Entities such as FileEntity and Folder inherit their permission from their containing Project. For such Entities the Project is the Entity's 'benefactor'. This permission inheritance can be overridden by creating an ACL for the Entity. When this occurs the Entity becomes its own benefactor and all permission are determined by its own ACL.

If the ACL of an Entity is deleted, then its benefactor will automatically be set to its parent's benefactor.

Special notice for Projects: The ACL for a Project cannot be deleted, you must individually update or revoke the permissions for each user or group.

PARAMETER DESCRIPTION
include_self

If True (default), delete the ACL of the current entity. If False, skip deleting the ACL of the current entity.

TYPE: bool DEFAULT: True

include_container_content

If True, delete ACLs from contents directly within containers (files and folders inside self). This must be set to True for recursive to have any effect. Defaults to False.

TYPE: bool DEFAULT: False

recursive

If True and the entity is a container (e.g., Project or Folder), recursively process child containers. Note that this must be used with include_container_content=True to have any effect. Setting recursive=True with include_container_content=False will raise a ValueError. Only works on classes that support the sync_from_synapse_async method.

TYPE: bool DEFAULT: False

target_entity_types

Specify which entity types to process when deleting ACLs. Allowed values are "folder", "file", "project", "table", "entityview", "materializedview", "virtualtable", "dataset", "datasetcollection", "submissionview" (case-insensitive). If None, defaults to ["folder", "file"]. This does not affect the entity type of the current entity, which is always processed if include_self=True.

TYPE: Optional[List[str]] DEFAULT: None

dry_run

If True, log the changes that would be made instead of actually performing the deletions. When enabled, all ACL deletion operations are simulated and logged at info level. Defaults to False.

TYPE: bool DEFAULT: False

show_acl_details

When dry_run=True, controls whether current ACL details are displayed for entities that will have their permissions changed. If True (default), shows detailed ACL information. If False, hides ACL details for cleaner output. Has no effect when dry_run=False.

TYPE: bool DEFAULT: True

show_files_in_containers

When dry_run=True, controls whether files within containers are displayed in the preview. If True (default), shows all files. If False, hides files when their only change is benefactor inheritance (but still shows files with local ACLs being deleted). Has no effect when dry_run=False.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

_benefactor_tracker

Internal use tracker for managing benefactor relationships. Used for recursive functionality to track which entities will be affected

TYPE: Optional[BenefactorTracker] DEFAULT: None

RETURNS DESCRIPTION
None

None

RAISES DESCRIPTION
ValueError

If the entity does not have an ID or if an invalid entity type is provided.

SynapseHTTPError

If there are permission issues or if the entity already inherits permissions.

Exception

For any other errors that may occur during the process.

Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to call this method.

Delete permissions for a single entity
import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    await File(id="syn123").delete_permissions_async()

asyncio.run(main())
Delete permissions recursively for a folder and all its children
import asyncio
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

async def main():
    # Delete permissions for this folder only (does not affect children)
    await Folder(id="syn123").delete_permissions_async()

    # Delete permissions for all files and folders directly within this folder,
    # but not the folder itself
    await Folder(id="syn123").delete_permissions_async(
        include_self=False,
        include_container_content=True
    )

    # Delete permissions for all items in the entire hierarchy (folders and their files)
    # Both recursive and include_container_content must be True
    await Folder(id="syn123").delete_permissions_async(
        recursive=True,
        include_container_content=True
    )

    # Delete permissions only for folder entities within this folder recursively
    # and their contents
    await Folder(id="syn123").delete_permissions_async(
        recursive=True,
        include_container_content=True,
        target_entity_types=["folder"]
    )

    # Delete permissions only for files within this folder and all subfolders
    await Folder(id="syn123").delete_permissions_async(
        include_self=False,
        recursive=True,
        include_container_content=True,
        target_entity_types=["file"]
    )

    # Delete permissions for specific entity types (e.g., tables and views)
    await Folder(id="syn123").delete_permissions_async(
        recursive=True,
        include_container_content=True,
        target_entity_types=["table", "entityview", "materializedview"]
    )

    # Dry run example: Log what would be deleted without making changes
    await Folder(id="syn123").delete_permissions_async(
        recursive=True,
        include_container_content=True,
        dry_run=True
    )
asyncio.run(main())
Source code in synapseclient/models/mixins/access_control.py
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
async def delete_permissions_async(
    self,
    include_self: bool = True,
    include_container_content: bool = False,
    recursive: bool = False,
    target_entity_types: Optional[List[str]] = None,
    dry_run: bool = False,
    show_acl_details: bool = True,
    show_files_in_containers: bool = True,
    *,
    synapse_client: Optional[Synapse] = None,
    _benefactor_tracker: Optional[BenefactorTracker] = None,
) -> None:
    """
    Delete the entire Access Control List (ACL) for a given Entity. This is not
    scoped to a specific user or group, but rather removes all permissions
    associated with the Entity. After this operation, the Entity will inherit
    permissions from its benefactor, which is typically its parent entity or
    the Project it belongs to.

    In order to remove permissions for a specific user or group, you
    should use the `set_permissions_async` method with the `access_type` set to
    an empty list.

    By default, Entities such as FileEntity and Folder inherit their permission from
    their containing Project. For such Entities the Project is the Entity's 'benefactor'.
    This permission inheritance can be overridden by creating an ACL for the Entity.
    When this occurs the Entity becomes its own benefactor and all permission are
    determined by its own ACL.

    If the ACL of an Entity is deleted, then its benefactor will automatically be set
    to its parent's benefactor.

    **Special notice for Projects:** The ACL for a Project cannot be deleted, you
    must individually update or revoke the permissions for each user or group.

    Arguments:
        include_self: If True (default), delete the ACL of the current entity.
            If False, skip deleting the ACL of the current entity.
        include_container_content: If True, delete ACLs from contents directly within
            containers (files and folders inside self). This must be set to
            True for recursive to have any effect. Defaults to False.
        recursive: If True and the entity is a container (e.g., Project or Folder),
            recursively process child containers. Note that this must be used with
            include_container_content=True to have any effect. Setting recursive=True
            with include_container_content=False will raise a ValueError.
            Only works on classes that support the `sync_from_synapse_async` method.
        target_entity_types: Specify which entity types to process when deleting ACLs.
            Allowed values are "folder", "file", "project", "table", "entityview",
            "materializedview", "virtualtable", "dataset", "datasetcollection",
            "submissionview" (case-insensitive). If None, defaults to ["folder", "file"].
            This does not affect the entity type of the current entity, which is always
            processed if `include_self=True`.
        dry_run: If True, log the changes that would be made instead of actually
            performing the deletions. When enabled, all ACL deletion operations are
            simulated and logged at info level. Defaults to False.
        show_acl_details: When dry_run=True, controls whether current ACL details are
            displayed for entities that will have their permissions changed. If True (default),
            shows detailed ACL information. If False, hides ACL details for cleaner output.
            Has no effect when dry_run=False.
        show_files_in_containers: When dry_run=True, controls whether files within containers
            are displayed in the preview. If True (default), shows all files. If False, hides
            files when their only change is benefactor inheritance (but still shows files with
            local ACLs being deleted). Has no effect when dry_run=False.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.
        _benefactor_tracker: Internal use tracker for managing benefactor relationships.
            Used for recursive functionality to track which entities will be affected

    Returns:
        None

    Raises:
        ValueError: If the entity does not have an ID or if an invalid entity type is provided.
        SynapseHTTPError: If there are permission issues or if the entity already inherits permissions.
        Exception: For any other errors that may occur during the process.

    Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to
    call this method.

    Example: Delete permissions for a single entity
        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            await File(id="syn123").delete_permissions_async()

        asyncio.run(main())
        ```

    Example: Delete permissions recursively for a folder and all its children
        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        async def main():
            # Delete permissions for this folder only (does not affect children)
            await Folder(id="syn123").delete_permissions_async()

            # Delete permissions for all files and folders directly within this folder,
            # but not the folder itself
            await Folder(id="syn123").delete_permissions_async(
                include_self=False,
                include_container_content=True
            )

            # Delete permissions for all items in the entire hierarchy (folders and their files)
            # Both recursive and include_container_content must be True
            await Folder(id="syn123").delete_permissions_async(
                recursive=True,
                include_container_content=True
            )

            # Delete permissions only for folder entities within this folder recursively
            # and their contents
            await Folder(id="syn123").delete_permissions_async(
                recursive=True,
                include_container_content=True,
                target_entity_types=["folder"]
            )

            # Delete permissions only for files within this folder and all subfolders
            await Folder(id="syn123").delete_permissions_async(
                include_self=False,
                recursive=True,
                include_container_content=True,
                target_entity_types=["file"]
            )

            # Delete permissions for specific entity types (e.g., tables and views)
            await Folder(id="syn123").delete_permissions_async(
                recursive=True,
                include_container_content=True,
                target_entity_types=["table", "entityview", "materializedview"]
            )

            # Dry run example: Log what would be deleted without making changes
            await Folder(id="syn123").delete_permissions_async(
                recursive=True,
                include_container_content=True,
                dry_run=True
            )
        asyncio.run(main())
        ```
    """
    if not self.id:
        raise ValueError("The entity must have an ID to delete permissions.")

    client = Synapse.get_client(synapse_client=synapse_client)

    if include_self and self.__class__.__name__.lower() == "project":
        client.logger.warning(
            "The ACL for a Project cannot be deleted, you must individually update or "
            "revoke the permissions for each user or group. Continuing without deleting "
            "the Project's ACL."
        )
        include_self = False

    normalized_types = self._normalize_target_entity_types(target_entity_types)

    is_top_level = not _benefactor_tracker
    benefactor_tracker = _benefactor_tracker or BenefactorTracker()

    should_process_children = (recursive or include_container_content) and hasattr(
        self, "sync_from_synapse_async"
    )
    all_entities = [self] if include_self else []

    custom_message = "Deleting ACLs [Dry Run]..." if dry_run else "Deleting ACLs..."
    with shared_download_progress_bar(
        file_size=1, synapse_client=client, custom_message=custom_message, unit=None
    ) as progress_bar:
        if progress_bar:
            progress_bar.update(1)  # Initial setup complete

        if should_process_children:
            if recursive and not include_container_content:
                raise ValueError(
                    "When recursive=True, include_container_content must also be True. "
                    "Setting recursive=True with include_container_content=False has no effect."
                )

            if progress_bar:
                progress_bar.total += 1
                progress_bar.refresh()

            all_entities = await self._collect_entities(
                client=client,
                target_entity_types=normalized_types,
                include_container_content=include_container_content,
                recursive=recursive,
                progress_bar=progress_bar,
            )
            if progress_bar:
                progress_bar.update(1)

            entity_ids = [entity.id for entity in all_entities if entity.id]
            if entity_ids:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()
                await benefactor_tracker.track_entity_benefactor(
                    entity_ids=entity_ids,
                    synapse_client=client,
                    progress_bar=progress_bar,
                )
            else:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()
                    progress_bar.update(1)

        if is_top_level:
            if progress_bar:
                progress_bar.total += 1
                progress_bar.refresh()
            await self._build_and_log_run_tree(
                client=client,
                benefactor_tracker=benefactor_tracker,
                collected_entities=all_entities,
                include_self=include_self,
                show_acl_details=show_acl_details,
                show_files_in_containers=show_files_in_containers,
                progress_bar=progress_bar,
                dry_run=dry_run,
            )

        if dry_run:
            return

        if include_self:
            if progress_bar:
                progress_bar.total += 1
                progress_bar.refresh()
            await self._delete_current_entity_acl(
                client=client,
                benefactor_tracker=benefactor_tracker,
                progress_bar=progress_bar,
            )

        if should_process_children:
            if include_container_content:
                if progress_bar:
                    progress_bar.total += 1
                    progress_bar.refresh()
                await self._process_container_contents(
                    client=client,
                    target_entity_types=normalized_types,
                    benefactor_tracker=benefactor_tracker,
                    progress_bar=progress_bar,
                    recursive=recursive,
                    include_container_content=include_container_content,
                )
                if progress_bar:
                    progress_bar.update(1)  # Process container contents complete

list_acl_async async

list_acl_async(recursive: bool = False, include_container_content: bool = False, target_entity_types: Optional[List[str]] = None, log_tree: bool = False, *, synapse_client: Optional[Synapse] = None, _progress_bar: Optional[tqdm] = None) -> AclListResult

List the Access Control Lists (ACLs) for this entity and optionally its children.

This function returns the local sharing settings for the entity and optionally its children. It provides a mapping of all ACLs for the given container/entity.

Important Note: This function returns the LOCAL sharing settings only, not the effective permissions that each Synapse User ID/Team has on the entities. More permissive permissions could be granted via a Team that the user has access to that has permissions on the entity, or through inheritance from parent entities.

PARAMETER DESCRIPTION
recursive

If True and the entity is a container (e.g., Project or Folder), recursively process child containers. Note that this must be used with include_container_content=True to have any effect. Setting recursive=True with include_container_content=False will raise a ValueError. Only works on classes that support the sync_from_synapse_async method.

TYPE: bool DEFAULT: False

include_container_content

If True, include ACLs from contents directly within containers (files and folders inside self). This must be set to True for recursive to have any effect. Defaults to False.

TYPE: bool DEFAULT: False

target_entity_types

Specify which entity types to process when listing ACLs. Allowed values are "folder", "file", "project", "table", "entityview", "materializedview", "virtualtable", "dataset", "datasetcollection", "submissionview" (case-insensitive). If None, defaults to ["folder", "file"].

TYPE: Optional[List[str]] DEFAULT: None

log_tree

If True, logs the ACL results to console in ASCII tree format showing entity hierarchies and their ACL permissions in a tree-like structure. Defaults to False.

TYPE: bool DEFAULT: False

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

_progress_bar

Internal parameter. Progress bar instance to use for updates when called recursively. Should not be used by external callers.

TYPE: Optional[tqdm] DEFAULT: None

RETURNS DESCRIPTION
AclListResult

An AclListResult object containing a structured representation of ACLs where:

AclListResult
  • entity_acls: A list of EntityAcl objects, each representing one entity's ACL
AclListResult
  • Each EntityAcl contains acl_entries (a list of AclEntry objects)
AclListResult
  • Each AclEntry contains the principal_id and their list of permissions
RAISES DESCRIPTION
ValueError

If the entity does not have an ID or if an invalid entity type is provided.

SynapseHTTPError

If there are permission issues accessing ACLs.

Exception

For any other errors that may occur during the process.

List ACLs for a single entity
import asyncio
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

async def main():
    acl_result = await File(id="syn123").list_acl_async()
    print(acl_result)

    # Access entity ACLs (entity_acls is a list, not a dict)
    for entity_acl in acl_result.all_entity_acls:
        if entity_acl.entity_id == "syn123":
            # Access individual ACL entries
            for acl_entry in entity_acl.acl_entries:
                if acl_entry.principal_id == "273948":
                    print(f"Principal 273948 has permissions: {acl_entry.permissions}")

    # I can also access the ACL for the file itself
    print(acl_result.entity_acl)

    print(acl_result)

asyncio.run(main())
List ACLs recursively for a folder and all its children
import asyncio
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

async def main():
    acl_result = await Folder(id="syn123").list_acl_async(
        recursive=True,
        include_container_content=True
    )

    # Access each entity's ACL (entity_acls is a list)
    for entity_acl in acl_result.all_entity_acls:
        print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")

    # I can also access the ACL for the folder itself
    print(acl_result.entity_acl)

    # List ACLs for only folder entities
    folder_acl_result = await Folder(id="syn123").list_acl_async(
        recursive=True,
        include_container_content=True,
        target_entity_types=["folder"]
    )

    # List ACLs for specific entity types (e.g., tables and views)
    table_view_acl_result = await Folder(id="syn123").list_acl_async(
        recursive=True,
        include_container_content=True,
        target_entity_types=["table", "entityview", "materializedview"]
    )

asyncio.run(main())
List ACLs with ASCII tree visualization

When log_tree=True, the ACLs will be logged in a tree format. Additionally, the ascii_tree attribute of the AclListResult will contain the ASCII tree representation of the ACLs.

import asyncio
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

async def main():
    acl_result = await Folder(id="syn123").list_acl_async(
        recursive=True,
        include_container_content=True,
        log_tree=True, # Enable ASCII tree logging
    )

    # The ASCII tree representation of the ACLs will also be available
    # in acl_result.ascii_tree
    print(acl_result.ascii_tree)

asyncio.run(main())
Source code in synapseclient/models/mixins/access_control.py
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
async def list_acl_async(
    self,
    recursive: bool = False,
    include_container_content: bool = False,
    target_entity_types: Optional[List[str]] = None,
    log_tree: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
    _progress_bar: Optional[tqdm] = None,  # Internal parameter for recursive calls
) -> AclListResult:
    """
    List the Access Control Lists (ACLs) for this entity and optionally its children.

    This function returns the local sharing settings for the entity and optionally
    its children. It provides a mapping of all ACLs for the given container/entity.

    **Important Note:** This function returns the LOCAL sharing settings only, not
    the effective permissions that each Synapse User ID/Team has on the entities.
    More permissive permissions could be granted via a Team that the user has access
    to that has permissions on the entity, or through inheritance from parent entities.

    Arguments:
        recursive: If True and the entity is a container (e.g., Project or Folder),
            recursively process child containers. Note that this must be used with
            include_container_content=True to have any effect. Setting recursive=True
            with include_container_content=False will raise a ValueError.
            Only works on classes that support the `sync_from_synapse_async` method.
        include_container_content: If True, include ACLs from contents directly within
            containers (files and folders inside self). This must be set to
            True for recursive to have any effect. Defaults to False.
        target_entity_types: Specify which entity types to process when listing ACLs.
            Allowed values are "folder", "file", "project", "table", "entityview",
            "materializedview", "virtualtable", "dataset", "datasetcollection",
            "submissionview" (case-insensitive). If None, defaults to ["folder", "file"].
        log_tree: If True, logs the ACL results to console in ASCII tree format showing
            entity hierarchies and their ACL permissions in a tree-like structure.
            Defaults to False.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.
        _progress_bar: Internal parameter. Progress bar instance to use for updates
            when called recursively. Should not be used by external callers.

    Returns:
        An AclListResult object containing a structured representation of ACLs where:
        - entity_acls: A list of EntityAcl objects, each representing one entity's ACL
        - Each EntityAcl contains acl_entries (a list of AclEntry objects)
        - Each AclEntry contains the principal_id and their list of permissions

    Raises:
        ValueError: If the entity does not have an ID or if an invalid entity type is provided.
        SynapseHTTPError: If there are permission issues accessing ACLs.
        Exception: For any other errors that may occur during the process.

    Example: List ACLs for a single entity
        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        async def main():
            acl_result = await File(id="syn123").list_acl_async()
            print(acl_result)

            # Access entity ACLs (entity_acls is a list, not a dict)
            for entity_acl in acl_result.all_entity_acls:
                if entity_acl.entity_id == "syn123":
                    # Access individual ACL entries
                    for acl_entry in entity_acl.acl_entries:
                        if acl_entry.principal_id == "273948":
                            print(f"Principal 273948 has permissions: {acl_entry.permissions}")

            # I can also access the ACL for the file itself
            print(acl_result.entity_acl)

            print(acl_result)

        asyncio.run(main())
        ```

    Example: List ACLs recursively for a folder and all its children
        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        async def main():
            acl_result = await Folder(id="syn123").list_acl_async(
                recursive=True,
                include_container_content=True
            )

            # Access each entity's ACL (entity_acls is a list)
            for entity_acl in acl_result.all_entity_acls:
                print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")

            # I can also access the ACL for the folder itself
            print(acl_result.entity_acl)

            # List ACLs for only folder entities
            folder_acl_result = await Folder(id="syn123").list_acl_async(
                recursive=True,
                include_container_content=True,
                target_entity_types=["folder"]
            )

            # List ACLs for specific entity types (e.g., tables and views)
            table_view_acl_result = await Folder(id="syn123").list_acl_async(
                recursive=True,
                include_container_content=True,
                target_entity_types=["table", "entityview", "materializedview"]
            )

        asyncio.run(main())
        ```

    Example: List ACLs with ASCII tree visualization
        When `log_tree=True`, the ACLs will be logged in a tree format. Additionally,
        the `ascii_tree` attribute of the AclListResult will contain the ASCII tree
        representation of the ACLs.

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        async def main():
            acl_result = await Folder(id="syn123").list_acl_async(
                recursive=True,
                include_container_content=True,
                log_tree=True, # Enable ASCII tree logging
            )

            # The ASCII tree representation of the ACLs will also be available
            # in acl_result.ascii_tree
            print(acl_result.ascii_tree)

        asyncio.run(main())
        ```
    """
    if not self.id:
        raise ValueError("The entity must have an ID to list ACLs.")

    normalized_types = self._normalize_target_entity_types(target_entity_types)
    client = Synapse.get_client(synapse_client=synapse_client)

    all_acls: Dict[str, Dict[str, List[str]]] = {}
    all_entities = []

    # Only update progress bar for self ACL if we're the top-level call (not recursive)
    # When _progress_bar is passed, it means this is a recursive call and the parent
    # is managing progress updates
    update_progress_for_self = _progress_bar is None
    acl = await self._get_current_entity_acl(
        client=client,
        progress_bar=_progress_bar if update_progress_for_self else None,
    )
    if acl is not None:
        all_acls[self.id] = acl
    all_entities.append(self)

    should_process_children = (recursive or include_container_content) and hasattr(
        self, "sync_from_synapse_async"
    )

    if should_process_children and (recursive and not include_container_content):
        raise ValueError(
            "When recursive=True, include_container_content must also be True. "
            "Setting recursive=True with include_container_content=False has no effect."
        )

    if should_process_children and _progress_bar is None:
        with shared_download_progress_bar(
            file_size=1,
            synapse_client=client,
            custom_message="Collecting ACLs...",
            unit=None,
        ) as progress_bar:
            await self._process_children_with_progress(
                client=client,
                normalized_types=normalized_types,
                include_container_content=include_container_content,
                recursive=recursive,
                all_entities=all_entities,
                all_acls=all_acls,
                progress_bar=progress_bar,
            )
            # Ensure progress bar reaches 100% completion
            if progress_bar:
                remaining = (
                    progress_bar.total - progress_bar.n
                    if progress_bar.total > progress_bar.n
                    else 0
                )
                if remaining > 0:
                    progress_bar.update(remaining)
    elif should_process_children:
        await self._process_children_with_progress(
            client=client,
            normalized_types=normalized_types,
            include_container_content=include_container_content,
            recursive=recursive,
            all_entities=all_entities,
            all_acls=all_acls,
            progress_bar=_progress_bar,
        )
    current_acl = all_acls.get(self.id)
    acl_result = AclListResult.from_dict(
        all_acl_dict=all_acls, current_acl_dict=current_acl
    )

    if log_tree:
        logged_tree = await self._log_acl_tree(acl_result, all_entities, client)
        acl_result.ascii_tree = logged_tree

    return acl_result

synapseclient.models.protocols.access_control_protocol.AccessControllableSynchronousProtocol

Bases: Protocol

The protocol for methods that are asynchronous but also have a synchronous counterpart that may also be called.

Source code in synapseclient/models/protocols/access_control_protocol.py
 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
class AccessControllableSynchronousProtocol(Protocol):
    """
    The protocol for methods that are asynchronous but also
    have a synchronous counterpart that may also be called.
    """

    def get_permissions(
        self,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "Permissions":
        """
        Get the [permissions][synapseclient.core.models.permission.Permissions]
        that the caller has on an Entity.

        Arguments:
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            A Permissions object


        Example: Using this function:
            Getting permissions for a Synapse Entity

            ```python
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            permissions = File(id="syn123").get_permissions()
            ```

            Getting access types list from the Permissions object

            ```
            permissions.access_types
            ```
        """
        return self

    def get_acl(
        self,
        principal_id: int = None,
        check_benefactor: bool = True,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> List[str]:
        """
        Get the [ACL][synapseclient.core.models.permission.Permissions.access_types]
        that a user or group has on an Entity.

        Note: If the entity does not have local sharing settings, or ACL set directly
        on it, this will look up the ACL on the benefactor of the entity. The
        benefactor is the entity that the current entity inherits its permissions from.
        The benefactor is usually the parent entity, but it can be any ancestor in the
        hierarchy. For example, a newly created Project will be its own benefactor,
        while a new FileEntity's benefactor will start off as its containing Project or
        Folder. If the entity already has local sharing settings, the benefactor would
        be itself.

        Arguments:
            principal_id: Identifier of a user or group (defaults to PUBLIC users)
            check_benefactor: If True (default), check the benefactor for the entity
                to get the ACL. If False, only check the entity itself.
                This is useful for checking the ACL of an entity that has local sharing
                settings, but you want to check the ACL of the entity itself and not
                the benefactor it may inherit from.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            An array containing some combination of
                ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
                'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
                or an empty array
        """
        return [""]

    def set_permissions(
        self,
        principal_id: int = None,
        access_type: List[str] = None,
        modify_benefactor: bool = False,
        warn_if_inherits: bool = True,
        overwrite: bool = True,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> Dict[str, Union[str, list]]:
        """
        Sets permission that a user or group has on an Entity.
        An Entity may have its own ACL or inherit its ACL from a benefactor.

        Arguments:
            principal_id: Identifier of a user or group. `273948` is for all
                registered Synapse users and `273949` is for public access.
                None implies public access.
            access_type: Type of permission to be granted. One or more of CREATE,
                READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS.

                **Defaults to ['READ', 'DOWNLOAD']**
            modify_benefactor: Set as True when modifying a benefactor's ACL. The term
                'benefactor' is used to indicate which Entity an Entity inherits its
                ACL from. For example, a newly created Project will be its own
                benefactor, while a new FileEntity's benefactor will start off as its
                containing Project. If the entity already has local sharing settings
                the benefactor would be itself. It may also be the immediate parent,
                somewhere in the parent tree, or the project itself.
            warn_if_inherits: When `modify_benefactor` is True, this does not have any
                effect. When `modify_benefactor` is False, and `warn_if_inherits` is
                True, a warning log message is produced if the benefactor for the
                entity you passed into the function is not itself, i.e., it's the
                parent folder, or another entity in the parent tree.
            overwrite: By default this function overwrites existing permissions for
                the specified user. Set this flag to False to add new permissions
                non-destructively.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            An Access Control List object

        Example: Setting permissions
            Grant all registered users download access

            ```python
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            File(id="syn123").set_permissions(principal_id=273948, access_type=['READ','DOWNLOAD'])
            ```

            Grant the public view access

            ```python
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            File(id="syn123").set_permissions(principal_id=273949, access_type=['READ'])
            ```
        """
        return {}

    def delete_permissions(
        self,
        include_self: bool = True,
        include_container_content: bool = False,
        recursive: bool = False,
        target_entity_types: Optional[List[str]] = None,
        dry_run: bool = False,
        show_acl_details: bool = True,
        show_files_in_containers: bool = True,
        *,
        benefactor_tracker: Optional["BenefactorTracker"] = None,
        synapse_client: Optional[Synapse] = None,
    ) -> None:
        """
        Delete the entire Access Control List (ACL) for a given Entity. This is not
        scoped to a specific user or group, but rather removes all permissions
        associated with the Entity. After this operation, the Entity will inherit
        permissions from its benefactor, which is typically its parent entity or
        the Project it belongs to.

        In order to remove permissions for a specific user or group, you
        should use the `set_permissions` method with the `access_type` set to
        an empty list.

        By default, Entities such as FileEntity and Folder inherit their permission from
        their containing Project. For such Entities the Project is the Entity's 'benefactor'.
        This permission inheritance can be overridden by creating an ACL for the Entity.
        When this occurs the Entity becomes its own benefactor and all permission are
        determined by its own ACL.

        If the ACL of an Entity is deleted, then its benefactor will automatically be set
        to its parent's benefactor.

        **Special notice for Projects:** The ACL for a Project cannot be deleted, you
        must individually update or revoke the permissions for each user or group.

        Arguments:
            include_self: If True (default), delete the ACL of the current entity.
                If False, skip deleting the ACL of the current entity.
            include_container_content: If True, delete ACLs from contents directly within
                containers (files and folders inside self). This must be set to
                True for recursive to have any effect. Defaults to False.
            recursive: If True and the entity is a container (e.g., Project or Folder),
                recursively process child containers. Note that this must be used with
                include_container_content=True to have any effect. Setting recursive=True
                with include_container_content=False will raise a ValueError.
                Only works on classes that support the `sync_from_synapse_async` method.
            target_entity_types: Specify which entity types to process when deleting ACLs.
                Allowed values are "folder" and "file" (case-insensitive).
                If None, defaults to ["folder", "file"]. This does not affect the
                entity type of the current entity, which is always processed if
                `include_self=True`.
            dry_run: If True, log the changes that would be made instead of actually
                performing the deletions. When enabled, all ACL deletion operations are
                simulated and logged at info level. Defaults to False.
            show_acl_details: When dry_run=True, controls whether current ACL details are
                displayed for entities that will have their permissions changed. If True (default),
                shows detailed ACL information. If False, hides ACL details for cleaner output.
                Has no effect when dry_run=False.
            show_files_in_containers: When dry_run=True, controls whether files within containers
                are displayed in the preview. If True (default), shows all files. If False, hides
                files when their only change is benefactor inheritance (but still shows files with
                local ACLs being deleted). Has no effect when dry_run=False.
            benefactor_tracker: Optional tracker for managing benefactor relationships.
                Used for recursive functionality to track which entities will be affected
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

        Returns:
            None

        Raises:
            ValueError: If the entity does not have an ID or if an invalid entity type is provided.
            SynapseHTTPError: If there are permission issues or if the entity already inherits permissions.
            Exception: For any other errors that may occur during the process.

        Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to
        call this method.

        Example: Delete permissions for a single entity
            ```python
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            File(id="syn123").delete_permissions()

            ```

        Example: Delete permissions recursively for a folder and all its children
            ```python
            from synapseclient import Synapse
            from synapseclient.models import Folder

            syn = Synapse()
            syn.login()

            # Delete permissions for this folder only (does not affect children)
            Folder(id="syn123").delete_permissions()

            # Delete permissions for all files and folders directly within this folder,
            # but not the folder itself
            Folder(id="syn123").delete_permissions(
                include_self=False,
                include_container_content=True
            )

            # Delete permissions for all items in the entire hierarchy (folders and their files)
            # Both recursive and include_container_content must be True
            Folder(id="syn123").delete_permissions(
                recursive=True,
                include_container_content=True
            )

            # Delete permissions only for folder entities within this folder recursively
            # and their contents
            Folder(id="syn123").delete_permissions(
                recursive=True,
                include_container_content=True,
                target_entity_types=["folder"]
            )

            # Delete permissions only for files within this folder and all subfolders
            Folder(id="syn123").delete_permissions(
                include_self=False,
                recursive=True,
                include_container_content=True,
                target_entity_types=["file"]
            )

            # Dry run example: Log what would be deleted without making changes
            Folder(id="syn123").delete_permissions(
                recursive=True,
                include_container_content=True,
                dry_run=True
            )
            ```
        """
        return None

    def list_acl(
        self,
        recursive: bool = False,
        include_container_content: bool = False,
        target_entity_types: Optional[List[str]] = None,
        log_tree: bool = False,
        *,
        synapse_client: Optional[Synapse] = None,
        _progress_bar: Optional[tqdm] = None,  # Internal parameter for recursive calls
    ) -> "AclListResult":
        """
        List the Access Control Lists (ACLs) for this entity and optionally its children.

        This function returns the local sharing settings for the entity and optionally
        its children. It provides a mapping of all ACLs for the given container/entity.

        **Important Note:** This function returns the LOCAL sharing settings only, not
        the effective permissions that each Synapse User ID/Team has on the entities.
        More permissive permissions could be granted via a Team that the user has access
        to that has permissions on the entity, or through inheritance from parent entities.

        Arguments:
            recursive: If True and the entity is a container (e.g., Project or Folder),
                recursively process child containers. Note that this must be used with
                include_container_content=True to have any effect. Setting recursive=True
                with include_container_content=False will raise a ValueError.
                Only works on classes that support the `sync_from_synapse_async` method.
            include_container_content: If True, include ACLs from contents directly within
                containers (files and folders inside self). This must be set to
                True for recursive to have any effect. Defaults to False.
            target_entity_types: Specify which entity types to process when listing ACLs.
                Allowed values are "folder" and "file" (case-insensitive).
                If None, defaults to ["folder", "file"].
            log_tree: If True, logs the ACL results to console in ASCII tree format showing
                entity hierarchies and their ACL permissions in a tree-like structure.
                Defaults to False.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.
            _progress_bar: Internal parameter. Progress bar instance to use for updates
                when called recursively. Should not be used by external callers.

        Returns:
            An AclListResult object containing a structured representation of ACLs where:
            - entity_acls: A list of EntityAcl objects, each representing one entity's ACL
            - Each EntityAcl contains acl_entries (a list of AclEntry objects)
            - Each AclEntry contains the principal_id and their list of permissions

        Raises:
            ValueError: If the entity does not have an ID or if an invalid entity type is provided.
            SynapseHTTPError: If there are permission issues accessing ACLs.
            Exception: For any other errors that may occur during the process.

        Example: List ACLs for a single entity
            ```python
            from synapseclient import Synapse
            from synapseclient.models import File

            syn = Synapse()
            syn.login()

            acl_result = File(id="syn123").list_acl()
            print(acl_result)

            # Access entity ACLs (entity_acls is a list, not a dict)
            for entity_acl in acl_result.all_entity_acls:
                if entity_acl.entity_id == "syn123":
                    # Access individual ACL entries
                    for acl_entry in entity_acl.acl_entries:
                        if acl_entry.principal_id == "273948":
                            print(f"Principal 273948 has permissions: {acl_entry.permissions}")

            # I can also access the ACL for the file itself
            print(acl_result.entity_acl)

            print(acl_result)

            ```

        Example: List ACLs recursively for a folder and all its children
            ```python
            from synapseclient import Synapse
            from synapseclient.models import Folder

            syn = Synapse()
            syn.login()

            acl_result = Folder(id="syn123").list_acl(
                recursive=True,
                include_container_content=True
            )

            # Access each entity's ACL (entity_acls is a list)
            for entity_acl in acl_result.all_entity_acls:
                print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")

            # I can also access the ACL for the folder itself
            print(acl_result.entity_acl)

            # List ACLs for only folder entities
            folder_acl_result = Folder(id="syn123").list_acl(
                recursive=True,
                include_container_content=True,
                target_entity_types=["folder"]
            )
            ```

        Example: List ACLs with ASCII tree visualization
            When `log_tree=True`, the ACLs will be logged in a tree format. Additionally,
            the `ascii_tree` attribute of the AclListResult will contain the ASCII tree
            representation of the ACLs.

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Folder

            syn = Synapse()
            syn.login()

            acl_result = Folder(id="syn123").list_acl(
                recursive=True,
                include_container_content=True,
                log_tree=True, # Enable ASCII tree logging
            )

            # The ASCII tree representation of the ACLs will also be available
            # in acl_result.ascii_tree
            print(acl_result.ascii_tree)
            ```
        """
        return AclListResult()

Functions

get_permissions

get_permissions(*, synapse_client: Optional[Synapse] = None) -> Permissions

Get the permissions that the caller has on an Entity.

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Permissions

A Permissions object

Using this function:

Getting permissions for a Synapse Entity

from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

permissions = File(id="syn123").get_permissions()

Getting access types list from the Permissions object

permissions.access_types
Source code in synapseclient/models/protocols/access_control_protocol.py
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
def get_permissions(
    self,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "Permissions":
    """
    Get the [permissions][synapseclient.core.models.permission.Permissions]
    that the caller has on an Entity.

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        A Permissions object


    Example: Using this function:
        Getting permissions for a Synapse Entity

        ```python
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        permissions = File(id="syn123").get_permissions()
        ```

        Getting access types list from the Permissions object

        ```
        permissions.access_types
        ```
    """
    return self

get_acl

get_acl(principal_id: int = None, check_benefactor: bool = True, *, synapse_client: Optional[Synapse] = None) -> List[str]

Get the ACL that a user or group has on an Entity.

Note: If the entity does not have local sharing settings, or ACL set directly on it, this will look up the ACL on the benefactor of the entity. The benefactor is the entity that the current entity inherits its permissions from. The benefactor is usually the parent entity, but it can be any ancestor in the hierarchy. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project or Folder. If the entity already has local sharing settings, the benefactor would be itself.

PARAMETER DESCRIPTION
principal_id

Identifier of a user or group (defaults to PUBLIC users)

TYPE: int DEFAULT: None

check_benefactor

If True (default), check the benefactor for the entity to get the ACL. If False, only check the entity itself. This is useful for checking the ACL of an entity that has local sharing settings, but you want to check the ACL of the entity itself and not the benefactor it may inherit from.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
List[str]

An array containing some combination of ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE', 'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS'] or an empty array

Source code in synapseclient/models/protocols/access_control_protocol.py
 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
def get_acl(
    self,
    principal_id: int = None,
    check_benefactor: bool = True,
    *,
    synapse_client: Optional[Synapse] = None,
) -> List[str]:
    """
    Get the [ACL][synapseclient.core.models.permission.Permissions.access_types]
    that a user or group has on an Entity.

    Note: If the entity does not have local sharing settings, or ACL set directly
    on it, this will look up the ACL on the benefactor of the entity. The
    benefactor is the entity that the current entity inherits its permissions from.
    The benefactor is usually the parent entity, but it can be any ancestor in the
    hierarchy. For example, a newly created Project will be its own benefactor,
    while a new FileEntity's benefactor will start off as its containing Project or
    Folder. If the entity already has local sharing settings, the benefactor would
    be itself.

    Arguments:
        principal_id: Identifier of a user or group (defaults to PUBLIC users)
        check_benefactor: If True (default), check the benefactor for the entity
            to get the ACL. If False, only check the entity itself.
            This is useful for checking the ACL of an entity that has local sharing
            settings, but you want to check the ACL of the entity itself and not
            the benefactor it may inherit from.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        An array containing some combination of
            ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
            'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
            or an empty array
    """
    return [""]

set_permissions

set_permissions(principal_id: int = None, access_type: List[str] = None, modify_benefactor: bool = False, warn_if_inherits: bool = True, overwrite: bool = True, *, synapse_client: Optional[Synapse] = None) -> Dict[str, Union[str, list]]

Sets permission that a user or group has on an Entity. An Entity may have its own ACL or inherit its ACL from a benefactor.

PARAMETER DESCRIPTION
principal_id

Identifier of a user or group. 273948 is for all registered Synapse users and 273949 is for public access. None implies public access.

TYPE: int DEFAULT: None

access_type

Type of permission to be granted. One or more of CREATE, READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS.

Defaults to ['READ', 'DOWNLOAD']

TYPE: List[str] DEFAULT: None

modify_benefactor

Set as True when modifying a benefactor's ACL. The term 'benefactor' is used to indicate which Entity an Entity inherits its ACL from. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project. If the entity already has local sharing settings the benefactor would be itself. It may also be the immediate parent, somewhere in the parent tree, or the project itself.

TYPE: bool DEFAULT: False

warn_if_inherits

When modify_benefactor is True, this does not have any effect. When modify_benefactor is False, and warn_if_inherits is True, a warning log message is produced if the benefactor for the entity you passed into the function is not itself, i.e., it's the parent folder, or another entity in the parent tree.

TYPE: bool DEFAULT: True

overwrite

By default this function overwrites existing permissions for the specified user. Set this flag to False to add new permissions non-destructively.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Dict[str, Union[str, list]]

An Access Control List object

Setting permissions

Grant all registered users download access

from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

File(id="syn123").set_permissions(principal_id=273948, access_type=['READ','DOWNLOAD'])

Grant the public view access

from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

File(id="syn123").set_permissions(principal_id=273949, access_type=['READ'])
Source code in synapseclient/models/protocols/access_control_protocol.py
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
def set_permissions(
    self,
    principal_id: int = None,
    access_type: List[str] = None,
    modify_benefactor: bool = False,
    warn_if_inherits: bool = True,
    overwrite: bool = True,
    *,
    synapse_client: Optional[Synapse] = None,
) -> Dict[str, Union[str, list]]:
    """
    Sets permission that a user or group has on an Entity.
    An Entity may have its own ACL or inherit its ACL from a benefactor.

    Arguments:
        principal_id: Identifier of a user or group. `273948` is for all
            registered Synapse users and `273949` is for public access.
            None implies public access.
        access_type: Type of permission to be granted. One or more of CREATE,
            READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS.

            **Defaults to ['READ', 'DOWNLOAD']**
        modify_benefactor: Set as True when modifying a benefactor's ACL. The term
            'benefactor' is used to indicate which Entity an Entity inherits its
            ACL from. For example, a newly created Project will be its own
            benefactor, while a new FileEntity's benefactor will start off as its
            containing Project. If the entity already has local sharing settings
            the benefactor would be itself. It may also be the immediate parent,
            somewhere in the parent tree, or the project itself.
        warn_if_inherits: When `modify_benefactor` is True, this does not have any
            effect. When `modify_benefactor` is False, and `warn_if_inherits` is
            True, a warning log message is produced if the benefactor for the
            entity you passed into the function is not itself, i.e., it's the
            parent folder, or another entity in the parent tree.
        overwrite: By default this function overwrites existing permissions for
            the specified user. Set this flag to False to add new permissions
            non-destructively.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        An Access Control List object

    Example: Setting permissions
        Grant all registered users download access

        ```python
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        File(id="syn123").set_permissions(principal_id=273948, access_type=['READ','DOWNLOAD'])
        ```

        Grant the public view access

        ```python
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        File(id="syn123").set_permissions(principal_id=273949, access_type=['READ'])
        ```
    """
    return {}

delete_permissions

delete_permissions(include_self: bool = True, include_container_content: bool = False, recursive: bool = False, target_entity_types: Optional[List[str]] = None, dry_run: bool = False, show_acl_details: bool = True, show_files_in_containers: bool = True, *, benefactor_tracker: Optional[BenefactorTracker] = None, synapse_client: Optional[Synapse] = None) -> None

Delete the entire Access Control List (ACL) for a given Entity. This is not scoped to a specific user or group, but rather removes all permissions associated with the Entity. After this operation, the Entity will inherit permissions from its benefactor, which is typically its parent entity or the Project it belongs to.

In order to remove permissions for a specific user or group, you should use the set_permissions method with the access_type set to an empty list.

By default, Entities such as FileEntity and Folder inherit their permission from their containing Project. For such Entities the Project is the Entity's 'benefactor'. This permission inheritance can be overridden by creating an ACL for the Entity. When this occurs the Entity becomes its own benefactor and all permission are determined by its own ACL.

If the ACL of an Entity is deleted, then its benefactor will automatically be set to its parent's benefactor.

Special notice for Projects: The ACL for a Project cannot be deleted, you must individually update or revoke the permissions for each user or group.

PARAMETER DESCRIPTION
include_self

If True (default), delete the ACL of the current entity. If False, skip deleting the ACL of the current entity.

TYPE: bool DEFAULT: True

include_container_content

If True, delete ACLs from contents directly within containers (files and folders inside self). This must be set to True for recursive to have any effect. Defaults to False.

TYPE: bool DEFAULT: False

recursive

If True and the entity is a container (e.g., Project or Folder), recursively process child containers. Note that this must be used with include_container_content=True to have any effect. Setting recursive=True with include_container_content=False will raise a ValueError. Only works on classes that support the sync_from_synapse_async method.

TYPE: bool DEFAULT: False

target_entity_types

Specify which entity types to process when deleting ACLs. Allowed values are "folder" and "file" (case-insensitive). If None, defaults to ["folder", "file"]. This does not affect the entity type of the current entity, which is always processed if include_self=True.

TYPE: Optional[List[str]] DEFAULT: None

dry_run

If True, log the changes that would be made instead of actually performing the deletions. When enabled, all ACL deletion operations are simulated and logged at info level. Defaults to False.

TYPE: bool DEFAULT: False

show_acl_details

When dry_run=True, controls whether current ACL details are displayed for entities that will have their permissions changed. If True (default), shows detailed ACL information. If False, hides ACL details for cleaner output. Has no effect when dry_run=False.

TYPE: bool DEFAULT: True

show_files_in_containers

When dry_run=True, controls whether files within containers are displayed in the preview. If True (default), shows all files. If False, hides files when their only change is benefactor inheritance (but still shows files with local ACLs being deleted). Has no effect when dry_run=False.

TYPE: bool DEFAULT: True

benefactor_tracker

Optional tracker for managing benefactor relationships. Used for recursive functionality to track which entities will be affected

TYPE: Optional[BenefactorTracker] DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
None

None

RAISES DESCRIPTION
ValueError

If the entity does not have an ID or if an invalid entity type is provided.

SynapseHTTPError

If there are permission issues or if the entity already inherits permissions.

Exception

For any other errors that may occur during the process.

Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to call this method.

Delete permissions for a single entity
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

File(id="syn123").delete_permissions()
Delete permissions recursively for a folder and all its children
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

# Delete permissions for this folder only (does not affect children)
Folder(id="syn123").delete_permissions()

# Delete permissions for all files and folders directly within this folder,
# but not the folder itself
Folder(id="syn123").delete_permissions(
    include_self=False,
    include_container_content=True
)

# Delete permissions for all items in the entire hierarchy (folders and their files)
# Both recursive and include_container_content must be True
Folder(id="syn123").delete_permissions(
    recursive=True,
    include_container_content=True
)

# Delete permissions only for folder entities within this folder recursively
# and their contents
Folder(id="syn123").delete_permissions(
    recursive=True,
    include_container_content=True,
    target_entity_types=["folder"]
)

# Delete permissions only for files within this folder and all subfolders
Folder(id="syn123").delete_permissions(
    include_self=False,
    recursive=True,
    include_container_content=True,
    target_entity_types=["file"]
)

# Dry run example: Log what would be deleted without making changes
Folder(id="syn123").delete_permissions(
    recursive=True,
    include_container_content=True,
    dry_run=True
)
Source code in synapseclient/models/protocols/access_control_protocol.py
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
def delete_permissions(
    self,
    include_self: bool = True,
    include_container_content: bool = False,
    recursive: bool = False,
    target_entity_types: Optional[List[str]] = None,
    dry_run: bool = False,
    show_acl_details: bool = True,
    show_files_in_containers: bool = True,
    *,
    benefactor_tracker: Optional["BenefactorTracker"] = None,
    synapse_client: Optional[Synapse] = None,
) -> None:
    """
    Delete the entire Access Control List (ACL) for a given Entity. This is not
    scoped to a specific user or group, but rather removes all permissions
    associated with the Entity. After this operation, the Entity will inherit
    permissions from its benefactor, which is typically its parent entity or
    the Project it belongs to.

    In order to remove permissions for a specific user or group, you
    should use the `set_permissions` method with the `access_type` set to
    an empty list.

    By default, Entities such as FileEntity and Folder inherit their permission from
    their containing Project. For such Entities the Project is the Entity's 'benefactor'.
    This permission inheritance can be overridden by creating an ACL for the Entity.
    When this occurs the Entity becomes its own benefactor and all permission are
    determined by its own ACL.

    If the ACL of an Entity is deleted, then its benefactor will automatically be set
    to its parent's benefactor.

    **Special notice for Projects:** The ACL for a Project cannot be deleted, you
    must individually update or revoke the permissions for each user or group.

    Arguments:
        include_self: If True (default), delete the ACL of the current entity.
            If False, skip deleting the ACL of the current entity.
        include_container_content: If True, delete ACLs from contents directly within
            containers (files and folders inside self). This must be set to
            True for recursive to have any effect. Defaults to False.
        recursive: If True and the entity is a container (e.g., Project or Folder),
            recursively process child containers. Note that this must be used with
            include_container_content=True to have any effect. Setting recursive=True
            with include_container_content=False will raise a ValueError.
            Only works on classes that support the `sync_from_synapse_async` method.
        target_entity_types: Specify which entity types to process when deleting ACLs.
            Allowed values are "folder" and "file" (case-insensitive).
            If None, defaults to ["folder", "file"]. This does not affect the
            entity type of the current entity, which is always processed if
            `include_self=True`.
        dry_run: If True, log the changes that would be made instead of actually
            performing the deletions. When enabled, all ACL deletion operations are
            simulated and logged at info level. Defaults to False.
        show_acl_details: When dry_run=True, controls whether current ACL details are
            displayed for entities that will have their permissions changed. If True (default),
            shows detailed ACL information. If False, hides ACL details for cleaner output.
            Has no effect when dry_run=False.
        show_files_in_containers: When dry_run=True, controls whether files within containers
            are displayed in the preview. If True (default), shows all files. If False, hides
            files when their only change is benefactor inheritance (but still shows files with
            local ACLs being deleted). Has no effect when dry_run=False.
        benefactor_tracker: Optional tracker for managing benefactor relationships.
            Used for recursive functionality to track which entities will be affected
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        None

    Raises:
        ValueError: If the entity does not have an ID or if an invalid entity type is provided.
        SynapseHTTPError: If there are permission issues or if the entity already inherits permissions.
        Exception: For any other errors that may occur during the process.

    Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to
    call this method.

    Example: Delete permissions for a single entity
        ```python
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        File(id="syn123").delete_permissions()

        ```

    Example: Delete permissions recursively for a folder and all its children
        ```python
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        # Delete permissions for this folder only (does not affect children)
        Folder(id="syn123").delete_permissions()

        # Delete permissions for all files and folders directly within this folder,
        # but not the folder itself
        Folder(id="syn123").delete_permissions(
            include_self=False,
            include_container_content=True
        )

        # Delete permissions for all items in the entire hierarchy (folders and their files)
        # Both recursive and include_container_content must be True
        Folder(id="syn123").delete_permissions(
            recursive=True,
            include_container_content=True
        )

        # Delete permissions only for folder entities within this folder recursively
        # and their contents
        Folder(id="syn123").delete_permissions(
            recursive=True,
            include_container_content=True,
            target_entity_types=["folder"]
        )

        # Delete permissions only for files within this folder and all subfolders
        Folder(id="syn123").delete_permissions(
            include_self=False,
            recursive=True,
            include_container_content=True,
            target_entity_types=["file"]
        )

        # Dry run example: Log what would be deleted without making changes
        Folder(id="syn123").delete_permissions(
            recursive=True,
            include_container_content=True,
            dry_run=True
        )
        ```
    """
    return None

list_acl

list_acl(recursive: bool = False, include_container_content: bool = False, target_entity_types: Optional[List[str]] = None, log_tree: bool = False, *, synapse_client: Optional[Synapse] = None, _progress_bar: Optional[tqdm] = None) -> AclListResult

List the Access Control Lists (ACLs) for this entity and optionally its children.

This function returns the local sharing settings for the entity and optionally its children. It provides a mapping of all ACLs for the given container/entity.

Important Note: This function returns the LOCAL sharing settings only, not the effective permissions that each Synapse User ID/Team has on the entities. More permissive permissions could be granted via a Team that the user has access to that has permissions on the entity, or through inheritance from parent entities.

PARAMETER DESCRIPTION
recursive

If True and the entity is a container (e.g., Project or Folder), recursively process child containers. Note that this must be used with include_container_content=True to have any effect. Setting recursive=True with include_container_content=False will raise a ValueError. Only works on classes that support the sync_from_synapse_async method.

TYPE: bool DEFAULT: False

include_container_content

If True, include ACLs from contents directly within containers (files and folders inside self). This must be set to True for recursive to have any effect. Defaults to False.

TYPE: bool DEFAULT: False

target_entity_types

Specify which entity types to process when listing ACLs. Allowed values are "folder" and "file" (case-insensitive). If None, defaults to ["folder", "file"].

TYPE: Optional[List[str]] DEFAULT: None

log_tree

If True, logs the ACL results to console in ASCII tree format showing entity hierarchies and their ACL permissions in a tree-like structure. Defaults to False.

TYPE: bool DEFAULT: False

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

_progress_bar

Internal parameter. Progress bar instance to use for updates when called recursively. Should not be used by external callers.

TYPE: Optional[tqdm] DEFAULT: None

RETURNS DESCRIPTION
AclListResult

An AclListResult object containing a structured representation of ACLs where:

AclListResult
  • entity_acls: A list of EntityAcl objects, each representing one entity's ACL
AclListResult
  • Each EntityAcl contains acl_entries (a list of AclEntry objects)
AclListResult
  • Each AclEntry contains the principal_id and their list of permissions
RAISES DESCRIPTION
ValueError

If the entity does not have an ID or if an invalid entity type is provided.

SynapseHTTPError

If there are permission issues accessing ACLs.

Exception

For any other errors that may occur during the process.

List ACLs for a single entity
from synapseclient import Synapse
from synapseclient.models import File

syn = Synapse()
syn.login()

acl_result = File(id="syn123").list_acl()
print(acl_result)

# Access entity ACLs (entity_acls is a list, not a dict)
for entity_acl in acl_result.all_entity_acls:
    if entity_acl.entity_id == "syn123":
        # Access individual ACL entries
        for acl_entry in entity_acl.acl_entries:
            if acl_entry.principal_id == "273948":
                print(f"Principal 273948 has permissions: {acl_entry.permissions}")

# I can also access the ACL for the file itself
print(acl_result.entity_acl)

print(acl_result)
List ACLs recursively for a folder and all its children
from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

acl_result = Folder(id="syn123").list_acl(
    recursive=True,
    include_container_content=True
)

# Access each entity's ACL (entity_acls is a list)
for entity_acl in acl_result.all_entity_acls:
    print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")

# I can also access the ACL for the folder itself
print(acl_result.entity_acl)

# List ACLs for only folder entities
folder_acl_result = Folder(id="syn123").list_acl(
    recursive=True,
    include_container_content=True,
    target_entity_types=["folder"]
)
List ACLs with ASCII tree visualization

When log_tree=True, the ACLs will be logged in a tree format. Additionally, the ascii_tree attribute of the AclListResult will contain the ASCII tree representation of the ACLs.

from synapseclient import Synapse
from synapseclient.models import Folder

syn = Synapse()
syn.login()

acl_result = Folder(id="syn123").list_acl(
    recursive=True,
    include_container_content=True,
    log_tree=True, # Enable ASCII tree logging
)

# The ASCII tree representation of the ACLs will also be available
# in acl_result.ascii_tree
print(acl_result.ascii_tree)
Source code in synapseclient/models/protocols/access_control_protocol.py
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
def list_acl(
    self,
    recursive: bool = False,
    include_container_content: bool = False,
    target_entity_types: Optional[List[str]] = None,
    log_tree: bool = False,
    *,
    synapse_client: Optional[Synapse] = None,
    _progress_bar: Optional[tqdm] = None,  # Internal parameter for recursive calls
) -> "AclListResult":
    """
    List the Access Control Lists (ACLs) for this entity and optionally its children.

    This function returns the local sharing settings for the entity and optionally
    its children. It provides a mapping of all ACLs for the given container/entity.

    **Important Note:** This function returns the LOCAL sharing settings only, not
    the effective permissions that each Synapse User ID/Team has on the entities.
    More permissive permissions could be granted via a Team that the user has access
    to that has permissions on the entity, or through inheritance from parent entities.

    Arguments:
        recursive: If True and the entity is a container (e.g., Project or Folder),
            recursively process child containers. Note that this must be used with
            include_container_content=True to have any effect. Setting recursive=True
            with include_container_content=False will raise a ValueError.
            Only works on classes that support the `sync_from_synapse_async` method.
        include_container_content: If True, include ACLs from contents directly within
            containers (files and folders inside self). This must be set to
            True for recursive to have any effect. Defaults to False.
        target_entity_types: Specify which entity types to process when listing ACLs.
            Allowed values are "folder" and "file" (case-insensitive).
            If None, defaults to ["folder", "file"].
        log_tree: If True, logs the ACL results to console in ASCII tree format showing
            entity hierarchies and their ACL permissions in a tree-like structure.
            Defaults to False.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.
        _progress_bar: Internal parameter. Progress bar instance to use for updates
            when called recursively. Should not be used by external callers.

    Returns:
        An AclListResult object containing a structured representation of ACLs where:
        - entity_acls: A list of EntityAcl objects, each representing one entity's ACL
        - Each EntityAcl contains acl_entries (a list of AclEntry objects)
        - Each AclEntry contains the principal_id and their list of permissions

    Raises:
        ValueError: If the entity does not have an ID or if an invalid entity type is provided.
        SynapseHTTPError: If there are permission issues accessing ACLs.
        Exception: For any other errors that may occur during the process.

    Example: List ACLs for a single entity
        ```python
        from synapseclient import Synapse
        from synapseclient.models import File

        syn = Synapse()
        syn.login()

        acl_result = File(id="syn123").list_acl()
        print(acl_result)

        # Access entity ACLs (entity_acls is a list, not a dict)
        for entity_acl in acl_result.all_entity_acls:
            if entity_acl.entity_id == "syn123":
                # Access individual ACL entries
                for acl_entry in entity_acl.acl_entries:
                    if acl_entry.principal_id == "273948":
                        print(f"Principal 273948 has permissions: {acl_entry.permissions}")

        # I can also access the ACL for the file itself
        print(acl_result.entity_acl)

        print(acl_result)

        ```

    Example: List ACLs recursively for a folder and all its children
        ```python
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        acl_result = Folder(id="syn123").list_acl(
            recursive=True,
            include_container_content=True
        )

        # Access each entity's ACL (entity_acls is a list)
        for entity_acl in acl_result.all_entity_acls:
            print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")

        # I can also access the ACL for the folder itself
        print(acl_result.entity_acl)

        # List ACLs for only folder entities
        folder_acl_result = Folder(id="syn123").list_acl(
            recursive=True,
            include_container_content=True,
            target_entity_types=["folder"]
        )
        ```

    Example: List ACLs with ASCII tree visualization
        When `log_tree=True`, the ACLs will be logged in a tree format. Additionally,
        the `ascii_tree` attribute of the AclListResult will contain the ASCII tree
        representation of the ACLs.

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Folder

        syn = Synapse()
        syn.login()

        acl_result = Folder(id="syn123").list_acl(
            recursive=True,
            include_container_content=True,
            log_tree=True, # Enable ASCII tree logging
        )

        # The ASCII tree representation of the ACLs will also be available
        # in acl_result.ascii_tree
        print(acl_result.ascii_tree)
        ```
    """
    return AclListResult()