tauri 3.0.0-alpha.3

Make tiny, secure apps for all desktop platforms with Tauri
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
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
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use std::collections::BTreeMap;
use std::fmt::{Debug, Display};
use std::sync::{Arc, Mutex, OnceLock};

use serde::de::DeserializeOwned;

#[cfg(feature = "dynamic-acl")]
use tauri_utils::acl::capability::CapabilityFile;
#[cfg(any(feature = "dynamic-acl", debug_assertions))]
use tauri_utils::acl::manifest::Manifest;
use tauri_utils::acl::{
  APP_ACL_KEY, ExecutionContext, Value,
  resolved::{Resolved, ResolvedCommand, ResolvedScope, ScopeKey},
};

use url::Url;

use crate::{AppHandle, Manager, StateManager, Webview};
use crate::{Runtime, ipc::InvokeError, sealed::ManagerBase};

use super::{CommandArg, CommandItem};

/// Materialized authority data derived from the resolved ACL.
///
/// Built lazily (see [`RuntimeAuthority::inner`]) because constructing it is the dominant cost
/// of `generate_context!`: the resolved ACL (`allowed_commands` / `denied_commands` / scopes for
/// every command) is emitted by `tauri-codegen` as a large literal built at runtime. It is only
/// needed at command-dispatch time, never during startup, so building it off-thread keeps that
/// cost off the startup critical path. Deep-link forwards exit without ever dispatching a
/// command, so they never block on the build: it runs on the background thread and is discarded
/// when the process exits.
struct RuntimeAuthorityInner {
  /// Raw ACL manifests. Only read on the command-denied error path
  /// ([`RuntimeAuthority::resolve_access_message`]) and by the `dynamic-acl` feature; dropped
  /// entirely in release builds.
  #[cfg(any(feature = "dynamic-acl", debug_assertions))]
  acl: BTreeMap<String, Manifest>,
  has_app_acl: bool,
  allowed_commands: BTreeMap<String, Vec<ResolvedCommand>>,
  denied_commands: BTreeMap<String, Vec<ResolvedCommand>>,
  scope_manager: ScopeManager,
}

/// `Send` inputs to a [`RuntimeAuthorityInner`], produced off-thread by
/// [`RuntimeAuthority::new_async`].
///
/// Only the expensive, `Send` data (the resolved ACL and raw manifests) is built on the
/// background thread; the empty `StateManager` scope caches are assembled on the consuming
/// thread in [`RuntimeAuthority::build_inner`] (they are not `Send` and are cheap to create).
struct ResolvedAcl {
  #[cfg(any(feature = "dynamic-acl", debug_assertions))]
  acl: BTreeMap<String, Manifest>,
  resolved: Resolved,
}

/// The runtime authority used to authorize IPC execution based on the Access Control List.
pub struct RuntimeAuthority {
  /// Materialized authority data. Populated eagerly by [`Self::new`] or lazily by
  /// [`Self::inner`], which joins the background builder on first access.
  inner: OnceLock<RuntimeAuthorityInner>,
  /// Lazy builder for [`Self::inner`]. `None` for the eager [`Self::new`] constructor.
  ///
  /// For [`Self::new_async`] it holds a *deferred* builder that is not started until
  /// [`Self::begin_build`] spawns it — after the runtime is created — so ACL construction stays
  /// off the startup critical path without racing runtime init. [`Self::inner`] consumes it
  /// (joining the thread, or building inline if it was never spawned) on first access.
  build: Option<Mutex<Option<AclBuild>>>,
}

/// Lazy-build state for [`RuntimeAuthority::inner`], held in [`RuntimeAuthority::build`].
enum AclBuild {
  /// Builder stored but not yet running. Spawned by [`RuntimeAuthority::begin_build`] once the
  /// runtime exists, or built inline by [`RuntimeAuthority::inner`] if the authority is read
  /// first.
  Deferred(Box<dyn FnOnce() -> ResolvedAcl + Send + 'static>),
  /// Building on a background thread; joined by [`RuntimeAuthority::inner`].
  Building(std::thread::JoinHandle<ResolvedAcl>),
}

/// The origin trying to access the IPC.
pub enum Origin {
  /// Local app origin.
  Local,
  /// Remote origin.
  Remote {
    /// Remote URL.
    url: Url,
  },
}

impl Display for Origin {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      Self::Local => write!(f, "local"),
      Self::Remote { url } => write!(f, "remote: {url}"),
    }
  }
}

impl Origin {
  fn matches(&self, context: &ExecutionContext) -> bool {
    match (self, context) {
      (Self::Local, ExecutionContext::Local) => true,
      (Self::Remote { url }, ExecutionContext::Remote { url: url_pattern }) => {
        url_pattern.test(url)
      }
      _ => false,
    }
  }
}

/// This is used internally by [`crate::generate_handler!`] for constructing [`RuntimeAuthority`]
/// to only include the raw ACL when it's needed
///
/// ## Stability
///
/// The output of this macro is managed internally by Tauri,
/// and should not be accessed directly on normal applications.
/// It may have breaking changes in the future.
#[cfg(any(feature = "dynamic-acl", debug_assertions))]
#[doc(hidden)]
#[macro_export]
macro_rules! runtime_authority {
  ($acl:expr, $resolved_acl:expr) => {
    // Build the (expensive) resolved ACL and raw ACL on a background thread; the first
    // command-authorization check blocks on the result. `|| $acl` / `|| $resolved_acl` are
    // non-capturing (both are emitted as compile-time literals), so they coerce to `fn`
    // pointers. This keeps ACL construction — the dominant cost of `generate_context!` — off
    // the startup critical path. See `RuntimeAuthority`.
    $crate::ipc::RuntimeAuthority::new_async(|| $acl, || $resolved_acl)
  };
}

/// This is used internally by [`crate::generate_handler!`] for constructing [`RuntimeAuthority`]
/// to only include the raw ACL when it's needed
///
/// ## Stability
///
/// The output of this macro is managed internally by Tauri,
/// and should not be accessed directly on normal applications.
/// It may have breaking changes in the future.
#[cfg(not(any(feature = "dynamic-acl", debug_assertions)))]
#[doc(hidden)]
#[macro_export]
macro_rules! runtime_authority {
  ($_acl:expr, $resolved_acl:expr) => {
    // Release builds drop the raw ACL entirely; only the resolved ACL is built, off-thread.
    $crate::ipc::RuntimeAuthority::new_async(|| $resolved_acl)
  };
}

impl RuntimeAuthority {
  /// Assembles [`RuntimeAuthorityInner`] from resolved ACL data.
  ///
  /// The expensive part (the [`Resolved`] literal) is already built; this only wires up the
  /// empty [`StateManager`] scope caches, so it is cheap and runs on the consuming thread.
  fn build_inner(resolved_acl: ResolvedAcl) -> RuntimeAuthorityInner {
    let ResolvedAcl {
      #[cfg(any(feature = "dynamic-acl", debug_assertions))]
      acl,
      resolved,
    } = resolved_acl;
    let command_cache = resolved
      .command_scope
      .keys()
      .map(|key| (*key, StateManager::new()))
      .collect();
    RuntimeAuthorityInner {
      #[cfg(any(feature = "dynamic-acl", debug_assertions))]
      acl,
      has_app_acl: resolved.has_app_acl,
      allowed_commands: resolved.allowed_commands,
      denied_commands: resolved.denied_commands,
      scope_manager: ScopeManager {
        command_scope: resolved.command_scope,
        global_scope: resolved.global_scope,
        command_cache,
        global_scope_cache: StateManager::new(),
      },
    }
  }

