apksigner 1.0.0

APK signer and verifier CLI — a faithful Rust port of AOSP apksigner
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
//! Mirrors `com.android.apksigner.OptionsParser`.
//!
//! Parser of command-line options/switches/flags.
//!
//! Supported option formats:
//! * `--name value`
//! * `--name=value`
//! * `-name value`
//! * `--name` (boolean options only)
//!
//! To use the parser, create an instance providing it with the command-line parameters, then
//! iterate over options by invoking [`OptionsParser::next_option`] until it returns `None`.
//!
//! ## Mapping notes
//!
//! The Java class signals "no more options" by returning `null` from `nextOption()`, and
//! reports malformed input through `OptionsException`. Here `next_option` returns
//! `Result<Option<String>, OptionsException>`, where `Ok(None)` is the Java `null`.
//!
//! `mLastOptionOriginalForm` is a `String` that starts out `null` in Java. Java's string
//! concatenation renders that as the literal text `"null"`, so the error messages built here do
//! the same to keep the wording identical.

use std::fmt;

/// Mirrors `OptionsParser.OptionsException`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OptionsException {
    pub message: String,
}

impl OptionsException {
    pub fn new(message: impl Into<String>) -> Self {
        OptionsException {
            message: message.into(),
        }
    }
}

impl fmt::Display for OptionsException {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for OptionsException {}

/// Mirrors `com.android.apksigner.OptionsParser`.
pub struct OptionsParser {
    params: Vec<String>,
    index: usize,
    put_back_index: usize,
    last_option_value: Option<String>,
    put_back_last_option_value: Option<String>,
    last_option_original_form: Option<String>,
    put_back_last_option_original_form: Option<String>,
}

impl OptionsParser {
    /// Constructs a new parser initialized with the provided command-line.
    pub fn new(params: &[String]) -> Self {
        OptionsParser {
            params: params.to_vec(),
            index: 0,
            put_back_index: 0,
            last_option_value: None,
            put_back_last_option_value: None,
            last_option_original_form: None,
            put_back_last_option_original_form: None,
        }
    }

    /// Returns the name (without leading dashes) of the next option, or `Ok(None)` if there are
    /// no options left.
    ///
    /// The value of this option can be obtained via [`OptionsParser::get_required_value`],
    /// [`OptionsParser::get_required_int_value`], and
    /// [`OptionsParser::get_optional_boolean_value`].
    #[allow(clippy::manual_strip)] // the indices are absolute, so slicing mirrors Java
    pub fn next_option(&mut self) -> Result<Option<String>, OptionsException> {
        if self.index >= self.params.len() {
            // No more parameters left.
            return Ok(None);
        }
        let param = self.params[self.index].clone();
        if !param.starts_with('-') {
            // Not an option.
            return Ok(None);
        }

        self.put_back_index = self.index;
        self.index += 1;
        self.put_back_last_option_original_form = self.last_option_original_form.clone();
        self.last_option_original_form = Some(param.clone());
        self.put_back_last_option_value = self.last_option_value.clone();
        self.last_option_value = None;

        if param.starts_with("--") {
            // FORMAT: --name value OR --name=value
            if param == "--" {
                // End of options marker.
                return Ok(None);
            }
            match param.find('=') {
                Some(value_delimiter_index) => {
                    self.last_option_value = Some(param[value_delimiter_index + 1..].to_string());
                    self.last_option_original_form =
                        Some(param[..value_delimiter_index].to_string());
                    Ok(Some(param["--".len()..value_delimiter_index].to_string()))
                }
                None => Ok(Some(param["--".len()..].to_string())),
            }
        } else {
            // FORMAT: -name value
            Ok(Some(param["-".len()..].to_string()))
        }
    }

    /// Undoes the last call to [`OptionsParser::next_option`], if one was made.
    ///
    /// This allows callers to unwind state so as not to consume an option that is meant to be
    /// processed elsewhere.
    pub fn put_option(&mut self) {
        self.index = self.put_back_index;
        self.last_option_original_form = self.put_back_last_option_original_form.clone();
        self.last_option_value = self.put_back_last_option_value.clone();
    }

