mod.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! Access Control List types.
  5. //!
  6. //! # Stability
  7. //!
  8. //! This is a core functionality that is not considered part of the stable API.
  9. //! If you use it, note that it may include breaking changes in the future.
  10. //!
  11. //! These items are intended to be non-breaking from a de/serialization standpoint only.
  12. //! Using and modifying existing config values will try to avoid breaking changes, but they are
  13. //! free to add fields in the future - causing breaking changes for creating and full destructuring.
  14. //!
  15. //! To avoid this, [ignore unknown fields when destructuring] with the `{my, config, ..}` pattern.
  16. //! If you need to create the Rust config directly without deserializing, then create the struct
  17. //! the [Struct Update Syntax] with `..Default::default()`, which may need a
  18. //! `#[allow(clippy::needless_update)]` attribute if you are declaring all fields.
  19. //!
  20. //! [ignore unknown fields when destructuring]: https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#ignoring-remaining-parts-of-a-value-with-
  21. //! [Struct Update Syntax]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
  22. use serde::{Deserialize, Serialize};
  23. use std::{num::NonZeroU64, str::FromStr, sync::Arc};
  24. use thiserror::Error;
  25. use url::Url;
  26. use crate::platform::Target;
  27. pub use self::{identifier::*, value::*};
  28. /// Known filename of the permission schema JSON file
  29. pub const PERMISSION_SCHEMA_FILE_NAME: &str = "schema.json";
  30. /// Known ACL key for the app permissions.
  31. pub const APP_ACL_KEY: &str = "__app-acl__";
  32. #[cfg(feature = "build")]
  33. pub mod build;
  34. pub mod capability;
  35. pub mod identifier;
  36. pub mod manifest;
  37. pub mod resolved;
  38. pub mod value;
  39. /// Possible errors while processing ACL files.
  40. #[derive(Debug, Error)]
  41. pub enum Error {
  42. /// Could not find an environmental variable that is set inside of build scripts.
  43. ///
  44. /// Whatever generated this should be called inside of a build script.
  45. #[error("expected build script env var {0}, but it was not found - ensure this is called in a build script")]
  46. BuildVar(&'static str),
  47. /// The links field in the manifest **MUST** be set and match the name of the crate.
  48. #[error("package.links field in the Cargo manifest is not set, it should be set to the same as package.name")]
  49. LinksMissing,
  50. /// The links field in the manifest **MUST** match the name of the crate.
  51. #[error(
  52. "package.links field in the Cargo manifest MUST be set to the same value as package.name"
  53. )]
  54. LinksName,
  55. /// IO error while reading a file
  56. #[error("failed to read file: {0}")]
  57. ReadFile(std::io::Error),
  58. /// IO error while writing a file
  59. #[error("failed to write file: {0}")]
  60. WriteFile(std::io::Error),
  61. /// IO error while creating a file
  62. #[error("failed to create file: {0}")]
  63. CreateFile(std::io::Error),
  64. /// [`cargo_metadata`] was not able to complete successfully
  65. #[cfg(feature = "build")]
  66. #[error("failed to execute: {0}")]
  67. Metadata(#[from] ::cargo_metadata::Error),
  68. /// Invalid glob
  69. #[error("failed to run glob: {0}")]
  70. Glob(#[from] glob::PatternError),
  71. /// Invalid TOML encountered
  72. #[error("failed to parse TOML: {0}")]
  73. Toml(#[from] toml::de::Error),
  74. /// Invalid JSON encountered
  75. #[error("failed to parse JSON: {0}")]
  76. Json(#[from] serde_json::Error),
  77. /// Invalid permissions file format
  78. #[error("unknown permission format {0}")]
  79. UnknownPermissionFormat(String),
  80. /// Invalid capabilities file format
  81. #[error("unknown capability format {0}")]
  82. UnknownCapabilityFormat(String),
  83. /// Permission referenced in set not found.
  84. #[error("permission {permission} not found from set {set}")]
  85. SetPermissionNotFound {
  86. /// Permission identifier.
  87. permission: String,
  88. /// Set identifier.
  89. set: String,
  90. },
  91. /// Unknown ACL manifest.
  92. #[error("unknown ACL for {key}, expected one of {available}")]
  93. UnknownManifest {
  94. /// Manifest key.
  95. key: String,
  96. /// Available manifest keys.
  97. available: String,
  98. },
  99. /// Unknown permission.
  100. #[error("unknown permission {permission} for {key}")]
  101. UnknownPermission {
  102. /// Manifest key.
  103. key: String,
  104. /// Permission identifier.
  105. permission: String,
  106. },
  107. /// Capability with the given identifier already exists.
  108. #[error("capability with identifier `{identifier}` already exists")]
  109. CapabilityAlreadyExists {
  110. /// Capability identifier.
  111. identifier: String,
  112. },
  113. }
  114. /// Allowed and denied commands inside a permission.
  115. ///
  116. /// If two commands clash inside of `allow` and `deny`, it should be denied by default.
  117. #[derive(Debug, Default, Serialize, Deserialize)]
  118. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  119. pub struct Commands {
  120. /// Allowed command.
  121. #[serde(default)]
  122. pub allow: Vec<String>,
  123. /// Denied command, which takes priority.
  124. #[serde(default)]
  125. pub deny: Vec<String>,
  126. }
  127. /// An argument for fine grained behavior control of Tauri commands.
  128. ///
  129. /// It can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command.
  130. /// The configured scope is passed to the command and will be enforced by the command implementation.
  131. ///
  132. /// ## Example
  133. ///
  134. /// ```json
  135. /// {
  136. /// "allow": [{ "path": "$HOME/**" }],
  137. /// "deny": [{ "path": "$HOME/secret.txt" }]
  138. /// }
  139. /// ```
  140. #[derive(Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
  141. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  142. pub struct Scopes {
  143. /// Data that defines what is allowed by the scope.
  144. #[serde(skip_serializing_if = "Option::is_none")]
  145. pub allow: Option<Vec<Value>>,
  146. /// Data that defines what is denied by the scope. This should be prioritized by validation logic.
  147. #[serde(skip_serializing_if = "Option::is_none")]
  148. pub deny: Option<Vec<Value>>,
  149. }
  150. impl Scopes {
  151. fn is_empty(&self) -> bool {
  152. self.allow.is_none() && self.deny.is_none()
  153. }
  154. }
  155. /// Descriptions of explicit privileges of commands.
  156. ///
  157. /// It can enable commands to be accessible in the frontend of the application.
  158. ///
  159. /// If the scope is defined it can be used to fine grain control the access of individual or multiple commands.
  160. #[derive(Debug, Serialize, Deserialize)]
  161. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  162. pub struct Permission {
  163. /// The version of the permission.
  164. #[serde(skip_serializing_if = "Option::is_none")]
  165. pub version: Option<NonZeroU64>,
  166. /// A unique identifier for the permission.
  167. pub identifier: String,
  168. /// Human-readable description of what the permission does.
  169. /// Tauri internal convention is to use <h4> headings in markdown content
  170. /// for Tauri documentation generation purposes.
  171. #[serde(skip_serializing_if = "Option::is_none")]
  172. pub description: Option<String>,
  173. /// Allowed or denied commands when using this permission.
  174. #[serde(default)]
  175. pub commands: Commands,
  176. /// Allowed or denied scoped when using this permission.
  177. #[serde(default, skip_serializing_if = "Scopes::is_empty")]
  178. pub scope: Scopes,
  179. /// Target platforms this permission applies. By default all platforms are affected by this permission.
  180. #[serde(skip_serializing_if = "Option::is_none")]
  181. pub platforms: Option<Vec<Target>>,
  182. }
  183. /// A set of direct permissions grouped together under a new name.
  184. #[derive(Debug, Serialize, Deserialize)]
  185. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
  186. pub struct PermissionSet {
  187. /// A unique identifier for the permission.
  188. pub identifier: String,
  189. /// Human-readable description of what the permission does.
  190. pub description: String,
  191. /// All permissions this set contains.
  192. pub permissions: Vec<String>,
  193. }
  194. /// UrlPattern for [`ExecutionContext::Remote`].
  195. #[derive(Debug, Clone)]
  196. pub struct RemoteUrlPattern(Arc<urlpattern::UrlPattern>, String);
  197. impl FromStr for RemoteUrlPattern {
  198. type Err = urlpattern::quirks::Error;
  199. fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  200. let mut init = urlpattern::UrlPatternInit::parse_constructor_string::<regex::Regex>(s, None)?;
  201. if init.search.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
  202. init.search.replace("*".to_string());
  203. }
  204. if init.hash.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
  205. init.hash.replace("*".to_string());
  206. }
  207. if init
  208. .pathname
  209. .as_ref()
  210. .map(|p| p.is_empty() || p == "/")
  211. .unwrap_or(true)
  212. {
  213. init.pathname.replace("*".to_string());
  214. }
  215. let pattern = urlpattern::UrlPattern::parse(init, Default::default())?;
  216. Ok(Self(Arc::new(pattern), s.to_string()))
  217. }
  218. }
  219. impl RemoteUrlPattern {
  220. #[doc(hidden)]
  221. pub fn as_str(&self) -> &str {
  222. &self.1
  223. }
  224. /// Test if a given URL matches the pattern.
  225. pub fn test(&self, url: &Url) -> bool {
  226. self
  227. .0
  228. .test(urlpattern::UrlPatternMatchInput::Url(url.clone()))
  229. .unwrap_or_default()
  230. }
  231. }
  232. impl PartialEq for RemoteUrlPattern {
  233. fn eq(&self, other: &Self) -> bool {
  234. self.0.protocol() == other.0.protocol()
  235. && self.0.username() == other.0.username()
  236. && self.0.password() == other.0.password()
  237. && self.0.hostname() == other.0.hostname()
  238. && self.0.port() == other.0.port()
  239. && self.0.pathname() == other.0.pathname()
  240. && self.0.search() == other.0.search()
  241. && self.0.hash() == other.0.hash()
  242. }
  243. }
  244. impl Eq for RemoteUrlPattern {}
  245. /// Execution context of an IPC call.
  246. #[derive(Debug, Default, Clone, Eq, PartialEq)]
  247. pub enum ExecutionContext {
  248. /// A local URL is used (the Tauri app URL).
  249. #[default]
  250. Local,
  251. /// Remote URL is trying to use the IPC.
  252. Remote {
  253. /// The URL trying to access the IPC (URL pattern).
  254. url: RemoteUrlPattern,
  255. },
  256. }
  257. #[cfg(test)]
  258. mod tests {
  259. use crate::acl::RemoteUrlPattern;
  260. #[test]
  261. fn url_pattern_domain_wildcard() {
  262. let pattern: RemoteUrlPattern = "http://*".parse().unwrap();
  263. assert!(pattern.test(&"http://tauri.app/path".parse().unwrap()));
  264. assert!(pattern.test(&"http://tauri.app/path?q=1".parse().unwrap()));
  265. assert!(pattern.test(&"http://localhost/path".parse().unwrap()));
  266. assert!(pattern.test(&"http://localhost/path?q=1".parse().unwrap()));
  267. let pattern: RemoteUrlPattern = "http://*.tauri.app".parse().unwrap();
  268. assert!(!pattern.test(&"http://tauri.app/path".parse().unwrap()));
  269. assert!(!pattern.test(&"http://tauri.app/path?q=1".parse().unwrap()));
  270. assert!(pattern.test(&"http://api.tauri.app/path".parse().unwrap()));
  271. assert!(pattern.test(&"http://api.tauri.app/path?q=1".parse().unwrap()));
  272. assert!(!pattern.test(&"http://localhost/path".parse().unwrap()));
  273. assert!(!pattern.test(&"http://localhost/path?q=1".parse().unwrap()));
  274. }
  275. #[test]
  276. fn url_pattern_path_wildcard() {
  277. let pattern: RemoteUrlPattern = "http://localhost/*".parse().unwrap();
  278. assert!(pattern.test(&"http://localhost/path".parse().unwrap()));
  279. assert!(pattern.test(&"http://localhost/path?q=1".parse().unwrap()));
  280. }
  281. #[test]
  282. fn url_pattern_scheme_wildcard() {
  283. let pattern: RemoteUrlPattern = "*://localhost".parse().unwrap();
  284. assert!(pattern.test(&"http://localhost/path".parse().unwrap()));
  285. assert!(pattern.test(&"https://localhost/path?q=1".parse().unwrap()));
  286. assert!(pattern.test(&"custom://localhost/path".parse().unwrap()));
  287. }
  288. }
  289. #[cfg(feature = "build")]
  290. mod build_ {
  291. use std::convert::identity;
  292. use crate::{literal_struct, tokens::*};
  293. use super::*;
  294. use proc_macro2::TokenStream;
  295. use quote::{quote, ToTokens, TokenStreamExt};
  296. impl ToTokens for ExecutionContext {
  297. fn to_tokens(&self, tokens: &mut TokenStream) {
  298. let prefix = quote! { ::tauri::utils::acl::ExecutionContext };
  299. tokens.append_all(match self {
  300. Self::Local => {
  301. quote! { #prefix::Local }
  302. }
  303. Self::Remote { url } => {
  304. let url = url.as_str();
  305. quote! { #prefix::Remote { url: #url.parse().unwrap() } }
  306. }
  307. });
  308. }
  309. }
  310. impl ToTokens for Commands {
  311. fn to_tokens(&self, tokens: &mut TokenStream) {
  312. let allow = vec_lit(&self.allow, str_lit);
  313. let deny = vec_lit(&self.deny, str_lit);
  314. literal_struct!(tokens, ::tauri::utils::acl::Commands, allow, deny)
  315. }
  316. }
  317. impl ToTokens for Scopes {
  318. fn to_tokens(&self, tokens: &mut TokenStream) {
  319. let allow = opt_vec_lit(self.allow.as_ref(), identity);
  320. let deny = opt_vec_lit(self.deny.as_ref(), identity);
  321. literal_struct!(tokens, ::tauri::utils::acl::Scopes, allow, deny)
  322. }
  323. }
  324. impl ToTokens for Permission {
  325. fn to_tokens(&self, tokens: &mut TokenStream) {
  326. let version = opt_lit_owned(self.version.as_ref().map(|v| {
  327. let v = v.get();
  328. quote!(::core::num::NonZeroU64::new(#v).unwrap())
  329. }));
  330. let identifier = str_lit(&self.identifier);
  331. let description = opt_str_lit(self.description.as_ref());
  332. let commands = &self.commands;
  333. let scope = &self.scope;
  334. let platforms = opt_vec_lit(self.platforms.as_ref(), identity);
  335. literal_struct!(
  336. tokens,
  337. ::tauri::utils::acl::Permission,
  338. version,
  339. identifier,
  340. description,
  341. commands,
  342. scope,
  343. platforms
  344. )
  345. }
  346. }
  347. impl ToTokens for PermissionSet {
  348. fn to_tokens(&self, tokens: &mut TokenStream) {
  349. let identifier = str_lit(&self.identifier);
  350. let description = str_lit(&self.description);
  351. let permissions = vec_lit(&self.permissions, str_lit);
  352. literal_struct!(
  353. tokens,
  354. ::tauri::utils::acl::PermissionSet,
  355. identifier,
  356. description,
  357. permissions
  358. )
  359. }
  360. }
  361. }