Skip to content

Commit f45ec0d

Browse files
authored
Merge commit from fork
* feat(cli): record app version in updater signature trusted comment * plugin add changes
1 parent 2014373 commit f45ec0d

5 files changed

Lines changed: 224 additions & 9 deletions

File tree

‎.changes/updater-sign-version.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
"tauri-cli": "minor:feat"
3+
"@tauri-apps/cli": "minor:feat"
4+
---
5+
6+
Record the app version in the trusted comment of updater signatures, so a signed artifact is bound to the version it was released as.
7+
8+
An update endpoint response is not signed, and the signature only covers the downloaded artifact, so the announced `version` on its own does not prove which release the `url` and `signature` point at. minisign covers the trusted comment with its global signature, which lets the updater plugin compare the two and reject a response that pairs a version number with a different release. Enable `requireSignedVersion` in the updater plugin configuration to enforce this.
9+
10+
`tauri build` fills the version in automatically, and `tauri plugin add updater` now enables `requireSignedVersion` for the project it is adding the plugin to. `tauri signer sign` gains an `--app-version` flag for signing updater artifacts by hand, and warns when it is omitted.

‎crates/tauri-cli/src/add.rs‎

Lines changed: 125 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,17 @@ use regex::Regex;
88

99
use crate::{
1010
Result, acl,
11-
error::ErrorExt,
11+
error::{Context, ErrorExt},
1212
helpers::{
1313
app_paths::{Dirs, resolve_frontend_dir},
1414
cargo,
15+
config::Target,
1516
npm::PackageManager,
1617
},
1718
};
1819

19-
use std::process::Command;
20+
use serde_json::Value as JsonValue;
21+
use std::{fs, path::Path, process::Command};
2022

2123
#[derive(Debug, Parser)]
2224
#[clap(about = "Add a tauri plugin to the project")]
@@ -124,6 +126,16 @@ pub fn run(options: Options, dirs: &Dirs) -> Result<()> {
124126
});
125127
}
126128

