capability.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. #[cfg_attr(feature = "schema", schemars(schema_with = "unique_permission"))]
  154. pub permissions: Vec<PermissionEntry>,
  155. /// Limit which target platforms this capability applies to.
  156. ///
  157. /// By default all platforms are targeted.
  158. ///
  159. /// ## Example
  160. ///
  161. /// `["macOS","windows"]`
  162. #[serde(skip_serializing_if = "Option::is_none")]
  163. pub platforms: Option<Vec<Target>>,
  164. }
  165. #[cfg(feature = "schema")]
  166. fn unique_permission(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
  167. use schemars::schema;
  168. schema::SchemaObject {
  169. instance_type: Some(schema::InstanceType::Array.into()),
  170. array: Some(Box::new(schema::ArrayValidation {
  171. unique_items: Some(true),
  172. items: Some(gen.subschema_for::<PermissionEntry>().into()),
  173. ..Default::default()
  174. })),
  175. ..Default::default()
  176. }
  177. .into()
  178. }
  179. fn default_capability_local() -> bool {
  180. true
  181. }
  182. /// Configuration for remote URLs that are associated with the capability.
  183. #[derive(Debug, Default, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord, Hash)]
  184. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  185. #[serde(rename_all = "camelCase")]
  186. pub struct CapabilityRemote {
  187. /// Remote domains this capability refers to using the [URLPattern standard](https://urlpattern.spec.whatwg.org/).
  188. ///
  189. /// ## Examples
  190. ///
  191. /// - "https://*.mydomain.dev": allows subdomains of mydomain.dev
  192. /// - "https://mydomain.dev/api/*": allows any subpath of mydomain.dev/api
  193. pub urls: Vec<String>,
  194. }
  195. /// Capability formats accepted in a capability file.
  196. #[derive(Deserialize)]
  197. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  198. #[serde(untagged)]
  199. pub enum CapabilityFile {
  200. /// A single capability.
  201. Capability(Capability),
  202. /// A list of capabilities.
  203. List(Vec<Capability>),
  204. /// A list of capabilities.
  205. NamedList {
  206. /// The list of capabilities.
  207. capabilities: Vec<Capability>,
  208. },
  209. }
  210. impl CapabilityFile {
  211. /// Load the given capability file.
  212. pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, super::Error> {
  213. let path = path.as_ref();
  214. let capability_file = std::fs::read_to_string(path).map_err(super::Error::ReadFile)?;
  215. let ext = path.extension().unwrap().to_string_lossy().to_string();
  216. let file: Self = match ext.as_str() {
  217. "toml" => toml::from_str(&capability_file)?,
  218. "json" => serde_json::from_str(&capability_file)?,
  219. _ => return Err(super::Error::UnknownCapabilityFormat(ext)),
  220. };
  221. Ok(file)
  222. }
  223. }
  224. impl FromStr for CapabilityFile {
  225. type Err = super::Error;
  226. fn from_str(s: &str) -> Result<Self, Self::Err> {
  227. serde_json::from_str(s)
  228. .or_else(|_| toml::from_str(s))
  229. .map_err(Into::into)
  230. }
  231. }
  232. #[cfg(feature = "build")]
  233. mod build {
  234. use std::convert::identity;
  235. use proc_macro2::TokenStream;
  236. use quote::{quote, ToTokens, TokenStreamExt};
  237. use super::*;
  238. use crate::{literal_struct, tokens::*};
  239. impl ToTokens for CapabilityRemote {
  240. fn to_tokens(&self, tokens: &mut TokenStream) {
  241. let urls = vec_lit(&self.urls, str_lit);
  242. literal_struct!(
  243. tokens,
  244. ::tauri::utils::acl::capability::CapabilityRemote,
  245. urls
  246. );
  247. }
  248. }
  249. impl ToTokens for PermissionEntry {
  250. fn to_tokens(&self, tokens: &mut TokenStream) {
  251. let prefix = quote! { ::tauri::utils::acl::capability::PermissionEntry };
  252. tokens.append_all(match self {
  253. Self::PermissionRef(id) => {
  254. quote! { #prefix::PermissionRef(#id) }
  255. }
  256. Self::ExtendedPermission { identifier, scope } => {
  257. quote! { #prefix::ExtendedPermission {
  258. identifier: #identifier,
  259. scope: #scope
  260. } }
  261. }
  262. });
  263. }
  264. }
  265. impl ToTokens for Capability {
  266. fn to_tokens(&self, tokens: &mut TokenStream) {
  267. let identifier = str_lit(&self.identifier);
  268. let description = str_lit(&self.description);
  269. let remote = opt_lit(self.remote.as_ref());
  270. let local = self.local;
  271. let windows = vec_lit(&self.windows, str_lit);
  272. let webviews = vec_lit(&self.webviews, str_lit);
  273. let permissions = vec_lit(&self.permissions, identity);
  274. let platforms = opt_vec_lit(self.platforms.as_ref(), identity);
  275. literal_struct!(
  276. tokens,
  277. ::tauri::utils::acl::capability::Capability,
  278. identifier,
  279. description,
  280. remote,
  281. local,
  282. windows,
  283. webviews,
  284. permissions,
  285. platforms
  286. );
  287. }
  288. }
  289. }