tauri 2.12.0

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
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use std::{
  path::{Component, Display, Path, PathBuf},
  str::FromStr,
};

use crate::Runtime;
use tauri_utils::config::AppDirectoriesOverride;

use serde::{Deserialize, Deserializer, Serialize, de::Error as DeError};
use serde_repr::{Deserialize_repr, Serialize_repr};

pub(crate) mod plugin;

use crate::error::*;

#[cfg(target_os = "android")]
mod android;
#[cfg(not(target_os = "android"))]
mod desktop;

#[cfg(target_os = "android")]
pub use android::PathResolver;
#[cfg(not(target_os = "android"))]
pub use desktop::PathResolver;

/// A wrapper for [`PathBuf`] that prevents path traversal.
///
/// # Examples
///
/// ```
/// # use tauri::path::SafePathBuf;
/// assert!(SafePathBuf::new("../secret.txt".into()).is_err());
/// assert!(SafePathBuf::new("/home/user/stuff/../secret.txt".into()).is_err());
///
/// assert!(SafePathBuf::new("./file.txt".into()).is_ok());
/// assert!(SafePathBuf::new("/home/user/secret.txt".into()).is_ok());
/// ```
#[derive(Clone, Debug, Serialize)]
pub struct SafePathBuf(PathBuf);

impl SafePathBuf {
  /// Validates the path for directory traversal vulnerabilities and returns a new [`SafePathBuf`] instance if it is safe.
  pub fn new(path: PathBuf) -> std::result::Result<Self, &'static str> {
    if path.components().any(|x| matches!(x, Component::ParentDir)) {
      return Err("cannot traverse directory, rewrite the path without the use of `../`");
    }
    Ok(Self(path))
  }

  /// Returns an object that implements [`std::fmt::Display`] for safely printing paths.
  ///
  /// See [`PathBuf#method.display`] for more information.
  pub fn display(&self) -> Display<'_> {
    self.0.display()
  }
}

impl AsRef<Path> for SafePathBuf {
  fn as_ref(&self) -> &Path {
    self.0.as_ref()
  }
}

impl FromStr for SafePathBuf {
  type Err = &'static str;

  fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
    Self::new(s.into())
  }
}

impl From<SafePathBuf> for PathBuf {
  fn from(path: SafePathBuf) -> Self {
    path.0
  }
}

impl<'de> Deserialize<'de> for SafePathBuf {
  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  where
    D: Deserializer<'de>,
  {
    let path = PathBuf::deserialize(deserializer)?;
    SafePathBuf::new(path).map_err(DeError::custom)
  }
}

/// A base directory for a path.
///
/// The base directory is the optional root of a file system operation.
/// If informed by the API call, all paths will be relative to the path of the given directory.
///
/// For more information, check the [`dirs` documentation](https://docs.rs/dirs/).
#[derive(Serialize_repr, Deserialize_repr, Clone, Copy, Debug)]
#[repr(u16)]
#[non_exhaustive]
pub enum BaseDirectory {
  /// The Audio directory.
  /// Resolves to [`crate::path::PathResolver::audio_dir`].
  Audio = 1,
  /// The Cache directory.
  /// Resolves to [`crate::path::PathResolver::cache_dir`].
  Cache = 2,
  /// The Config directory.
  /// Resolves to [`crate::path::PathResolver::config_dir`].
  Config = 3,
  /// The Data directory.
  /// Resolves to [`crate::path::PathResolver::data_dir`].
  Data = 4,
  /// The LocalData directory.
  /// Resolves to [`crate::path::PathResolver::local_data_dir`].
  LocalData = 5,
  /// The Document directory.
  /// Resolves to [`crate::path::PathResolver::document_dir`].
  Document = 6,
  /// The Download directory.
  /// Resolves to [`crate::path::PathResolver::download_dir`].
  Download = 7,
  /// The Picture directory.
  /// Resolves to [`crate::path::PathResolver::picture_dir`].
  Picture = 8,
  /// The Public directory.
  /// Resolves to [`crate::path::PathResolver::public_dir`].
  Public = 9,
  /// The Video directory.
  /// Resolves to [`crate::path::PathResolver::video_dir`].
  Video = 10,
  /// The Resource directory.
  /// Resolves to [`crate::path::PathResolver::resource_dir`].
  Resource = 11,
  /// A temporary directory.
  /// Resolves to [`std::env::temp_dir`].
  Temp = 12,
  /// The default app config directory.
  /// Resolves to [`crate::path::PathResolver::app_config_dir`],
  /// which can be overridden with the `app > appDirectoriesOverride` config.
  AppConfig = 13,
  /// The default app data directory.
  /// Resolves to [`crate::path::PathResolver::app_data_dir`],
  /// which can be overridden with the `app > appDirectoriesOverride` config.
  AppData = 14,
  /// The default app local data directory.
  /// Resolves to [`crate::path::PathResolver::app_local_data_dir`],
  /// which can be overridden with the `app > appDirectoriesOverride` config.
  AppLocalData = 15,
  /// The default app cache directory.
  /// Resolves to [`crate::path::PathResolver::app_cache_dir`],
  /// which can be overridden with the `app > appDirectoriesOverride` config.
  AppCache = 16,
  /// The default app log directory.
  /// Resolves to [`crate::path::PathResolver::app_log_dir`],
  /// which can be overridden with the `app > appDirectoriesOverride` config.
  AppLog = 17,
  /// The Desktop directory.
  /// Resolves to [`crate::path::PathResolver::desktop_dir`].
  #[cfg(not(target_os = "android"))]
  Desktop = 18,
  /// The Executable directory.
  /// Resolves to [`crate::path::PathResolver::executable_dir`].
  #[cfg(not(target_os = "android"))]
  Executable = 19,
  /// The Font directory.
  /// Resolves to [`crate::path::PathResolver::font_dir`].
  #[cfg(not(target_os = "android"))]
  Font = 20,
  /// The Home directory.
  /// Resolves to [`crate::path::PathResolver::home_dir`].
  Home = 21,
  /// The Runtime directory.
  /// Resolves to [`crate::path::PathResolver::runtime_dir`].
  #[cfg(not(target_os = "android"))]
  Runtime = 22,
  /// The Template directory.
  /// Resolves to [`crate::path::PathResolver::template_dir`].
  #[cfg(not(target_os = "android"))]
  Template = 23,
}

