mod.rs 14 KB

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