  /// Construct a new [`RuntimeAuthority`] from already-resolved ACL data (built eagerly).
  ///
  /// Prefer the [`runtime_authority`] macro, which builds the ACL lazily off-thread via
  /// [`Self::new_async`]. This eager constructor is for callers that already have the resolved
  /// ACL in hand (e.g. tests).
  #[doc(hidden)]
  pub fn new(
    #[cfg(any(feature = "dynamic-acl", debug_assertions))] acl: BTreeMap<String, Manifest>,
    resolved_acl: Resolved,
  ) -> Self {
    let inner = OnceLock::new();
    let _ = inner.set(Self::build_inner(ResolvedAcl {
      #[cfg(any(feature = "dynamic-acl", debug_assertions))]
      acl,
      resolved: resolved_acl,
    }));
    Self { inner, build: None }
  }

  /// Construct a new [`RuntimeAuthority`] whose resolved ACL is built lazily on a background
  /// thread.
  ///
  /// The resolved ACL (and raw ACL) is the dominant cost of `generate_context!`, yet it is only
  /// needed at command-dispatch time. Building it off-thread keeps it off the startup critical
  /// path; the first read via [`Self::inner`] (e.g. [`Self::resolve_access`]) blocks on the
  /// result. The [`runtime_authority`] macro passes non-capturing closures over compile-time
  /// literals; the `Send + 'static` bound also lets callers (e.g. tests) pass capturing
  /// closures.
  ///
  /// The builder is *stored, not spawned*: the background thread is started later by
  /// [`Self::begin_build`], once the runtime has been created. Spawning it eagerly here (at
  /// `generate_context!()` time) would let it allocate *during* runtime init, which is unsafe on
  /// runtimes that replace the process allocator in `new` — CEF loads the Chromium framework,
  /// swapping macOS's default `malloc` zone, and an allocation racing that swap corrupts the
  /// heap and crashes at startup. Deferring the spawn keeps the off-thread win (the build
  /// overlaps webview creation and frontend boot) without the race.
  ///
  /// The thread spawn + join is pure overhead for trivial ACLs (e.g. tests and small apps), so
  /// this only pays off above a non-trivial resolved-ACL size; the size is not known until the
  /// ACL is built, so the trade-off cannot be gated at runtime. Use [`Self::new`] when the
  /// resolved ACL is already in hand and the overhead is not worth it.
  ///
  /// **Please prefer using the [`runtime_authority`] macro instead of calling this directly**
  #[doc(hidden)]
  pub fn new_async(
    #[cfg(any(feature = "dynamic-acl", debug_assertions))] acl_builder: impl FnOnce() -> BTreeMap<
      String,
      Manifest,
    > + Send
    + 'static,
    resolved_builder: impl FnOnce() -> Resolved + Send + 'static,
  ) -> Self {
    let builder: Box<dyn FnOnce() -> ResolvedAcl + Send + 'static> =
      Box::new(move || ResolvedAcl {
        #[cfg(any(feature = "dynamic-acl", debug_assertions))]
        acl: acl_builder(),
        resolved: resolved_builder(),
      });
    Self {
      inner: OnceLock::new(),
      build: Some(Mutex::new(Some(AclBuild::Deferred(builder)))),
    }
  }

  /// Spawns the resolved-ACL builder on a dedicated background thread.
  fn spawn_builder(
    builder: Box<dyn FnOnce() -> ResolvedAcl + Send + 'static>,
  ) -> std::thread::JoinHandle<ResolvedAcl> {
    std::thread::Builder::new()
      .name(String::from("tauri runtime authority"))
      // The resolved-ACL literal construction is deep; give it the headroom the generated
      // context-creation thread used to need (it no longer constructs the ACL inline).
      .stack_size(8 * 1024 * 1024)
      .spawn(builder)
      .expect("failed to spawn runtime authority builder thread")
  }

  /// Starts the deferred resolved-ACL build on a background thread, if it has not started yet.
  ///
  /// Called once the runtime has been created (see [`crate::Builder::build`]). Deferring the
  /// spawn to here — rather than eagerly in [`Self::new_async`] — keeps ACL construction off the
  /// startup critical path (it overlaps webview creation and frontend boot) while guaranteeing
  /// no builder thread allocates *during* runtime init, which would race the allocator swap that
  /// CEF performs when it loads the Chromium framework and crash at startup. No-op for the eager
  /// [`Self::new`] constructor or once the build has started; [`Self::inner`] joins it on first
  /// access.
  pub(crate) fn begin_build(&self) {
    let Some(build) = self.build.as_ref() else {
      return;
    };
    let mut guard = build.lock().unwrap();
    match guard.take() {
      Some(AclBuild::Deferred(builder)) => {
        *guard = Some(AclBuild::Building(Self::spawn_builder(builder)));
      }
      // Already building, or already consumed by `inner()`: put it back untouched.
      other => *guard = other,
    }
  }

  /// Returns the materialized authority data, blocking on the background builder on first
  /// access if this authority was constructed via [`Self::new_async`].
  fn inner(&self) -> &RuntimeAuthorityInner {
    self.inner.get_or_init(|| {
      let build = self
        .build
        .as_ref()
        .expect("runtime authority has neither resolved data nor a builder")
        .lock()
        .unwrap()
        .take()
        // Taken exactly once. If it is already gone while `inner` is still unset, a previous
        // `inner()` call took it and panicked, so report that rather than the misleading
        // "neither data nor builder".
        .expect("runtime authority builder thread panicked");
      let handle = match build {
        AclBuild::Building(handle) => handle,
        // `begin_build` never ran (the authority was read before the runtime was created); build
        // it now on a big-stack thread, matching the deferred path's headroom.
        AclBuild::Deferred(builder) => Self::spawn_builder(builder),
      };
      let resolved_acl = handle
        .join()
        .expect("runtime authority builder thread panicked");
      Self::build_inner(resolved_acl)
    })
  }

  /// Mutable access to the materialized authority data, materializing it first if needed.
  fn inner_mut(&mut self) -> &mut RuntimeAuthorityInner {
    // Force materialization (the returned shared borrow ends immediately), then hand out `&mut`.
    let _ = self.inner();
    self
      .inner
      .get_mut()
      .expect("runtime authority materialized above")
  }

  /// The scope manager, materializing the authority data first if needed.
  pub(crate) fn scope_manager(&self) -> &ScopeManager {
    &self.inner().scope_manager
  }

  pub(crate) fn has_app_manifest(&self) -> bool {
    self.inner().has_app_acl
  }

  #[doc(hidden)]
  pub fn __allow_command(&mut self, command: String, context: ExecutionContext) {
    self.inner_mut().allowed_commands.insert(
      command,
      vec![ResolvedCommand {
        context,
        windows: vec!["*".parse().unwrap()],
        ..Default::default()
      }],
    );
  }

  /// Adds the given capability to the runtime authority.
  #[cfg(feature = "dynamic-acl")]
  pub fn add_capability(&mut self, capability: impl super::RuntimeCapability) -> crate::Result<()> {
    self.add_capability_inner(capability.build())
  }