    /// Returns the original form of the current option, including the leading dash or dashes.
    ///
    /// This is intended to be used for referencing the option in error messages.
    pub fn get_option_original_form(&self) -> Option<String> {
        self.last_option_original_form.clone()
    }

    /// The original form of the current option, rendered the way Java string concatenation
    /// renders a `null` String.
    fn original_form_for_message(&self) -> String {
        match &self.last_option_original_form {
            Some(form) => form.clone(),
            None => "null".to_string(),
        }
    }

    /// Returns the value of the current option, failing if the value is missing.
    pub fn get_required_value(
        &mut self,
        value_description: &str,
    ) -> Result<String, OptionsException> {
        if let Some(value) = self.last_option_value.take() {
            return Ok(value);
        }
        if self.index >= self.params.len() {
            // No more parameters left.
            return Err(OptionsException::new(format!(
                "{} missing after {}",
                value_description,
                self.original_form_for_message()
            )));
        }
        let param = self.params[self.index].clone();
        if param == "--" {
            // End of options marker.
            return Err(OptionsException::new(format!(
                "{} missing after {}",
                value_description,
                self.original_form_for_message()
            )));
        }
        self.index += 1;
        Ok(param)
    }

    /// Returns the value of the current numeric option, failing if the value is missing or is
    /// not numeric.
    pub fn get_required_int_value(
        &mut self,
        value_description: &str,
    ) -> Result<i32, OptionsException> {
        let value = self.get_required_value(value_description)?;
        match parse_java_int(&value) {
            Some(parsed) => Ok(parsed),
            None => Err(OptionsException::new(format!(
                "{} ({}) must be a decimal number: {}",
                value_description,
                self.original_form_for_message(),
                value
            ))),
        }
    }

    /// Gets the value of the current boolean option.
    ///
    /// Boolean options are not required to have explicitly specified values.
    pub fn get_optional_boolean_value(
        &mut self,
        default_value: bool,
    ) -> Result<bool, OptionsException> {
        if let Some(string_value) = self.last_option_value.take() {
            // --option=value form
            return match string_value.as_str() {
                "true" => Ok(true),
                "false" => Ok(false),
                _ => Err(OptionsException::new(format!(
                    "Unsupported value for {}: {}. Only true or false supported.",
                    self.original_form_for_message(),
                    string_value
                ))),
            };
        }

        // --option (true|false) form OR just --option
        if self.index >= self.params.len() {
            return Ok(default_value);
        }

        let string_value = self.params[self.index].clone();
        if string_value == "true" {
            self.index += 1;
            Ok(true)
        } else if string_value == "false" {
            self.index += 1;
            Ok(false)
        } else {
            Ok(default_value)
        }
    }