impl BaseDirectory {
  /// Gets the variable that represents this [`BaseDirectory`] for string paths.
  pub fn variable(self) -> &'static str {
    match self {
      Self::Audio => "$AUDIO",
      Self::Cache => "$CACHE",
      Self::Config => "$CONFIG",
      Self::Data => "$DATA",
      Self::LocalData => "$LOCALDATA",
      Self::Document => "$DOCUMENT",
      Self::Download => "$DOWNLOAD",
      Self::Picture => "$PICTURE",
      Self::Public => "$PUBLIC",
      Self::Video => "$VIDEO",
      Self::Resource => "$RESOURCE",
      Self::Temp => "$TEMP",
      Self::AppConfig => "$APPCONFIG",
      Self::AppData => "$APPDATA",
      Self::AppLocalData => "$APPLOCALDATA",
      Self::AppCache => "$APPCACHE",
      Self::AppLog => "$APPLOG",
      Self::Home => "$HOME",

      #[cfg(not(target_os = "android"))]
      Self::Desktop => "$DESKTOP",
      #[cfg(not(target_os = "android"))]
      Self::Executable => "$EXE",
      #[cfg(not(target_os = "android"))]
      Self::Font => "$FONT",
      #[cfg(not(target_os = "android"))]
      Self::Runtime => "$RUNTIME",
      #[cfg(not(target_os = "android"))]
      Self::Template => "$TEMPLATE",
    }
  }

  /// Gets the [`BaseDirectory`] associated with the given variable, or [`None`] if the variable doesn't match any.
  pub fn from_variable(variable: &str) -> Option<Self> {
    let res = match variable {
      "$AUDIO" => Self::Audio,
      "$CACHE" => Self::Cache,
      "$CONFIG" => Self::Config,
      "$DATA" => Self::Data,
      "$LOCALDATA" => Self::LocalData,
      "$DOCUMENT" => Self::Document,
      "$DOWNLOAD" => Self::Download,

      "$PICTURE" => Self::Picture,
      "$PUBLIC" => Self::Public,
      "$VIDEO" => Self::Video,
      "$RESOURCE" => Self::Resource,
      "$TEMP" => Self::Temp,
      "$APPCONFIG" => Self::AppConfig,
      "$APPDATA" => Self::AppData,
      "$APPLOCALDATA" => Self::AppLocalData,
      "$APPCACHE" => Self::AppCache,
      "$APPLOG" => Self::AppLog,
      "$HOME" => Self::Home,

      #[cfg(not(target_os = "android"))]
      "$DESKTOP" => Self::Desktop,
      #[cfg(not(target_os = "android"))]
      "$EXE" => Self::Executable,
      #[cfg(not(target_os = "android"))]
      "$FONT" => Self::Font,
      #[cfg(not(target_os = "android"))]
      "$RUNTIME" => Self::Runtime,
      #[cfg(not(target_os = "android"))]
      "$TEMPLATE" => Self::Template,

      _ => return None,
    };
    Some(res)
  }
}