  #[cfg(feature = "dynamic-acl")]
  fn add_capability_inner(&mut self, capability: CapabilityFile) -> crate::Result<()> {
    let mut capabilities = BTreeMap::new();
    match capability {
      CapabilityFile::Capability(c) => {
        capabilities.insert(c.identifier.clone(), c);
      }

      CapabilityFile::List(capabilities_list)
      | CapabilityFile::NamedList {
        capabilities: capabilities_list,
      } => {
        capabilities.extend(
          capabilities_list
            .into_iter()
            .map(|c| (c.identifier.clone(), c)),
        );
      }
    }

    // Resolve against the raw ACL (materializes the authority) before taking `&mut` below.
    let resolved = Resolved::resolve_with_base_scope_id(
      &self.inner().acl,
      capabilities,
      tauri_utils::platform::Target::current(),
      self.scope_manager().last_scope_id(),
    )
    .unwrap();

    let inner = self.inner_mut();

    // fill global scope
    for (plugin, global_scope) in resolved.global_scope {
      let global_scope_entry = inner.scope_manager.global_scope.entry(plugin).or_default();

      global_scope_entry.allow.extend(global_scope.allow);
      global_scope_entry.deny.extend(global_scope.deny);

      inner.scope_manager.global_scope_cache = StateManager::new();
    }

    // fill command scope
    // the scope ids were assigned past the existing ones, so these are all new entries
    for (scope_id, command_scope) in resolved.command_scope {
      inner
        .scope_manager
        .command_cache
        .entry(scope_id)
        .or_insert_with(StateManager::new);
      inner
        .scope_manager
        .command_scope
        .insert(scope_id, command_scope);
    }

    // denied commands
    for (cmd_key, resolved_cmds) in resolved.denied_commands {
      let entry = inner.denied_commands.entry(cmd_key).or_default();
      entry.extend(resolved_cmds);
    }

    // allowed commands
    for (cmd_key, resolved_cmds) in resolved.allowed_commands {
      let entry = inner.allowed_commands.entry(cmd_key).or_default();
      entry.extend(resolved_cmds);
    }

    Ok(())
  }

  #[cfg(debug_assertions)]
  pub(crate) fn resolve_access_message(
    &self,
    key: &str,
    command_name: &str,
    window: &str,
    webview: &str,
    origin: &Origin,
  ) -> String {
    fn print_references(resolved: &[ResolvedCommand]) -> String {
      resolved
        .iter()
        .map(|r| {
          format!(
            "capability: {}, permission: {}",
            r.referenced_by.capability, r.referenced_by.permission
          )
        })
        .collect::<Vec<_>>()
        .join(" || ")
    }

    fn print_allowed_on(resolved: &[ResolvedCommand]) -> String {
      if resolved.is_empty() {
        "command not allowed on any window/webview/URL context".to_string()
      } else {
        let mut s = "allowed on: ".to_string();

        let last_index = resolved.len() - 1;
        for (index, cmd) in resolved.iter().enumerate() {
          let windows = cmd
            .windows
            .iter()
            .map(|w| format!("\"{}\"", w.as_str()))
            .collect::<Vec<_>>()
            .join(", ");
          let webviews = cmd
            .webviews
            .iter()
            .map(|w| format!("\"{}\"", w.as_str()))
            .collect::<Vec<_>>()
            .join(", ");

          s.push('[');

          if !windows.is_empty() {
            s.push_str(&format!("windows: {windows}, "));
          }

          if !webviews.is_empty() {
            s.push_str(&format!("webviews: {webviews}, "));
          }

          match &cmd.context {
            ExecutionContext::Local => s.push_str("URL: local"),
            ExecutionContext::Remote { url } => s.push_str(&format!("URL: {}", url.as_str())),
          }

          s.push(']');

          if index != last_index {
            s.push_str(", ");
          }
        }

        s
      }
    }

    fn has_permissions_allowing_command(
      manifest: &Manifest,
      set: &crate::utils::acl::PermissionSet,
      command: &str,
      allow_wildcard: bool,
    ) -> bool {
      for permission_id in &set.permissions {
        if permission_id == "default" {
          if let Some(default) = &manifest.default_permission
            && has_permissions_allowing_command(manifest, default, command, allow_wildcard)
          {
            return true;
          }
        } else if let Some(ref_set) = manifest.permission_sets.get(permission_id)
          && has_permissions_allowing_command(manifest, ref_set, command, allow_wildcard)
        {
          return true;
        } else if let Some(permission) = manifest.permissions.get(permission_id)
          && permission.commands.allow.contains(&command.into())
        {
          return true;
        } else if let Some(permission) = manifest.command_permission(permission_id, allow_wildcard)
        {
          // `*` is the wildcard command produced by the `allow-*` permission
          if permission
            .commands
            .allow
            .iter()
            .any(|c| c == command || c == "*")
          {
            return true;
          }
        }
      }
      false
    }

    let command = if key == APP_ACL_KEY {
      command_name.to_string()
    } else {
      format!("plugin:{key}|{command_name}")
    };

    let command_pretty_name = if key == APP_ACL_KEY {
      command_name.to_string()
    } else {
      format!("{key}.{command_name}")
    };

    // Materialize the authority once; everything below reads the resolved ACL.
    let inner = self.inner();

    let denied_on_origin = inner
      .denied_on(&command, origin)
      .cloned()
      .collect::<Vec<_>>();

    if !denied_on_origin.is_empty() {
      format!(
        "{command_pretty_name} explicitly denied on origin {origin}\n\nreferenced by: {}",
        print_references(&denied_on_origin)
      )
    } else {
      let command_matches = inner.allowed_commands.get(&command);

      if let Some(resolved) = inner.allowed_commands.get(&command) {
        let resolved_matching_origin = resolved
          .iter()
          .filter(|cmd| origin.matches(&cmd.context))
          .collect::<Vec<&ResolvedCommand>>();
        if resolved_matching_origin
          .iter()
          .any(|cmd| cmd.webviews.iter().any(|w| w.matches(webview)))
          || resolved_matching_origin
            .iter()
            .any(|cmd| cmd.windows.iter().any(|w| w.matches(window)))
        {
          "allowed".to_string()
        } else {
          format!(
            "{command_pretty_name} not allowed on window \"{window}\", webview \"{webview}\", URL: {}\n\n{}\n\nreferenced by: {}",
            match origin {
              Origin::Local => "local",
              Origin::Remote { url } => url.as_str(),
            },
            print_allowed_on(resolved),
            print_references(resolved)
          )
        }
      } else {
        let permission_error_detail = if let Some((key, manifest)) = inner
          .acl
          .get_key_value(key)
          .or_else(|| inner.acl.get_key_value(&format!("core:{key}")))
        {
          let mut permissions_referencing_command = Vec::new();

          // the `allow-*`/`deny-*` wildcards are only available for the app manifest
          let allow_wildcard = key == APP_ACL_KEY;

          if let Some(default) = &manifest.default_permission
            && has_permissions_allowing_command(manifest, default, command_name, allow_wildcard)
          {
            permissions_referencing_command.push("default".into());
          }
          for set in manifest.permission_sets.values() {
            if has_permissions_allowing_command(manifest, set, command_name, allow_wildcard) {
              permissions_referencing_command.push(set.identifier.clone());
            }
          }
          for permission in manifest.permissions.values() {
            if permission.commands.allow.contains(&command_name.into()) {
              permissions_referencing_command.push(permission.identifier.clone());
            }
          }
          if manifest.commands.iter().any(|c| c == command_name) {
            permissions_referencing_command
              .push(format!("allow-{}", command_name.replace('_', "-")));
          }
          if allow_wildcard && !manifest.commands.is_empty() {
            permissions_referencing_command.push("allow-*".to_string());
          }

          permissions_referencing_command.sort();

          let associated_permissions = permissions_referencing_command
            .into_iter()
            .map(|permission| {
              if key == APP_ACL_KEY {
                permission
              } else {
                format!("{key}:{permission}")
              }
            })
            .collect::<Vec<_>>()
            .join(", ");

          if associated_permissions.is_empty() {
            "Command not found".to_string()
          } else {
            format!("Permissions associated with this command: {associated_permissions}")
          }
        } else {
          "Plugin not found".to_string()
        };

        if let Some(resolved_cmds) = command_matches {
          format!(
            "{command_pretty_name} not allowed on origin [{origin}]. Please create a capability that has this origin on the context field.\n\nFound matches for: {}\n\n{permission_error_detail}",
            resolved_cmds
              .iter()
              .map(|resolved| {
                let context = match &resolved.context {
                  ExecutionContext::Local => "[local]".to_string(),
                  ExecutionContext::Remote { url } => format!("[remote: {}]", url.as_str()),
                };
                format!(
                  "- context: {context}, referenced by: capability: {}, permission: {}",
                  resolved.referenced_by.capability, resolved.referenced_by.permission
                )
              })
              .collect::<Vec<_>>()
              .join("\n")
          )
        } else {
          format!("{command_pretty_name} not allowed. {permission_error_detail}")
        }
      }
    }
  }

