capability.rs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! End-user abstraction for selecting permissions a window has access to.
  5. use std::{path::Path, str::FromStr};
  6. use crate::{acl::Identifier, platform::Target};
  7. use serde::{Deserialize, Serialize};
  8. use super::Scopes;
  9. /// An entry for a permission value in a [`Capability`] can be either a raw permission [`Identifier`]
  10. /// or an object that references a permission and extends its scope.
  11. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
  12. #[serde(untagged)]
  13. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  14. pub enum PermissionEntry {
  15. /// Reference a permission or permission set by identifier.
  16. PermissionRef(Identifier),
  17. /// Reference a permission or permission set by identifier and extends its scope.
  18. ExtendedPermission {
  19. /// Identifier of the permission or permission set.
  20. identifier: Identifier,
  21. /// Scope to append to the existing permission scope.
  22. #[serde(default, flatten)]
  23. scope: Scopes,
  24. },
  25. }
  26. impl PermissionEntry {
  27. /// The identifier of the permission referenced in this entry.
  28. pub fn identifier(&self) -> &Identifier {
  29. match self {
  30. Self::PermissionRef(identifier) => identifier,
  31. Self::ExtendedPermission {
  32. identifier,
  33. scope: _,
  34. } => identifier,
  35. }
  36. }
  37. }
  38. /// A grouping and boundary mechanism developers can use to isolate access to the IPC layer.
  39. ///
  40. /// It controls application windows fine grained access to the Tauri core, application, or plugin commands.
  41. /// If a window is not matching any capability then it has no access to the IPC layer at all.
  42. ///
  43. /// This can be done to create groups of windows, based on their required system access, which can reduce
  44. /// impact of frontend vulnerabilities in less privileged windows.
  45. /// Windows can be added to a capability by exact name (e.g. `main-window`) or glob patterns like `*` or `admin-*`.
  46. /// A Window can have none, one, or multiple associated capabilities.
  47. ///
  48. /// ## Example
  49. ///
  50. /// ```json
  51. /// {
  52. /// "identifier": "main-user-files-write",
  53. /// "description": "This capability allows the `main` window on macOS and Windows access to `filesystem` write related commands and `dialog` commands to enable programatic access to files selected by the user.",
  54. /// "windows": [
  55. /// "main"
  56. /// ],
  57. /// "permissions": [
  58. /// "path:default",
  59. /// "dialog:open",
  60. /// {
  61. /// "identifier": "fs:allow-write-text-file",
  62. /// "allow": [{ "path": "$HOME/test.txt" }]
  63. /// },
  64. /// "platforms": ["macOS","windows"]
  65. /// }
  66. /// ```
  67. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
  68. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  69. pub struct Capability {
  70. /// Identifier of the capability.
  71. ///
  72. /// ## Example
  73. ///
  74. /// `main-user-files-write`
  75. ///
  76. pub identifier: String,
  77. /// Description of what the capability is intended to allow on associated windows.
  78. ///
  79. /// It should contain a description of what the grouped permissions should allow.
  80. ///
  81. /// ## Example
  82. ///
  83. /// This capability allows the `main` window access to `filesystem` write related
  84. /// commands and `dialog` commands to enable programatic access to files selected by the user.
  85. #[serde(default)]
  86. pub description: String,
  87. /// Configure remote URLs that can use the capability permissions.
  88. ///
  89. /// This setting is optional and defaults to not being set, as our
  90. /// default use case is that the content is served from our local application.
  91. ///
  92. /// :::caution
  93. /// Make sure you understand the security implications of providing remote
  94. /// sources with local system access.
  95. /// :::
  96. ///
  97. /// ## Example
  98. ///
  99. /// ```json
  100. /// {
  101. /// "urls": ["https://*.mydomain.dev"]
  102. /// }
  103. /// ```
  104. #[serde(default, skip_serializing_if = "Option::is_none")]
  105. pub remote: Option<CapabilityRemote>,
  106. /// Whether this capability is enabled for local app URLs or not. Defaults to `true`.
  107. #[serde(default = "default_capability_local")]
  108. pub local: bool,
  109. /// List of windows that are affected by this capability. Can be a glob pattern.
  110. ///
  111. /// On multiwebview windows, prefer [`Self::webviews`] for a fine grained access control.
  112. ///
  113. /// ## Example
  114. ///
  115. /// `["main"]`
  116. #[serde(default, skip_serializing_if = "Vec::is_empty")]
  117. pub windows: Vec<String>,
  118. /// List of webviews that are affected by this capability. Can be a glob pattern.
  119. ///
  120. /// This is only required when using on multiwebview contexts, by default
  121. /// all child webviews of a window that matches [`Self::windows`] are linked.
  122. ///
  123. /// ## Example
  124. ///
  125. /// `["sub-webview-one", "sub-webview-two"]`
  126. #[serde(default, skip_serializing_if = "Vec::is_empty")]
  127. pub webviews: Vec<String>,
  128. /// List of permissions attached to this capability.
  129. ///
  130. /// Must include the plugin name as prefix in the form of `${plugin-name}:${permission-name}`.
  131. /// For commands directly implemented in the application itself only `${permission-name}`
  132. /// is required.
  133. ///
  134. /// ## Example
  135. ///
  136. /// ```json
  137. /// [
  138. /// "path:default",
  139. /// "event:default",
  140. /// "window:default",
  141. /// "app:default",
  142. /// "image:default",
  143. /// "resources:default",
  144. /// "menu:default",
  145. /// "tray:default",
  146. /// "shell:allow-open",
  147. /// "dialog:open",
  148. /// {
  149. /// "identifier": "fs:allow-write-text-file",
  150. /// "allow": [{ "path": "$HOME/test.txt" }]
  151. /// }
  152. /// ```
  153. pub permissions: Vec<PermissionEntry>,
  154. /// Limit which target platforms this capability applies to.
  155. ///
  156. /// By default all platforms are targeted.
  157. ///
  158. /// ## Example
  159. ///
  160. /// `["macOS","windows"]`
  161. #[serde(skip_serializing_if = "Option::is_none")]
  162. pub platforms: Option<Vec<Target>>,
  163. }
  164. fn default_capability_local() -> bool {
  165. true
  166. }
  167. /// Configuration for remote URLs that are associated with the capability.
  168. #[derive(Debug, Default, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord, Hash)]
  169. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  170. #[serde(rename_all = "camelCase")]
  171. pub struct CapabilityRemote {
  172. /// Remote domains this capability refers to using the [URLPattern standard](https://urlpattern.spec.whatwg.org/).
  173. ///
  174. /// ## Examples
  175. ///
  176. /// - "https://*.mydomain.dev": allows subdomains of mydomain.dev
  177. /// - "https://mydomain.dev/api/*": allows any subpath of mydomain.dev/api
  178. pub urls: Vec<String>,
  179. }
  180. /// Capability formats accepted in a capability file.
  181. #[derive(Deserialize)]
  182. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  183. #[serde(untagged)]
  184. pub enum CapabilityFile {
  185. /// A single capability.
  186. Capability(Capability),
  187. /// A list of capabilities.
  188. List(Vec<Capability>),
  189. /// A list of capabilities.
  190. NamedList {
  191. /// The list of capabilities.
  192. capabilities: Vec<Capability>,
  193. },
  194. }
  195. impl CapabilityFile {
  196. /// Load the given capability file.
  197. pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, super::Error> {
  198. let path = path.as_ref();
  199. let capability_file = std::fs::read_to_string(path).map_err(super::Error::ReadFile)?;
  200. let ext = path.extension().unwrap().to_string_lossy().to_string();
  201. let file: Self = match ext.as_str() {
  202. "toml" => toml::from_str(&capability_file)?,
  203. "json" => serde_json::from_str(&capability_file)?,
  204. _ => return Err(super::Error::UnknownCapabilityFormat(ext)),
  205. };
  206. Ok(file)
  207. }
  208. }
  209. impl FromStr for CapabilityFile {
  210. type Err = super::Error;
  211. fn from_str(s: &str) -> Result<Self, Self::Err> {
  212. serde_json::from_str(s)
  213. .or_else(|_| toml::from_str(s))
  214. .map_err(Into::into)
  215. }
  216. }
  217. #[cfg(feature = "build")]
  218. mod build {
  219. use std::convert::identity;
  220. use proc_macro2::TokenStream;
  221. use quote::{quote, ToTokens, TokenStreamExt};
  222. use super::*;
  223. use crate::{literal_struct, tokens::*};
  224. impl ToTokens for CapabilityRemote {
  225. fn to_tokens(&self, tokens: &mut TokenStream) {
  226. let urls = vec_lit(&self.urls, str_lit);
  227. literal_struct!(
  228. tokens,
  229. ::tauri::utils::acl::capability::CapabilityRemote,
  230. urls
  231. );
  232. }
  233. }
  234. impl ToTokens for PermissionEntry {
  235. fn to_tokens(&self, tokens: &mut TokenStream) {
  236. let prefix = quote! { ::tauri::utils::acl::capability::PermissionEntry };
  237. tokens.append_all(match self {
  238. Self::PermissionRef(id) => {
  239. quote! { #prefix::PermissionRef(#id) }
  240. }
  241. Self::ExtendedPermission { identifier, scope } => {
  242. quote! { #prefix::ExtendedPermission {
  243. identifier: #identifier,
  244. scope: #scope
  245. } }
  246. }
  247. });
  248. }
  249. }
  250. impl ToTokens for Capability {
  251. fn to_tokens(&self, tokens: &mut TokenStream) {
  252. let identifier = str_lit(&self.identifier);
  253. let description = str_lit(&self.description);
  254. let remote = opt_lit(self.remote.as_ref());
  255. let local = self.local;
  256. let windows = vec_lit(&self.windows, str_lit);
  257. let webviews = vec_lit(&self.webviews, str_lit);
  258. let permissions = vec_lit(&self.permissions, identity);
  259. let platforms = opt_vec_lit(self.platforms.as_ref(), identity);
  260. literal_struct!(
  261. tokens,
  262. ::tauri::utils::acl::capability::Capability,
  263. identifier,
  264. description,
  265. remote,
  266. local,
  267. windows,
  268. webviews,
  269. permissions,
  270. platforms
  271. );
  272. }
  273. }
  274. }