impl<R: Runtime> PathResolver<R> {
  /// Resolves the path with the base directory.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// use tauri::{path::BaseDirectory, Manager};
  /// tauri::Builder::default()
  ///   .setup(|app| {
  ///     let path = app.path().resolve("path/to/something", BaseDirectory::Config)?;
  ///     assert_eq!(path.to_str().unwrap(), "/home/${whoami}/.config/path/to/something");
  ///     Ok(())
  ///   });
  /// ```
  pub fn resolve<P: AsRef<Path>>(&self, path: P, base_directory: BaseDirectory) -> Result<PathBuf> {
    resolve_path::<R>(self, base_directory, Some(path.as_ref().to_path_buf()))
  }

  /// Parse the given path, resolving a [`BaseDirectory`] variable if the path starts with one.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// use tauri::Manager;
  /// tauri::Builder::default()
  ///   .setup(|app| {
  ///     let path = app.path().parse("$HOME/.bashrc")?;
  ///     assert_eq!(path.to_str().unwrap(), "/home/${whoami}/.bashrc");
  ///     Ok(())
  ///   });
  /// ```
  pub fn parse<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
    let mut p = PathBuf::new();
    let mut components = path.as_ref().components();
    match components.next() {
      Some(Component::Normal(str)) => {
        if let Some(base_directory) = BaseDirectory::from_variable(&str.to_string_lossy()) {
          p.push(resolve_path::<R>(self, base_directory, None)?);
        } else {
          p.push(str);
        }
      }
      Some(component) => p.push(component),
      None => (),
    }

    for component in components {
      if let Component::ParentDir = component {
        continue;
      }
      p.push(component);
    }

    Ok(p)
  }
}

fn resolve_path<R: Runtime>(
  resolver: &PathResolver<R>,
  directory: BaseDirectory,
  path: Option<PathBuf>,
) -> Result<PathBuf> {
  let resolve_resource = matches!(directory, BaseDirectory::Resource);
  let mut base_dir_path = match directory {
    BaseDirectory::Audio => resolver.audio_dir(),
    BaseDirectory::Cache => resolver.cache_dir(),
    BaseDirectory::Config => resolver.config_dir(),
    BaseDirectory::Data => resolver.data_dir(),
    BaseDirectory::LocalData => resolver.local_data_dir(),
    BaseDirectory::Document => resolver.document_dir(),
    BaseDirectory::Download => resolver.download_dir(),
    BaseDirectory::Picture => resolver.picture_dir(),
    BaseDirectory::Public => resolver.public_dir(),
    BaseDirectory::Video => resolver.video_dir(),
    BaseDirectory::Resource => resolver.resource_dir(),
    BaseDirectory::Temp => resolver.temp_dir(),
    BaseDirectory::AppConfig => resolver.app_config_dir(),
    BaseDirectory::AppData => resolver.app_data_dir(),
    BaseDirectory::AppLocalData => resolver.app_local_data_dir(),
    BaseDirectory::AppCache => resolver.app_cache_dir(),
    BaseDirectory::AppLog => resolver.app_log_dir(),
    BaseDirectory::Home => resolver.home_dir(),
    #[cfg(not(target_os = "android"))]
    BaseDirectory::Desktop => resolver.desktop_dir(),
    #[cfg(not(target_os = "android"))]
    BaseDirectory::Executable => resolver.executable_dir(),
    #[cfg(not(target_os = "android"))]
    BaseDirectory::Font => resolver.font_dir(),
    #[cfg(not(target_os = "android"))]
    BaseDirectory::Runtime => resolver.runtime_dir(),
    #[cfg(not(target_os = "android"))]
    BaseDirectory::Template => resolver.template_dir(),
  }?;

  if let Some(path) = path {
    // use the same path resolution mechanism as the bundler's resource injection algorithm
    if resolve_resource {
      let mut resource_path = PathBuf::new();
      for component in path.components() {
        match component {
          Component::Prefix(_) => {}
          Component::RootDir => resource_path.push("_root_"),
          Component::CurDir => {}
          Component::ParentDir => resource_path.push("_up_"),
          Component::Normal(p) => resource_path.push(p),
        }
      }
      base_dir_path.push(resource_path);
    } else {
      base_dir_path.push(path);
    }
  }

  Ok(base_dir_path)
}

/// An app-specific directory that can be overridden with the `app > appDirectoriesOverride` config.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AppDirectory {
  Config,
  Data,
  LocalData,
  Cache,
  Log,
}