  /// Checks if the given IPC execution is allowed and returns the [`ResolvedCommand`] if it is.
  ///
  /// A command is denied when a capability that denies it matches the given origin
  /// (execution context), window and webview labels are not taken into account for denial.
  pub fn resolve_access(
    &self,
    command: &str,
    window: &str,
    webview: &str,
    origin: &Origin,
  ) -> Option<Vec<ResolvedCommand>> {
    // First command dispatch blocks here if the resolved ACL is still building on the
    // background thread (see `RuntimeAuthority::new_async`); subsequent calls are cached.
    let inner = self.inner();
    if inner.is_denied(command, origin) {
      return None;
    }
    // the `allow-*` wildcard permission resolves to a single `*` command (per manifest)
    // instead of one entry per command, so we also look the command up under its wildcard key.
    let wildcard = wildcard_command(command);
    let resolved_cmds = inner
      .allowed_commands
      .get(command)
      .into_iter()
      .chain(inner.allowed_commands.get(&wildcard))
      .flatten()
      .filter(|cmd| {
        origin.matches(&cmd.context)
          && (cmd.webviews.iter().any(|w| w.matches(webview))
            || cmd.windows.iter().any(|w| w.matches(window)))
      })
      .cloned()
      .collect::<Vec<_>>();
    if resolved_cmds.is_empty() {
      None
    } else {
      Some(resolved_cmds)
    }
  }
}

impl RuntimeAuthorityInner {
  /// Returns the deny entries of the given command whose execution context matches the given origin.
  ///
  /// Deny entries carry the [`ExecutionContext`] of the capability that defined them,
  /// so a command denied by a remote capability is not denied for the local app and vice-versa.
  ///
  /// The `deny-*` wildcard permission resolves to a single `*` command (per manifest),
  /// so the command is also looked up under its wildcard key.
  fn denied_on<'a>(
    &'a self,
    command: &str,
    origin: &'a Origin,
  ) -> impl Iterator<Item = &'a ResolvedCommand> + use<'a> {
    self
      .denied_commands
      .get(command)
      .into_iter()
      .chain(self.denied_commands.get(&wildcard_command(command)))
      .flatten()
      .filter(move |cmd| origin.matches(&cmd.context))
  }

  /// Checks if the given command is explicitly denied for the given origin.
  fn is_denied(&self, command: &str, origin: &Origin) -> bool {
    self.denied_on(command, origin).next().is_some()
  }
}

/// The wildcard command key that matches every command of the same manifest:
/// `*` for app commands and `plugin:$name|*` for plugin commands.
///
/// Used to resolve the implicit `allow-*`/`deny-*` permissions without expanding them
/// into one entry per command in the resolved ACL.
fn wildcard_command(command: &str) -> String {
  match command.rsplit_once('|') {
    Some((prefix, _)) => format!("{prefix}|*"),
    None => "*".to_string(),
  }
}

/// List of allowed and denied objects that match either the command-specific or plugin global scope criteria.
#[derive(Debug)]
pub struct ScopeValue<T: ScopeObject> {
  allow: Arc<Vec<Arc<T>>>,
  deny: Arc<Vec<Arc<T>>>,
}

impl<T: ScopeObject> ScopeValue<T> {
  fn clone(&self) -> Self {
    Self {
      allow: self.allow.clone(),
      deny: self.deny.clone(),
    }
  }

  /// What this access scope allows.
  pub fn allows(&self) -> &Vec<Arc<T>> {
    &self.allow
  }

  /// What this access scope denies.
  pub fn denies(&self) -> &Vec<Arc<T>> {
    &self.deny
  }
}

/// Access scope for a command that can be retrieved directly in the command function.
#[derive(Debug)]
pub struct CommandScope<T: ScopeObject> {
  allow: Vec<Arc<T>>,
  deny: Vec<Arc<T>>,
}

impl<T: ScopeObject> CommandScope<T> {
  pub(crate) fn resolve<R: Runtime>(
    webview: &Webview<R>,
    scope_ids: Vec<u64>,
  ) -> crate::Result<Self> {
    let mut allow = Vec::new();
    let mut deny = Vec::new();

    for scope_id in scope_ids {
      let scope = webview
        .manager()
        .runtime_authority
        .lock()
        .unwrap()
        .scope_manager()
        .get_command_scope_typed::<R, T>(webview.app_handle(), &scope_id)?;

      for s in scope.allows() {
        allow.push(s.clone());
      }
      for s in scope.denies() {
        deny.push(s.clone());
      }
    }

    Ok(CommandScope { allow, deny })
  }

  /// What this access scope allows.
  pub fn allows(&self) -> &Vec<Arc<T>> {
    &self.allow
  }

  /// What this access scope denies.
  pub fn denies(&self) -> &Vec<Arc<T>> {
    &self.deny
  }
}

impl<T: ScopeObjectMatch> CommandScope<T> {
  /// Ensure all deny scopes were not matched and any allow scopes were.
  ///
  /// This **WILL** return `true` if the allow scopes are empty and the deny
  /// scopes did not trigger. If you require at least one allow scope, then
  /// ensure the allow scopes are not empty before calling this method.
  ///
  /// ```
  /// # use tauri::ipc::CommandScope;
  /// # fn command(scope: CommandScope<()>) -> Result<(), &'static str> {
  /// if scope.allows().is_empty() {
  ///   return Err("you need to specify at least 1 allow scope!");
  /// }
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Example
  ///
  /// ```
  /// # use serde::{Serialize, Deserialize};
  /// # use url::Url;
  /// # use tauri::{ipc::{CommandScope, ScopeObjectMatch}, command};
  /// #
  /// #[derive(Debug, Clone, Serialize, Deserialize)]
  /// # pub struct Scope;
  /// #
  /// # impl ScopeObjectMatch for Scope {
  /// #   type Input = str;
  /// #
  /// #   fn matches(&self, input: &str) -> bool {
  /// #     true
  /// #   }
  /// # }
  /// #
  /// # fn do_work(_: String) -> Result<String, &'static str> {
  /// #   Ok("Output".into())
  /// # }
  /// #
  /// #[command]
  /// fn my_command(scope: CommandScope<Scope>, input: String) -> Result<String, &'static str> {
  ///   if scope.matches(&input) {
  ///     do_work(input)
  ///   } else {
  ///     Err("Scope didn't match input")
  ///   }
  /// }
  /// ```
  pub fn matches(&self, input: &T::Input) -> bool {
    // first make sure the input doesn't match any existing deny scope
    if self.deny.iter().any(|s| s.matches(input)) {
      return false;
    }

    // if there are allow scopes, ensure the input matches at least 1
    if self.allow.is_empty() {
      true
    } else {
      self.allow.iter().any(|s| s.matches(input))
    }
  }
}