    /// Returns the remaining command-line parameters.
    ///
    /// This is intended to be invoked once [`OptionsParser::next_option`] returns `None`.
    pub fn get_remaining_params(&self) -> Vec<String> {
        if self.index >= self.params.len() {
            return Vec::new();
        }
        let param = &self.params[self.index];
        if param == "--" {
            // Skip end of options marker.
            self.params[self.index + 1..].to_vec()
        } else {
            self.params[self.index..].to_vec()
        }
    }
}

/// Parses a decimal integer the way `Integer.parseInt` does: an optional leading `+` or `-`
/// followed by one or more ASCII digits, with overflow rejected.
fn parse_java_int(value: &str) -> Option<i32> {
    let bytes = value.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    let (negative, digits) = match bytes[0] {
        b'-' => (true, &bytes[1..]),
        b'+' => (false, &bytes[1..]),
        _ => (false, bytes),
    };
    if digits.is_empty() {
        return None;
    }

    let mut magnitude: u64 = 0;
    for &b in digits {
        if !b.is_ascii_digit() {
            return None;
        }
        magnitude = magnitude.checked_mul(10)?.checked_add((b - b'0') as u64)?;
    }

    if negative {
        if magnitude > (i32::MAX as u64) + 1 {
            return None;
        }
        if magnitude == (i32::MAX as u64) + 1 {
            return Some(i32::MIN);
        }
        Some(-(magnitude as i64) as i32)
    } else {
        if magnitude > i32::MAX as u64 {
            return None;
        }
        Some(magnitude as i32)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn params(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn parses_double_dash_space_form() {
        let mut p = OptionsParser::new(&params(&["--ks", "release.jks", "app.apk"]));
        assert_eq!(p.next_option().unwrap(), Some("ks".to_string()));
        assert_eq!(
            p.get_required_value("KeyStore file").unwrap(),
            "release.jks"
        );
        assert_eq!(p.get_option_original_form().unwrap(), "--ks");
        assert_eq!(p.next_option().unwrap(), None);
        assert_eq!(p.get_remaining_params(), params(&["app.apk"]));
    }

    #[test]
    fn parses_double_dash_equals_form() {
        let mut p = OptionsParser::new(&params(&["--ks=release.jks"]));
        assert_eq!(p.next_option().unwrap(), Some("ks".to_string()));
        // The original form drops the value part for the `=` form.
        assert_eq!(p.get_option_original_form().unwrap(), "--ks");
        assert_eq!(
            p.get_required_value("KeyStore file").unwrap(),
            "release.jks"
        );
    }

    #[test]
    fn parses_single_dash_form() {
        let mut p = OptionsParser::new(&params(&["-v", "app.apk"]));
        assert_eq!(p.next_option().unwrap(), Some("v".to_string()));
        assert_eq!(p.get_option_original_form().unwrap(), "-v");
    }

    #[test]
    fn stops_at_first_non_option() {
        let mut p = OptionsParser::new(&params(&["app.apk", "--ks", "x.jks"]));
        assert_eq!(p.next_option().unwrap(), None);
        assert_eq!(
            p.get_remaining_params(),
            params(&["app.apk", "--ks", "x.jks"])
        );
    }

    #[test]
    fn double_dash_is_end_of_options_marker() {
        let mut p = OptionsParser::new(&params(&["--", "app.apk"]));
        assert_eq!(p.next_option().unwrap(), None);
        assert_eq!(p.get_remaining_params(), params(&["app.apk"]));
    }

    #[test]
    fn missing_value_reports_option_original_form() {
        let mut p = OptionsParser::new(&params(&["--ks"]));
        assert_eq!(p.next_option().unwrap(), Some("ks".to_string()));
        let err = p.get_required_value("KeyStore file").unwrap_err();
        assert_eq!(err.to_string(), "KeyStore file missing after --ks");
    }

    #[test]
    fn missing_value_before_end_of_options_marker_is_an_error() {
        let mut p = OptionsParser::new(&params(&["--ks", "--"]));
        assert_eq!(p.next_option().unwrap(), Some("ks".to_string()));
        let err = p.get_required_value("KeyStore file").unwrap_err();
        assert_eq!(err.to_string(), "KeyStore file missing after --ks");
    }

    #[test]
    fn int_value_reports_non_numeric_input() {
        let mut p = OptionsParser::new(&params(&["--min-sdk-version", "abc"]));
        assert_eq!(
            p.next_option().unwrap(),
            Some("min-sdk-version".to_string())
        );
        let err = p.get_required_int_value("Mininimum API Level").unwrap_err();
        assert_eq!(
            err.to_string(),
            "Mininimum API Level (--min-sdk-version) must be a decimal number: abc"
        );
    }

    #[test]
    fn int_value_accepts_plain_decimal() {
        let mut p = OptionsParser::new(&params(&["--min-sdk-version", "24"]));
        assert_eq!(
            p.next_option().unwrap(),
            Some("min-sdk-version".to_string())
        );
        assert_eq!(p.get_required_int_value("Mininimum API Level").unwrap(), 24);
    }

    #[test]
    fn boolean_option_defaults_when_bare() {
        let mut p = OptionsParser::new(&params(&["--v1-signing-enabled", "--next-signer"]));
        assert_eq!(
            p.next_option().unwrap(),
            Some("v1-signing-enabled".to_string())
        );
        assert!(p.get_optional_boolean_value(true).unwrap());
        // The bare form must not consume the following option.
        assert_eq!(p.next_option().unwrap(), Some("next-signer".to_string()));
    }

    #[test]
    fn boolean_option_accepts_separate_value() {
        let mut p = OptionsParser::new(&params(&["--v1-signing-enabled", "false"]));
        assert_eq!(
            p.next_option().unwrap(),
            Some("v1-signing-enabled".to_string())
        );
        assert!(!p.get_optional_boolean_value(true).unwrap());
    }

    #[test]
    fn boolean_option_accepts_equals_value() {
        let mut p = OptionsParser::new(&params(&["--v2-signing-enabled=false"]));
        assert_eq!(
            p.next_option().unwrap(),
            Some("v2-signing-enabled".to_string())
        );
        assert!(!p.get_optional_boolean_value(true).unwrap());
    }

    #[test]
    fn boolean_option_rejects_other_values() {
        let mut p = OptionsParser::new(&params(&["--v2-signing-enabled=maybe"]));
        assert_eq!(
            p.next_option().unwrap(),
            Some("v2-signing-enabled".to_string())
        );
        let err = p.get_optional_boolean_value(true).unwrap_err();
        assert_eq!(
            err.to_string(),
            "Unsupported value for --v2-signing-enabled: maybe. Only true or false supported."
        );
    }

    #[test]
    fn boolean_option_leaves_default_when_next_param_is_not_boolean() {
        let mut p = OptionsParser::new(&params(&["--verbose", "app.apk"]));
        assert_eq!(p.next_option().unwrap(), Some("verbose".to_string()));
        assert!(p.get_optional_boolean_value(true).unwrap());
        assert_eq!(p.get_remaining_params(), params(&["app.apk"]));
    }

    #[test]
    fn put_option_undoes_the_last_next_option() {
        let mut p = OptionsParser::new(&params(&["--next-signer", "--ks", "x.jks"]));
        assert_eq!(p.next_option().unwrap(), Some("next-signer".to_string()));
        p.put_option();
        assert_eq!(p.next_option().unwrap(), Some("next-signer".to_string()));
        assert_eq!(p.next_option().unwrap(), Some("ks".to_string()));
    }

    #[test]
    fn put_option_restores_the_original_form() {
        let mut p = OptionsParser::new(&params(&["--ks", "--out"]));
        assert_eq!(p.next_option().unwrap(), Some("ks".to_string()));
        assert_eq!(p.get_option_original_form().unwrap(), "--ks");
        p.put_option();
        assert_eq!(p.next_option().unwrap(), Some("ks".to_string()));
        assert_eq!(p.get_option_original_form().unwrap(), "--ks");
    }

    #[test]
    fn remaining_params_are_empty_when_exhausted() {
        let mut p = OptionsParser::new(&params(&["--verbose"]));
        assert_eq!(p.next_option().unwrap(), Some("verbose".to_string()));
        assert!(p.get_optional_boolean_value(true).unwrap());
        assert_eq!(p.next_option().unwrap(), None);
        assert!(p.get_remaining_params().is_empty());
    }

    #[test]
    fn java_int_parsing_matches_parse_int_bounds() {
        assert_eq!(parse_java_int("0"), Some(0));
        assert_eq!(parse_java_int("+7"), Some(7));
        assert_eq!(parse_java_int("-7"), Some(-7));
        assert_eq!(parse_java_int("2147483647"), Some(i32::MAX));
        assert_eq!(parse_java_int("-2147483648"), Some(i32::MIN));
        assert_eq!(parse_java_int("2147483648"), None);
        assert_eq!(parse_java_int("-2147483649"), None);
        assert_eq!(parse_java_int(""), None);
        assert_eq!(parse_java_int("-"), None);
        assert_eq!(parse_java_int("1.5"), None);
        assert_eq!(parse_java_int(" 1"), None);
    }
}