impl AppDirectory {
  /// The subdirectory this directory resolves to when a single root overrides all app directories.
  fn root_override_subdirectory(self) -> Option<&'static str> {
    match self {
      Self::Cache => Some("caches"),
      Self::Log => Some("logs"),
      Self::Config | Self::Data | Self::LocalData => None,
    }
  }
}

impl<R: Runtime> PathResolver<R> {
  /// Resolves an app directory, honoring the `app > appDirectoriesOverride` config.
  pub(crate) fn app_dir(
    &self,
    dir: AppDirectory,
    default: impl FnOnce() -> Result<PathBuf>,
  ) -> Result<PathBuf> {
    match self.app_directory_override(dir)? {
      Some(path) => Ok(path),
      None => default(),
    }
  }

  /// Resolves the override configured for the given app directory, if any.
  fn app_directory_override(&self, dir: AppDirectory) -> Result<Option<PathBuf>> {
    let Some(config) = &self.app_handle().config().app.app_directories_override else {
      return Ok(None);
    };

    let (path, subdirectory) = match config {
      AppDirectoriesOverride::Root(root) => (root, dir.root_override_subdirectory()),
      AppDirectoriesOverride::Directories(directories) => {
        let path = match dir {
          AppDirectory::Config => &directories.config,
          AppDirectory::Data => &directories.data,
          AppDirectory::LocalData => &directories.local_data,
          AppDirectory::Cache => &directories.cache,
          AppDirectory::Log => &directories.log,
        };
        match path {
          Some(path) => (path, None),
          None => return Ok(None),
        }
      }
    };

    let mut path = self.resolve_override_path(path)?;
    if let Some(subdirectory) = subdirectory {
      path.push(subdirectory);
    }

    Ok(Some(path))
  }

  /// Resolves a path from the `app > appDirectoriesOverride` config:
  ///
  /// - a path starting with a base directory variable (e.g. `$DATA/my-app`) is resolved against that directory,
  /// - an absolute path is used as is,
  /// - any other path is resolved relative to the app binary directory on desktop,
  ///   and rejected on mobile where the app bundle is read-only.
  fn resolve_override_path(&self, path: &Path) -> Result<PathBuf> {
    let mut components = path.components();
    let first = components.next();

    if let Some(Component::Normal(first)) = first {
      if let Some(variable) = first.to_str().filter(|s| s.starts_with('$')) {
        let base_directory = BaseDirectory::from_variable(variable).ok_or_else(|| {
          Error::InvalidAppDirectoriesOverride(
            path.to_path_buf(),
            format!("unknown base directory variable `{variable}`"),
          )
        })?;

        if matches!(
          base_directory,
          BaseDirectory::AppConfig
            | BaseDirectory::AppData
            | BaseDirectory::AppLocalData
            | BaseDirectory::AppCache
            | BaseDirectory::AppLog
        ) {
          return Err(Error::InvalidAppDirectoriesOverride(
            path.to_path_buf(),
            format!("`{variable}` refers to an app directory, which is what is being overridden"),
          ));
        }

        // unlike `parse`, `resolve` keeps `..` components
        return self
          .resolve(components.as_path(), base_directory)
          .map(normalize);
      }
    }

    if path.is_absolute() {
      return Ok(normalize(path));
    }

    // Windows root-relative (`\foo`) and drive-relative (`C:foo`) paths would replace the base directory on join
    if path.has_root() || matches!(first, Some(Component::Prefix(_))) {
      return Err(Error::InvalidAppDirectoriesOverride(
        path.to_path_buf(),
        "root-relative and drive-relative paths are not supported".into(),
      ));
    }

    #[cfg(desktop)]
    {
      Ok(normalize(self.app_binary_dir()?.join(path)))
    }
    #[cfg(mobile)]
    {
      Err(Error::InvalidAppDirectoriesOverride(
        path.to_path_buf(),
        "relative paths are not supported on Android and iOS, use a base directory variable or an absolute path".into(),
      ))
    }
  }
}

/// Removes `.` components and trailing separators from a path, keeping `..` components.
fn normalize(path: impl AsRef<Path>) -> PathBuf {
  path.as_ref().components().collect()
}

#[cfg(test)]
mod test {
  use super::SafePathBuf;
  use quickcheck::{Arbitrary, Gen};

  use std::path::PathBuf;

  impl Arbitrary for SafePathBuf {
    fn arbitrary(g: &mut Gen) -> Self {
      Self(PathBuf::arbitrary(g))
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
      Box::new(self.0.shrink().map(SafePathBuf))
    }
  }
}