impl<'a, R: Runtime, T: ScopeObject> CommandArg<'a, R> for CommandScope<T> {
  /// Grabs the [`ResolvedScope`] from the [`CommandItem`] and returns the associated [`CommandScope`].
  fn from_command(command: CommandItem<'a, R>) -> Result<Self, InvokeError> {
    if let Some(resolved) = &command.acl {
      let scope_ids = resolved
        .iter()
        .filter_map(|cmd| cmd.scope_id)
        .collect::<Vec<_>>();
      CommandScope::resolve(&command.message.webview, scope_ids).map_err(Into::into)
    } else {
      Ok(CommandScope {
        allow: Default::default(),
        deny: Default::default(),
      })
    }
  }
}

/// Global access scope that can be retrieved directly in the command function.
#[derive(Debug)]
pub struct GlobalScope<T: ScopeObject>(ScopeValue<T>);

impl<T: ScopeObject> GlobalScope<T> {
  pub(crate) fn resolve<R: Runtime>(webview: &Webview<R>, plugin: &str) -> crate::Result<Self> {
    webview
      .manager()
      .runtime_authority
      .lock()
      .unwrap()
      .scope_manager()
      .get_global_scope_typed(webview.app_handle(), plugin)
      .map(Self)
  }

  /// What this access scope allows.
  pub fn allows(&self) -> &Vec<Arc<T>> {
    &self.0.allow
  }

  /// What this access scope denies.
  pub fn denies(&self) -> &Vec<Arc<T>> {
    &self.0.deny
  }
}

impl<'a, R: Runtime, T: ScopeObject> CommandArg<'a, R> for GlobalScope<T> {
  /// Grabs the [`ResolvedScope`] from the [`CommandItem`] and returns the associated [`GlobalScope`].
  fn from_command(command: CommandItem<'a, R>) -> Result<Self, InvokeError> {
    GlobalScope::resolve(
      &command.message.webview,
      command.plugin.unwrap_or(APP_ACL_KEY),
    )
    .map_err(InvokeError::from_error)
  }
}

#[derive(Debug)]
pub struct ScopeManager {
  command_scope: BTreeMap<ScopeKey, ResolvedScope>,
  global_scope: BTreeMap<String, ResolvedScope>,
  command_cache: BTreeMap<ScopeKey, StateManager>,
  global_scope_cache: StateManager,
}

/// Marks a type as a scope object.
///
/// Usually you will just rely on [`serde::de::DeserializeOwned`] instead of implementing it manually,
/// though this is useful if you need to do some initialization logic on the type itself.
pub trait ScopeObject: Sized + Send + Sync + Debug + 'static {
  /// The error type.
  type Error: std::error::Error + Send + Sync;
  /// Deserialize the raw scope value.
  fn deserialize<R: Runtime>(app: &AppHandle<R>, raw: Value) -> Result<Self, Self::Error>;
}

impl<T: Send + Sync + Debug + DeserializeOwned + 'static> ScopeObject for T {
  type Error = serde_json::Error;
  fn deserialize<R: Runtime>(_app: &AppHandle<R>, raw: Value) -> Result<Self, Self::Error> {
    serde_json::from_value(raw.into())
  }
}

/// A [`ScopeObject`] whose validation can be represented as a `bool`.
///
/// # Example
///
/// ```
/// # use serde::{Deserialize, Serialize};
/// # use tauri::{ipc::ScopeObjectMatch, Url};
/// #
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// #[serde(rename_all = "camelCase")]
/// pub enum Scope {
///   Domain(Url),
///   StartsWith(String),
/// }
///
/// impl ScopeObjectMatch for Scope {
///   type Input = str;
///
///   fn matches(&self, input: &str) -> bool {
///     match self {
///       Scope::Domain(url) => {
///         let parsed: Url = match input.parse() {
///           Ok(parsed) => parsed,
///           Err(_) => return false,
///         };
///
///         let domain = parsed.domain();
///
///         domain.is_some() && domain == url.domain()
///       }
///       Scope::StartsWith(start) => input.starts_with(start),
///     }
///   }
/// }
/// ```
pub trait ScopeObjectMatch: ScopeObject {
  /// The type of input expected to validate against the scope.
  ///
  /// This will be borrowed, so if you want to match on a `&str` this type should be `str`.
  type Input: ?Sized;

  /// Check if the input matches against the scope.
  fn matches(&self, input: &Self::Input) -> bool;
}

impl ScopeManager {
  /// The highest assigned command scope id, or `0` if there are none.
  #[cfg(feature = "dynamic-acl")]
  fn last_scope_id(&self) -> ScopeKey {
    self.command_scope.keys().next_back().copied().unwrap_or(0)
  }

  pub(crate) fn get_global_scope_typed<R: Runtime, T: ScopeObject>(
    &self,
    app: &AppHandle<R>,
    key: &str,
  ) -> crate::Result<ScopeValue<T>> {
    match self.global_scope_cache.try_get::<ScopeValue<T>>() {
      Some(cached) => Ok((*cached).clone()),
      None => {
        let mut allow = Vec::new();
        let mut deny = Vec::new();

        if let Some(global_scope) = self.global_scope.get(key) {
          for allowed in &global_scope.allow {
            allow
              .push(Arc::new(T::deserialize(app, allowed.clone()).map_err(
                |e| crate::Error::CannotDeserializeScope(Box::new(e)),
              )?));
          }
          for denied in &global_scope.deny {
            deny
              .push(Arc::new(T::deserialize(app, denied.clone()).map_err(
                |e| crate::Error::CannotDeserializeScope(Box::new(e)),
              )?));
          }
        }

        let scope = ScopeValue {
          allow: Arc::new(allow),
          deny: Arc::new(deny),
        };
        self.global_scope_cache.set(scope.clone());
        Ok(scope)
      }
    }
  }

  fn get_command_scope_typed<R: Runtime, T: ScopeObject>(
    &self,
    app: &AppHandle<R>,
    key: &ScopeKey,
  ) -> crate::Result<ScopeValue<T>> {
    let cache = self.command_cache.get(key).unwrap();
    match cache.try_get::<ScopeValue<T>>() {
      Some(cached) => Ok((*cached).clone()),
      None => {
        let resolved_scope = self
          .command_scope
          .get(key)
          .unwrap_or_else(|| panic!("missing command scope for key {key}"));

        let mut allow = Vec::new();
        let mut deny = Vec::new();

        for allowed in &resolved_scope.allow {
          allow
            .push(Arc::new(T::deserialize(app, allowed.clone()).map_err(
              |e| crate::Error::CannotDeserializeScope(Box::new(e)),
            )?));
        }
        for denied in &resolved_scope.deny {
          deny
            .push(Arc::new(T::deserialize(app, denied.clone()).map_err(
              |e| crate::Error::CannotDeserializeScope(Box::new(e)),
            )?));
        }

        let value = ScopeValue {
          allow: Arc::new(allow),
          deny: Arc::new(deny),
        };

        let _ = cache.set(value.clone());
        Ok(value)
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use glob::Pattern;
  use tauri_utils::acl::{
    ExecutionContext,
    resolved::{Resolved, ResolvedCommand},
  };

  use crate::ipc::Origin;

  use super::RuntimeAuthority;

  #[test]
  fn window_glob_pattern_matches() {
    let command = "my-command";
    let window = "main-*";
    let webview = "other-*";

    let resolved_cmd = vec![ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      ..Default::default()
    }];
    let allowed_commands = [(command.to_string(), resolved_cmd.clone())]
      .into_iter()
      .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        ..Default::default()
      },
    );

    assert_eq!(
      authority.resolve_access(
        command,
        &window.replace('*', "something"),
        webview,
        &Origin::Local
      ),
      Some(resolved_cmd)
    );
  }