129+
if plugin == "updater" {
130+
// not fatal: the plugin is installed by this point, and the developer can set the option by
131+
// hand if we could not
132+
if let Err(e) = enable_require_signed_version(dirs.tauri) {
133+
log::warn!(
134+
"Failed to enable `plugins > updater > requireSignedVersion`, set it manually: {e}"
135+
);
136+
}
137+
}
138+
127139
// add plugin init code to main.rs or lib.rs
128140
let plugin_init_fn = if plugin == "stronghold" {
129141
"Builder::new(|pass| todo!()).build()"
@@ -203,3 +215,114 @@ pub fn run(options: Options, dirs: &Dirs) -> Result<()> {
203215

204216
Ok(())
205217
}
218+
219+
/// Turns on the updater's signed version check for a project adopting the plugin now.
220+
///
221+
/// An update endpoint response is not signed, so the version it announces does not by itself
222+
/// prove which release its `url` and `signature` point at. `requireSignedVersion` makes the
223+
/// updater compare that version against the one recorded inside the signature, which is what
224+
/// stops a tampered response from pairing a new version number with an older release to force a
225+
/// downgrade.
226+
///
227+
/// This can only be the default for a project adding the plugin now, because the check also
228+
/// rejects releases that were signed before the version was recorded. A project already serving
229+
/// such releases has to re-sign them first, so a value that is already in the config is left
230+
/// alone.
231+
fn enable_require_signed_version(tauri_dir: &Path) -> Result<()> {
232+
let (mut config, config_path) =
233+
tauri_utils::config::parse::parse_value(Target::current(), tauri_dir.join("tauri.conf.json"))
234+
.context("failed to parse config")?;
235+
236+
if !set_require_signed_version(&mut config) {
237+
return Ok(());
238+
}
239+
240+
let serialized = if config_path.extension().is_some_and(|ext| ext == "toml") {
241+
toml::to_string_pretty(&config).context("failed to serialize config")?
242+
} else {
243+
serde_json::to_string_pretty(&config).context("failed to serialize config")?
244+
};
245+
fs::write(&config_path, serialized).fs_context("failed to write config", config_path.clone())?;
246+
247+
log::info!(
248+
"Enabled `plugins > updater > requireSignedVersion` in {}",
249+
config_path.display()
250+
);
251+
log::info!("Remember to set `plugins > updater > pubkey` and `endpoints`.");
252+
253+
Ok(())
254+
}
255+
256+
/// Sets `plugins > updater > requireSignedVersion`, returning whether the config changed.
257+
fn set_require_signed_version(config: &mut JsonValue) -> bool {
258+
let Some(root) = config.as_object_mut() else {
259+
return false;
260+
};
261+
let plugins = root
262+
.entry("plugins")
263+
.or_insert_with(|| JsonValue::Object(Default::default()));
264+
let Some(plugins) = plugins.as_object_mut() else {
265+
return false;
266+
};
267+
let updater = plugins
268+
.entry("updater")
269+
.or_insert_with(|| JsonValue::Object(Default::default()));
270+
let Some(updater) = updater.as_object_mut() else {
271+
return false;
272+
};
273+
274+
// a value already in the config is a deliberate choice, an explicit `false` included
275+
if updater.contains_key("requireSignedVersion") || updater.contains_key("require-signed-version")
276+
{
277+
return false;
278+
}
279+
280+
updater.insert("requireSignedVersion".into(), JsonValue::Bool(true));
281+
true
282+
}
283+
284+
#[cfg(test)]
285+
mod tests {
286+
use super::set_require_signed_version;
287+
use serde_json::json;
288+
289+
#[test]
290+
fn enables_required_version_signing_on_a_config_without_updater_plugin_config() {
291+
let mut config = json!({ "identifier": "com.tauri.dev" });
292+
assert!(set_require_signed_version(&mut config));
293+
assert_eq!(config["plugins"]["updater"]["requireSignedVersion"], true);
294+
// the rest of the config is carried through untouched
295+
assert_eq!(config["identifier"], "com.tauri.dev");
296+
}
297+
298+
#[test]
299+
fn keeps_the_existing_updater_config() {
300+
let mut config = json!({ "plugins": { "updater": { "pubkey": "abc" } } });
301+
assert!(set_require_signed_version(&mut config));
302+
assert_eq!(config["plugins"]["updater"]["pubkey"], "abc");
303+
assert_eq!(config["plugins"]["updater"]["requireSignedVersion"], true);
304+
}
305+
306+
#[test]
307+
fn never_overwrites_a_deliberate_choice() {
308+
// a project that still serves releases signed before the version was recorded has to keep
309+
// this off until it has re-signed them, so an explicit `false` must survive
310+
for existing in ["requireSignedVersion", "require-signed-version"] {
311+
let mut config = json!({ "plugins": { "updater": { existing: false } } });
312+
assert!(!set_require_signed_version(&mut config));
313+
assert_eq!(config["plugins"]["updater"][existing], false);
314+
assert!(
315+
config["plugins"]["updater"]
316+
.as_object()
317+
.is_some_and(|updater| updater.len() == 1)
318+
);
319+
}
320+
}
321+
322+
#[test]
323+
fn leaves_a_config_it_cannot_understand_alone() {
324+
let mut config = json!({ "plugins": { "updater": "not an object" } });
325+
assert!(!set_require_signed_version(&mut config));
326+
assert_eq!(config["plugins"]["updater"], "not an object");
327+
}
328+
}

‎crates/tauri-cli/src/bundle.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,8 @@ fn sign_updaters(
311311
// another type of updater package who require multiple file signature
312312
for path in &bundle.bundle_paths {
313313
// sign our path from environment variables
314-
let (signature_path, signature) = updater_signature::sign_file(&secret_key, path)?;
314+
let (signature_path, signature) =
315+
updater_signature::sign_file(&secret_key, path, Some(settings.version_string()))?;
315316
if signature.keynum() != public_key.keynum() {
316317
log::warn!(
317318
"The updater secret key from `TAURI_SIGNING_PRIVATE_KEY` does not match the public key from `plugins > updater > pubkey`. If you are not rotating keys, this means your configuration is wrong and won't be accepted at runtime when performing update."

‎crates/tauri-cli/src/helpers/updater_signature.rs‎

Lines changed: 65 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,17 @@ where
114114
}
115115

116116
/// Sign files
117-
pub fn sign_file<P>(secret_key: &SecretKey, bin_path: P) -> crate::Result<(PathBuf, SignatureBox)>
117+
///
118+
/// When `version` is given it is embedded in the signature's trusted comment. minisign covers
119+
/// the trusted comment with its global signature, so this binds the signed artifact to the
120+
/// version it was released as. The update manifest is not itself signed, so without this the
121+
/// manifest's `version` field can be paired with an older release's URL and signature to force
122+
/// a downgrade. See the `requireSignedVersion` updater config option.
123+
pub fn sign_file<P>(
124+
secret_key: &SecretKey,
125+
bin_path: P,
126+
version: Option<&str>,
127+
) -> crate::Result<(PathBuf, SignatureBox)>
118128
where
119129
P: AsRef<Path>,
120130
{
@@ -129,11 +139,23 @@ where
129139
bin_path.with_extension("sig")
130140
};
131141

132-
let trusted_comment = format!(
142+
let mut trusted_comment = format!(
133143
"timestamp:{}\tfile:{}",
134144
unix_timestamp(),
135145
bin_path.file_name().unwrap().to_string_lossy()
136146
);
147+
if let Some(version) = version {
148+
// the trusted comment is a single line of tab separated fields, so a version carrying
149+
// either separator would produce a signature we cannot parse back
150+
if version.contains(['\t', '\r', '\n']) {
151+
crate::error::bail!(
152+
"the app version {version:?} cannot be signed because it contains a tab or newline"
153+
);
154+
}
155+
// appended last so anything parsing the historical `timestamp:...\tfile:...` prefix keeps working
156+
trusted_comment.push_str("\tversion:");
157+
trusted_comment.push_str(version);
158+
}
137159

138160
let data_reader = open_data_file(bin_path)?;
139161

@@ -219,7 +241,47 @@ mod tests {
219241

220242
let secret_key =
221243
secret_key(PRIVATE_KEY, Some("".into())).expect("failed to resolve secret key");
222-
sign_file(&secret_key, &path).expect("failed to sign file");
244+
sign_file(&secret_key, &path, None).expect("failed to sign file");
245+
}
246+
247+
#[test]
248+
fn embeds_version_in_trusted_comment() {
249+
let path = std::env::temp_dir().join("minisign-versioned-text.txt");
250+
std::fs::write(&path, b"TAURI").expect("failed to write test file");
251+
252+
let secret_key =
253+
secret_key(PRIVATE_KEY, Some("".into())).expect("failed to resolve secret key");
254+
255+
let (_, signature) = sign_file(&secret_key, &path, Some("1.2.3")).expect("failed to sign file");
256+
let trusted_comment = signature
257+
.trusted_comment()
258+
.expect("failed to read trusted comment");
259+
assert!(
260+
trusted_comment.ends_with("\tversion:1.2.3"),
261+
"unexpected trusted comment: {trusted_comment}"
262+
);
263+
// the historical prefix must stay intact so older consumers keep parsing it
264+
assert!(trusted_comment.starts_with("timestamp:"));
265+
assert!(trusted_comment.contains("\tfile:minisign-versioned-text.txt\t"));
266+
267+
let (_, signature) = sign_file(&secret_key, &path, None).expect("failed to sign file");
268+
assert!(
269+
!signature
270+
.trusted_comment()
271+
.expect("failed to read trusted comment")
272+
.contains("version:")
273+
);
274+
}
275+
276+
#[test]
277+
fn rejects_version_that_breaks_the_trusted_comment() {
278+
let path = std::env::temp_dir().join("minisign-invalid-version-text.txt");
279+
std::fs::write(&path, b"TAURI").expect("failed to write test file");
280+
281+
let secret_key =
282+
secret_key(PRIVATE_KEY, Some("".into())).expect("failed to resolve secret key");
283+
assert!(sign_file(&secret_key, &path, Some("1.0.0\ttampered")).is_err());
284+
assert!(sign_file(&secret_key, &path, Some("1.0.0\ntampered")).is_err());
223285
}
224286

225287
// This tests the newly generated keys with empty string password works

‎crates/tauri-cli/src/signer/sign.rs‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,16 @@ pub struct Options {
3535
/// Set private key password when signing
3636
#[clap(short, long, env = "TAURI_SIGNING_PRIVATE_KEY_PASSWORD")]
3737
password: Option<String>,
38+
/// Bind the signature to this app version.
39+
///
40+
/// The version is embedded in the signature's trusted comment, which is covered by the
41+
/// signature itself. Updaters configured with `requireSignedVersion` reject an update whose
42+
/// manifest announces a different version than the one signed here, which prevents a
43+
/// tampered manifest from pairing a new version number with an older release.
44+
///
45+
/// `tauri build` sets this automatically; pass it when signing updater artifacts by hand.
46+
#[clap(long)]
47+
app_version: Option<String>,
3848
/// Sign the specified file
3949
file: PathBuf,
4050
}
@@ -88,9 +98,18 @@ pub fn command(mut options: Options) -> Result<()> {
8898
println!("Signing without password.");
8999
}
90100

91-
let (manifest_dir, signature) =
92-
sign_file(&secret_key(private_key, options.password)?, options.file)
93-
.with_context(|| "failed to sign file")?;
101+
if options.app_version.is_none() {
102+
println!(
103+
"Signing without an app version. Pass --app-version to bind this signature to a version; updaters configured with `requireSignedVersion` will reject this signature."
104+
);
105+
}
106+
107+
let (manifest_dir, signature) = sign_file(
108+
&secret_key(private_key, options.password)?,
109+
options.file,
110+
options.app_version.as_deref(),
111+
)
112+
.with_context(|| "failed to sign file")?;
94113

95114
println!(
96115
"\nYour file was signed successfully, You can find the signature here:\n{}\n\nPublic signature:\n{}\n\nMake sure to include this into the signature field of your update server.",

0 commit comments

Comments
 (0)