  #[test]
  fn wildcard_command_allows_any_app_command() {
    let window = "main";
    let webview = "main";

    // a single `*` entry stands in for every app command (the `allow-*` permission)
    let resolved_cmd = vec![ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      ..Default::default()
    }];
    let allowed_commands = [("*".to_string(), resolved_cmd.clone())]
      .into_iter()
      .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        ..Default::default()
      },
    );

    // an arbitrary app command (never listed explicitly) is allowed through the wildcard entry
    assert_eq!(
      authority.resolve_access("some_command", window, webview, &Origin::Local),
      Some(resolved_cmd.clone())
    );
    assert_eq!(
      authority.resolve_access("another_command", window, webview, &Origin::Local),
      Some(resolved_cmd)
    );

    // plugin commands use a per-plugin wildcard key, so the app wildcard does not allow them
    assert!(
      authority
        .resolve_access("plugin:fs|read", window, webview, &Origin::Local)
        .is_none()
    );
  }

  #[test]
  fn webview_glob_pattern_matches() {
    let command = "my-command";
    let window = "other-*";
    let webview = "main-*";

    let resolved_cmd = vec![ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      webviews: vec![Pattern::new(webview).unwrap()],
      ..Default::default()
    }];
    let allowed_commands = [(command.to_string(), resolved_cmd.clone())]
      .into_iter()
      .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        ..Default::default()
      },
    );

    assert_eq!(
      authority.resolve_access(
        command,
        window,
        &webview.replace('*', "something"),
        &Origin::Local
      ),
      Some(resolved_cmd)
    );
  }

  #[test]
  fn remote_domain_matches() {
    let url = "https://tauri.app";
    let command = "my-command";
    let window = "main";
    let webview = "main";

    let resolved_cmd = vec![ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      context: ExecutionContext::Remote {
        url: url.parse().unwrap(),
      },
      ..Default::default()
    }];
    let allowed_commands = [(command.to_string(), resolved_cmd.clone())]
      .into_iter()
      .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        ..Default::default()
      },
    );

    assert_eq!(
      authority.resolve_access(
        command,
        window,
        webview,
        &Origin::Remote {
          url: url.parse().unwrap()
        }
      ),
      Some(resolved_cmd)
    );
  }

  #[test]
  fn remote_domain_glob_pattern_matches() {
    let url = "http://tauri.*";
    let command = "my-command";
    let window = "main";
    let webview = "main";

    let resolved_cmd = vec![ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      context: ExecutionContext::Remote {
        url: url.parse().unwrap(),
      },
      ..Default::default()
    }];
    let allowed_commands = [(command.to_string(), resolved_cmd.clone())]
      .into_iter()
      .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        ..Default::default()
      },
    );

    assert_eq!(
      authority.resolve_access(
        command,
        window,
        webview,
        &Origin::Remote {
          url: url.replace('*', "studio").parse().unwrap()
        }
      ),
      Some(resolved_cmd)
    );
  }

  #[test]
  fn remote_context_denied() {
    let command = "my-command";
    let window = "main";
    let webview = "main";

    let resolved_cmd = vec![ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      ..Default::default()
    }];
    let allowed_commands = [(command.to_string(), resolved_cmd)].into_iter().collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        ..Default::default()
      },
    );

    assert!(
      authority
        .resolve_access(
          command,
          window,
          webview,
          &Origin::Remote {
            url: "https://tauri.app".parse().unwrap()
          }
        )
        .is_none()
    );
  }

  #[test]
  fn denied_command_takes_precedence() {
    let command = "my-command";
    let window = "main";
    let webview = "main";
    let windows = vec![Pattern::new(window).unwrap()];
    let allowed_commands = [(
      command.to_string(),
      vec![ResolvedCommand {
        windows: windows.clone(),
        ..Default::default()
      }],
    )]
    .into_iter()
    .collect();
    let denied_commands = [(
      command.to_string(),
      vec![ResolvedCommand {
        windows,
        ..Default::default()
      }],
    )]
    .into_iter()
    .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        denied_commands,
        ..Default::default()
      },
    );

    assert!(
      authority
        .resolve_access(command, window, webview, &Origin::Local)
        .is_none()
    );
  }

  #[test]
  fn denied_command_is_scoped_to_the_execution_context() {
    let url = "https://tauri.app";
    let command = "my-command";
    let window = "main";
    let webview = "main";
    let windows = vec![Pattern::new(window).unwrap()];

    // the command is allowed on both the local app and the remote URL
    let allowed_commands = [(
      command.to_string(),
      vec![
        ResolvedCommand {
          windows: windows.clone(),
          ..Default::default()
        },
        ResolvedCommand {
          windows: windows.clone(),
          context: ExecutionContext::Remote {
            url: url.parse().unwrap(),
          },
          ..Default::default()
        },
      ],
    )]
    .into_iter()
    .collect();

    // but it is only denied on the remote URL
    let denied_commands = [(
      command.to_string(),
      vec![ResolvedCommand {
        windows,
        context: ExecutionContext::Remote {
          url: url.parse().unwrap(),
        },
        ..Default::default()
      }],
    )]
    .into_iter()
    .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        denied_commands,
        ..Default::default()
      },
    );

    // the remote origin the deny entry was defined for is denied
    assert!(
      authority
        .resolve_access(
          command,
          window,
          webview,
          &Origin::Remote {
            url: url.parse().unwrap()
          }
        )
        .is_none()
    );

    // the local app must not be affected by a deny entry of a remote capability
    let resolved = authority
      .resolve_access(command, window, webview, &Origin::Local)
      .expect("local origin must not be denied by a remote capability");
    assert_eq!(resolved.len(), 1);
    assert_eq!(resolved[0].context, ExecutionContext::Local);
  }

  #[test]
  fn denied_command_on_local_context_does_not_deny_remote() {
    let url = "https://tauri.app";
    let command = "my-command";
    let window = "main";
    let webview = "main";
    let windows = vec![Pattern::new(window).unwrap()];

    // the command is allowed on both the local app and the remote URL
    let allowed_commands = [(
      command.to_string(),
      vec![
        ResolvedCommand {
          windows: windows.clone(),
          ..Default::default()
        },
        ResolvedCommand {
          windows: windows.clone(),
          context: ExecutionContext::Remote {
            url: url.parse().unwrap(),
          },
          ..Default::default()
        },
      ],
    )]
    .into_iter()
    .collect();

    // but it is only denied on the local app
    let denied_commands = [(
      command.to_string(),
      vec![ResolvedCommand {
        windows,
        ..Default::default()
      }],
    )]
    .into_iter()
    .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        denied_commands,
        ..Default::default()
      },
    );

    // the remote origin must not be affected by a deny entry of a local capability
    let resolved = authority
      .resolve_access(
        command,
        window,
        webview,
        &Origin::Remote {
          url: url.parse().unwrap(),
        },
      )
      .expect("remote origin must not be denied by a local capability");
    assert_eq!(resolved.len(), 1);
    assert_eq!(
      resolved[0].context,
      ExecutionContext::Remote {
        url: url.parse().unwrap()
      }
    );

    // the local app is denied even though it has an allow entry
    assert!(
      authority
        .resolve_access(command, window, webview, &Origin::Local)
        .is_none()
    );
  }

  #[cfg(debug_assertions)]
  #[test]
  fn resolve_access_message_denied_on_origin() {
    use tauri_utils::acl::resolved::ResolvedCommandReference;

    let plugin_name = "myplugin";
    let command_name = "my-command";
    let command = format!("plugin:{plugin_name}|{command_name}");
    let window = "main";
    let webview = "main";
    let remote_url = "http://localhost:8080";
    let windows = vec![Pattern::new(window).unwrap()];

    let remote_context = ExecutionContext::Remote {
      url: remote_url.parse().unwrap(),
    };

    let allowed_commands = [(
      command.clone(),
      vec![
        ResolvedCommand {
          windows: windows.clone(),
          referenced_by: ResolvedCommandReference {
            capability: "maincap".to_string(),
            permission: "allow-command".to_string(),
          },
          ..Default::default()
        },
        ResolvedCommand {
          windows: windows.clone(),
          context: remote_context.clone(),
          referenced_by: ResolvedCommandReference {
            capability: "remotecap".to_string(),
            permission: "allow-command".to_string(),
          },
          ..Default::default()
        },
      ],
    )]
    .into_iter()
    .collect();

    // one capability denies the command locally, another denies it on the remote URL
    let denied_commands = [(
      command,
      vec![
        ResolvedCommand {
          windows: windows.clone(),
          referenced_by: ResolvedCommandReference {
            capability: "localcap".to_string(),
            permission: "deny-command".to_string(),
          },
          ..Default::default()
        },
        ResolvedCommand {
          windows,
          context: remote_context,
          referenced_by: ResolvedCommandReference {
            capability: "remotecap".to_string(),
            permission: "deny-command".to_string(),
          },
          ..Default::default()
        },
      ],
    )]
    .into_iter()
    .collect();

    let authority = RuntimeAuthority::new(
      Default::default(),
      Resolved {
        allowed_commands,
        denied_commands,
        ..Default::default()
      },
    );

    // only the capability denying the local context is referenced
    assert_eq!(
      authority.resolve_access_message(plugin_name, command_name, window, webview, &Origin::Local),
      "myplugin.my-command explicitly denied on origin local\n\nreferenced by: capability: localcap, permission: deny-command"
    );

    // only the capability denying the remote URL is referenced
    assert_eq!(
      authority.resolve_access_message(
        plugin_name,
        command_name,
        window,
        webview,
        &Origin::Remote {
          url: remote_url.parse().unwrap()
        }
      ),
      "myplugin.my-command explicitly denied on origin remote: http://localhost:8080/\n\nreferenced by: capability: remotecap, permission: deny-command"
    );

    // a remote URL that matches no deny entry is not reported as explicitly denied
    let message = authority.resolve_access_message(
      plugin_name,
      command_name,
      window,
      webview,
      &Origin::Remote {
        url: "http://localhost:123".parse().unwrap(),
      },
    );
    assert!(
      !message.contains("explicitly denied"),
      "unexpected message: {message}"
    );
    assert!(
      message.starts_with("myplugin.my-command not allowed"),
      "unexpected message: {message}"
    );
  }

  #[cfg(debug_assertions)]
  #[test]
  fn resolve_access_message() {
    use tauri_utils::acl::manifest::Manifest;

    let plugin_name = "myplugin";
    let command_allowed_on_window = "my-command-window";
    let command_allowed_on_webview_window = "my-command-webview-window";
    let window = "main-*";
    let webview = "webview-*";
    let remote_url = "http://localhost:8080";

    let referenced_by = tauri_utils::acl::resolved::ResolvedCommandReference {
      capability: "maincap".to_string(),
      permission: "allow-command".to_string(),
    };

    let resolved_window_cmd = ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      referenced_by: referenced_by.clone(),
      ..Default::default()
    };
    let resolved_webview_window_cmd = ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      webviews: vec![Pattern::new(webview).unwrap()],
      referenced_by: referenced_by.clone(),
      ..Default::default()
    };
    let resolved_webview_window_remote_cmd = ResolvedCommand {
      windows: vec![Pattern::new(window).unwrap()],
      webviews: vec![Pattern::new(webview).unwrap()],
      referenced_by,
      context: ExecutionContext::Remote {
        url: remote_url.parse().unwrap(),
      },
      ..Default::default()
    };

    let allowed_commands = [
      (
        format!("plugin:{plugin_name}|{command_allowed_on_window}"),
        vec![resolved_window_cmd],
      ),
      (
        format!("plugin:{plugin_name}|{command_allowed_on_webview_window}"),
        vec![
          resolved_webview_window_cmd,
          resolved_webview_window_remote_cmd,
        ],
      ),
    ]
    .into_iter()
    .collect();

    let authority = RuntimeAuthority::new(
      [(
        plugin_name.to_string(),
        Manifest {
          default_permission: None,
          permissions: Default::default(),
          permission_sets: Default::default(),
          commands: Default::default(),
          global_scope_schema: None,
        },
      )]
      .into_iter()
      .collect(),
      Resolved {
        allowed_commands,
        ..Default::default()
      },
    );

    // unknown plugin
    assert_eq!(
      authority.resolve_access_message(
        "unknown-plugin",
        command_allowed_on_window,
        window,
        webview,
        &Origin::Local
      ),
      "unknown-plugin.my-command-window not allowed. Plugin not found"
    );

    // unknown command
    assert_eq!(
      authority.resolve_access_message(
        plugin_name,
        "unknown-command",
        window,
        webview,
        &Origin::Local
      ),
      "myplugin.unknown-command not allowed. Command not found"
    );

    // window/webview do not match
    assert_eq!(
      authority.resolve_access_message(
        plugin_name,
        command_allowed_on_window,
        "other-window",
        "any-webview",
        &Origin::Local
      ),
      "myplugin.my-command-window not allowed on window \"other-window\", webview \"any-webview\", URL: local\n\nallowed on: [windows: \"main-*\", URL: local]\n\nreferenced by: capability: maincap, permission: allow-command"
    );

    // window matches, but not origin
    assert_eq!(
      authority.resolve_access_message(
        plugin_name,
        command_allowed_on_window,
        window,
        "any-webview",
        &Origin::Remote {
          url: "http://localhst".parse().unwrap()
        }
      ),
      "myplugin.my-command-window not allowed on window \"main-*\", webview \"any-webview\", URL: http://localhst/\n\nallowed on: [windows: \"main-*\", URL: local]\n\nreferenced by: capability: maincap, permission: allow-command"
    );

    // window/webview do not match
    assert_eq!(
      authority.resolve_access_message(
        plugin_name,
        command_allowed_on_webview_window,
        "other-window",
        "other-webview",
        &Origin::Local
      ),
      "myplugin.my-command-webview-window not allowed on window \"other-window\", webview \"other-webview\", URL: local\n\nallowed on: [windows: \"main-*\", webviews: \"webview-*\", URL: local], [windows: \"main-*\", webviews: \"webview-*\", URL: http://localhost:8080]\n\nreferenced by: capability: maincap, permission: allow-command || capability: maincap, permission: allow-command"
    );

    // window/webview matches, but not origin
    assert_eq!(
      authority.resolve_access_message(
        plugin_name,
        command_allowed_on_webview_window,
        window,
        webview,
        &Origin::Remote {
          url: "http://localhost:123".parse().unwrap()
        }
      ),
      "myplugin.my-command-webview-window not allowed on window \"main-*\", webview \"webview-*\", URL: http://localhost:123/\n\nallowed on: [windows: \"main-*\", webviews: \"webview-*\", URL: local], [windows: \"main-*\", webviews: \"webview-*\", URL: http://localhost:8080]\n\nreferenced by: capability: maincap, permission: allow-command || capability: maincap, permission: allow-command"
    );
  }

  #[cfg(feature = "dynamic-acl")]
  #[test]
  fn add_capability_assigns_fresh_scope_ids() {
    use serde_json::json;
    use std::collections::{BTreeMap, BTreeSet};
    use tauri_utils::acl::{
      Permission,
      capability::{Capability, CapabilityFile},
      manifest::Manifest,
    };

    fn manifest(permission: serde_json::Value) -> Manifest {
      let permission: Permission = serde_json::from_value(permission).unwrap();
      Manifest {
        permissions: [(permission.identifier.clone(), permission)].into(),
        ..Default::default()
      }
    }

    fn capability(identifier: &str, permission: &str) -> Capability {
      serde_json::from_value(json!({
        "identifier": identifier,
        "windows": ["main"],
        "permissions": [permission]
      }))
      .unwrap()
    }

    fn scope_ids(authority: &RuntimeAuthority, command: &str) -> BTreeSet<u64> {
      authority.inner().allowed_commands[command]
        .iter()
        .filter_map(|cmd| cmd.scope_id)
        .collect()
    }

    // the scope values the command resolves to, see `CommandScope::resolve`
    fn allowed_scope(authority: &RuntimeAuthority, command: &str) -> Vec<serde_json::Value> {
      scope_ids(authority, command)
        .iter()
        .flat_map(|id| &authority.scope_manager().command_scope[id].allow)
        .cloned()
        .map(serde_json::Value::from)
        .collect()
    }

    let acl: BTreeMap<String, Manifest> = [
      (
        "opener".to_string(),
        manifest(json!({
          "identifier": "allow-open-path",
          "commands": { "allow": ["open_path"] },
          "scope": { "allow": [{ "path": "/tmp/**" }] }
        })),
      ),
      (
        "http".to_string(),
        manifest(json!({
          "identifier": "allow-fetch",
          "commands": { "allow": ["fetch", "fetch_send"] },
          "scope": { "allow": [{ "url": "https://example.com" }] }
        })),
      ),
    ]
    .into();

    // build time ACL, the opener scope gets id 1
    let baked = Resolved::resolve(
      &acl,
      [(
        "baked".to_string(),
        capability("baked", "opener:allow-open-path"),
      )]
      .into(),
      tauri_utils::platform::Target::current(),
    )
    .unwrap();
    let mut authority = RuntimeAuthority::new(acl, baked);
    assert_eq!(scope_ids(&authority, "plugin:opener|open_path"), [1].into());

    // a runtime capability for another plugin must not be merged into scope 1
    authority
      .add_capability_inner(CapabilityFile::Capability(capability(
        "runtime",
        "http:allow-fetch",
      )))
      .unwrap();

    assert_eq!(
      authority
        .scope_manager()
        .command_scope
        .keys()
        .copied()
        .collect::<Vec<_>>(),
      vec![1, 2]
    );
    assert!(authority.scope_manager().command_cache.contains_key(&2));
    assert_eq!(
      allowed_scope(&authority, "plugin:opener|open_path"),
      vec![json!({ "path": "/tmp/**" })]
    );
    // fetch and fetch_send share the scope, and it must not be duplicated
    assert_eq!(scope_ids(&authority, "plugin:http|fetch"), [2].into());
    assert_eq!(scope_ids(&authority, "plugin:http|fetch_send"), [2].into());
    assert_eq!(
      allowed_scope(&authority, "plugin:http|fetch"),
      vec![json!({ "url": "https://example.com" })]
    );

    // the next runtime capability continues past the previous one
    authority
      .add_capability_inner(CapabilityFile::Capability(capability(
        "runtime-2",
        "opener:allow-open-path",
      )))
      .unwrap();
    assert_eq!(
      authority
        .scope_manager()
        .command_scope
        .keys()
        .copied()
        .collect::<Vec<_>>(),
      vec![1, 2, 3]
    );
    assert!(authority.scope_manager().command_cache.contains_key(&3));
    assert_eq!(
      scope_ids(&authority, "plugin:opener|open_path"),
      [1, 3].into()
    );
    assert_eq!(scope_ids(&authority, "plugin:http|fetch"), [2].into());
  }

  // ============================================================================
  // Async (background-built) authority
  // ============================================================================
  //
  // The `runtime_authority!` macro builds the resolved ACL on a background thread via
  // `new_async`; the first authorization read joins it (see `RuntimeAuthority::inner`). These
  // tests assert the background-built authority authorizes identically to the eager `new` path.

  /// A resolved ACL with one allowed command (window `main-*`, command scope `1`), one denied
  /// command (any window), and a command scope. Built fresh on each call so it can be used both
  /// eagerly and as a `new_async` builder.
  fn sample_resolved() -> Resolved {
    use tauri_utils::acl::resolved::{ResolvedScope, ScopeKey};

    let allowed_commands = [(
      "allowed-command".to_string(),
      vec![ResolvedCommand {
        windows: vec![Pattern::new("main-*").unwrap()],
        scope_id: Some(1 as ScopeKey),
        ..Default::default()
      }],
    )]
    .into_iter()
    .collect();
    let denied_commands = [(
      "denied-command".to_string(),
      vec![ResolvedCommand {
        windows: vec![Pattern::new("*").unwrap()],
        ..Default::default()
      }],
    )]
    .into_iter()
    .collect();
    let command_scope = [(1 as ScopeKey, ResolvedScope::default())]
      .into_iter()
      .collect();

    Resolved {
      allowed_commands,
      denied_commands,
      command_scope,
      ..Default::default()
    }
  }

  #[test]
  fn async_authority_resolves_allowed_command() {
    // Built off-thread; `resolve_access` must block on the builder, then authorize correctly.
    let authority = RuntimeAuthority::new_async(Default::default, sample_resolved);

    assert!(
      authority
        .resolve_access("allowed-command", "main-window", "wv", &Origin::Local)
        .is_some(),
      "allowed command should resolve through the background-built authority"
    );
    assert!(
      authority
        .resolve_access("unknown-command", "main-window", "wv", &Origin::Local)
        .is_none(),
      "unknown command must not be allowed"
    );
  }

  #[test]
  fn async_authority_denied_takes_precedence() {
    let authority = RuntimeAuthority::new_async(Default::default, sample_resolved);
    assert!(
      authority
        .resolve_access("denied-command", "anything", "wv", &Origin::Local)
        .is_none(),
      "denied command must be rejected through the background-built authority"
    );
  }

  #[test]
  fn async_and_eager_authority_agree() {
    let eager = RuntimeAuthority::new(Default::default(), sample_resolved());
    let lazy = RuntimeAuthority::new_async(Default::default, sample_resolved);

    for (command, window) in [
      ("allowed-command", "main-1"),
      ("allowed-command", "other-1"),
      ("denied-command", "main-1"),
      ("unknown-command", "main-1"),
    ] {
      assert_eq!(
        eager.resolve_access(command, window, "wv", &Origin::Local),
        lazy.resolve_access(command, window, "wv", &Origin::Local),
        "eager and background-built authority disagree for command={command} window={window}"
      );
    }
  }

  #[test]
  fn async_authority_scope_manager_materializes() {
    // `scope_manager()` must also join the background builder and expose the resolved scopes.
    let authority = RuntimeAuthority::new_async(Default::default, sample_resolved);
    assert!(
      authority.scope_manager().command_scope.contains_key(&1),
      "scope manager should expose the resolved command scope after materialization"
    );
  }

  #[cfg(debug_assertions)]
  #[test]
  fn async_authority_resolve_access_message_materializes() {
    // The debug-only error path reads the raw ACL through the background-built authority; ensure
    // it materializes and produces a denial message without panicking.
    let authority = RuntimeAuthority::new_async(Default::default, sample_resolved);
    let message = authority.resolve_access_message(
      super::APP_ACL_KEY,
      "denied-command",
      "win",
      "wv",
      &Origin::Local,
    );
    assert!(
      message.contains("denied"),
      "expected a denial message, got: {message}"
    );
  }
}