rust-apk 1.0.0

Build, align, sign, verify, and inspect Android APKs in pure Rust
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
//! `AndroidManifest.xml`.
//!
//! A [`Manifest`] is the XML [`Document`] itself, with typed accessors for
//! the facts tools need and setters for the ones builders change. There is
//! no second schema to keep in step with Android: anything else is edited
//! through the element tree, with framework attributes typed by the
//! platform's own definitions ([`AttrDef::parse`]).
//!
//! ```
//! use apk::android::attr;
//! use apk::manifest::{self, Manifest};
//! use apk::{ClassName, PackageName};
//!
//! let mut manifest = Manifest::new(&PackageName::try_new("org.example.game")?);
//! manifest.add_permission(&"android.permission.INTERNET".parse()?);
//! let activity = manifest::activity(&ClassName::native_activity())
//!     .with_attr(attr::EXPORTED, true)
//!     .with_attr(attr::SCREEN_ORIENTATION, attr::SCREEN_ORIENTATION.parse("landscape")?)
//!     .with_child(manifest::launcher_filter());
//! manifest.application_mut().push_child(activity);
//! assert_eq!(manifest.launcher_activity(), Some("android.app.NativeActivity"));
//! println!("{manifest}");
//! # Ok::<(), apk::Error>(())
//! ```

use std::fmt;

use crate::android::{AttrDef, PLATFORM_API_LEVEL, attr};
use crate::error::Error;
use crate::res::Value;
use crate::types::{ApiLevel, ApiLevelError, ClassName, PackageName, PermissionName, VersionCode};
use crate::xml::{Document, Element};

/// Why a document is not a usable manifest.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ManifestError {
    #[error("the root element is <{root}>, not <manifest>")]
    NotAManifest { root: String },
    #[error("<manifest> has no package attribute")]
    MissingPackage,
    #[error("android:{attribute} has invalid SDK version {value:?}")]
    InvalidSdkVersion { attribute: &'static str, value: String },
}

/// An SDK version attribute: an API level, or the codename of a preview SDK.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum SdkVersion {
    Level(u32),
    Codename(String),
}

impl SdkVersion {
    /// The API level, treating a preview codename as the release after the
    /// newest one this crate knows, as `apksigner` does.
    pub fn api_level(&self) -> Result<ApiLevel, ApiLevelError> {
        match self {
            Self::Level(level) => ApiLevel::try_new(*level),
            Self::Codename(_) => ApiLevel::try_new(PLATFORM_API_LEVEL + 1),
        }
    }

    fn from_value(value: &Value) -> Option<Self> {
        match value {
            Value::String(text) => Some(text.parse().map_or_else(|_| Self::Codename(text.clone()), Self::Level)),
            value => value.as_int().and_then(|i| u32::try_from(i).ok()).map(Self::Level),
        }
    }
}

impl fmt::Display for SdkVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Level(level) => write!(f, "{level}"),
            Self::Codename(codename) => f.write_str(codename),
        }
    }
}

/// An `AndroidManifest.xml` document.
#[derive(Clone, Debug, PartialEq)]
pub struct Manifest {
    document: Document,
}

/// The activity that hosts a native library, and the meta-data naming it.
const NATIVE_ACTIVITY: &str = "android.app.NativeActivity";
const LIB_NAME: &str = "android.app.lib_name";

impl Manifest {
    /// A manifest for `package` with version code 1, `minSdkVersion` 24,
    /// `targetSdkVersion` 36, and an empty `<application>`.
    pub fn new(package: &PackageName) -> Self {
        let uses_sdk = Element::new("uses-sdk")
            .with_attr(attr::MIN_SDK_VERSION, ApiLevel::N.get() as i32)
            .with_attr(attr::TARGET_SDK_VERSION, ApiLevel::BAKLAVA.get() as i32);
        let root = Element::new("manifest")
            .with_android_namespace()
            .with_attr("package", package.as_str())
            .with_attr(attr::VERSION_CODE, VersionCode::ONE.get() as i32)
            .with_child(uses_sdk)
            .with_child(Element::new("application"));
        Self { document: Document::new(root) }
    }

    /// Parses a text manifest, typing attributes as aapt2 does.
    pub fn parse(text: &str) -> Result<Self, Error> {
        Ok(Self::from_document(Document::parse(text)?)?)
    }

    /// Decodes a compiled (binary XML) manifest.
    pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
        Ok(Self::from_document(Document::decode(bytes)?)?)
    }

    /// Checks that `document` is a manifest: its root is `<manifest>` with a
    /// `package`.
    pub fn from_document(document: Document) -> Result<Self, ManifestError> {
        let manifest = Self { document };
        manifest.validate()?;
        Ok(manifest)
    }

    /// Checks the root, package presence, and SDK values after tree edits.
    pub fn validate(&self) -> Result<(), ManifestError> {
        if self.root().name != "manifest" {
            return Err(ManifestError::NotAManifest { root: self.root().name.clone() });
        }
        self.package().ok_or(ManifestError::MissingPackage)?;
        if let Some(sdk) = self.root().element("uses-sdk") {
            for def in [attr::MIN_SDK_VERSION, attr::TARGET_SDK_VERSION, attr::MAX_SDK_VERSION] {
                let Some(value) = sdk.android_attr(def) else { continue };
                let valid = match value {
                    Value::Int(level) => ApiLevel::try_new(*level as u32).is_ok(),
                    Value::Hex(level) => ApiLevel::try_new(*level).is_ok(),
                    Value::String(text) => match text.parse::<u32>() {
                        Ok(level) => ApiLevel::try_new(level).is_ok(),
                        Err(_) => def != attr::MAX_SDK_VERSION && is_codename(text),
                    },
                    _ => false,
                };
                if !valid {
                    return Err(ManifestError::InvalidSdkVersion { attribute: def.name(), value: value.to_string() });
                }
            }
        }
        Ok(())
    }

    pub fn document(&self) -> &Document {
        &self.document
    }

    pub fn into_document(self) -> Document {
        self.document
    }

    /// The `<manifest>` element.
    pub fn root(&self) -> &Element {
        &self.document.root
    }

    /// The `<manifest>` element, for edits without a dedicated method.
    pub fn root_mut(&mut self) -> &mut Element {
        &mut self.document.root
    }

    /// The application ID (`package`).
    pub fn package(&self) -> Option<&str> {
        self.root().attr(None, "package").and_then(Value::as_str)
    }

    pub fn version_code(&self) -> Option<u32> {
        self.root().android_attr(attr::VERSION_CODE)?.as_int().and_then(|v| u32::try_from(v).ok())
    }

    pub fn version_name(&self) -> Option<&str> {
        android_str(self.root(), attr::VERSION_NAME)
    }

    /// `minSdkVersion`, which defaults to 1.
    pub fn min_sdk(&self) -> SdkVersion {
        self.sdk(attr::MIN_SDK_VERSION).unwrap_or(SdkVersion::Level(1))
    }

    pub fn target_sdk(&self) -> Option<SdkVersion> {
        self.sdk(attr::TARGET_SDK_VERSION)
    }

    pub fn max_sdk(&self) -> Option<u32> {
        match self.sdk(attr::MAX_SDK_VERSION)? {
            SdkVersion::Level(level) => Some(level),
            SdkVersion::Codename(_) => None,
        }
    }

    fn sdk(&self, def: &AttrDef) -> Option<SdkVersion> {
        SdkVersion::from_value(self.root().element("uses-sdk")?.android_attr(def)?)
    }

    /// The target API level, which defaults to the minimum.
    pub fn effective_target_sdk(&self) -> Result<ApiLevel, ApiLevelError> {
        self.target_sdk().unwrap_or_else(|| self.min_sdk()).api_level()
    }

    /// The requested permissions, including `uses-permission-sdk-23`.
    pub fn permissions(&self) -> impl Iterator<Item = &str> {
        let elements =
            self.root().elements().filter(|e| matches!(e.name.as_str(), "uses-permission" | "uses-permission-sdk-23"));
        elements.filter_map(|e| android_str(e, attr::NAME))
    }

    /// The named features (`uses-feature`) the app declares.
    pub fn features(&self) -> impl Iterator<Item = &str> {
        self.root().elements_named("uses-feature").filter_map(|e| android_str(e, attr::NAME))
    }

    pub fn application(&self) -> Option<&Element> {
        self.root().element("application")
    }

    /// The `<application>` element, which is added if missing.
    pub fn application_mut(&mut self) -> &mut Element {
        let root = self.root_mut();
        if root.element("application").is_none() {
            root.push_child(Element::new("application"));
        }
        root.element_mut("application").expect("ensured above")
    }

    fn application_bool(&self, def: &AttrDef) -> Option<bool> {
        self.application()?.android_attr(def)?.as_bool()
    }

    /// Whether the app has DEX code (`android:hasCode`, default `true`).
    pub fn has_code(&self) -> bool {
        self.application_bool(attr::HAS_CODE).unwrap_or(true)
    }

    pub fn debuggable(&self) -> bool {
        self.application_bool(attr::DEBUGGABLE).unwrap_or(false)
    }

    pub fn extract_native_libs(&self) -> Option<bool> {
        self.application_bool(attr::EXTRACT_NATIVE_LIBS)
    }

    /// The application label: a string, or a reference to a string resource.
    pub fn label(&self) -> Option<&Value> {
        self.application()?.android_attr(attr::LABEL)
    }

    pub fn activities(&self) -> impl Iterator<Item = &Element> {
        self.application().into_iter().flat_map(|application| application.elements_named("activity"))
    }

    /// The components that can declare intent filters: activities, activity
    /// aliases, services, and receivers.
    pub fn components(&self) -> impl Iterator<Item = &Element> {
        let application = self.application().into_iter().flat_map(Element::elements);
        application.filter(|e| matches!(e.name.as_str(), "activity" | "activity-alias" | "service" | "receiver"))
    }

    /// The activity or alias started from the launcher (`MAIN` and `LAUNCHER`).
    pub fn launcher_activity(&self) -> Option<&str> {
        let launcher =
            self.components().filter(|c| matches!(c.name.as_str(), "activity" | "activity-alias")).find(|activity| {
                activity.elements_named("intent-filter").any(|filter| {
                    let has = |tag, name| filter.elements_named(tag).any(|e| android_str(e, attr::NAME) == Some(name));
                    has("action", "android.intent.action.MAIN") && has("category", "android.intent.category.LAUNCHER")
                })
            });
        android_str(launcher?, attr::NAME)
    }

    /// The library a `NativeActivity` loads, if the app has one: the string
    /// value of its `android.app.lib_name` meta-data, or `main`, as
    /// `NativeActivity` chooses it.
    ///
    /// `Err` holds a reference, which names the library only once Android
    /// resolves it.
    pub fn native_activity_library(&self) -> Option<Result<&str, &Value>> {
        let activity = self.activities().find(|a| android_str(a, attr::NAME) == Some(NATIVE_ACTIVITY))?;
        let meta = activity.elements_named("meta-data").find(|m| android_str(m, attr::NAME) == Some(LIB_NAME));
        Some(match meta.and_then(|meta| meta.android_attr(attr::VALUE)) {
            Some(Value::String(library)) => Ok(library),
            Some(value @ (Value::Reference(_) | Value::Attribute(_))) => Err(value),
            // `getString` reads anything else as absent.
            _ => Ok("main"),
        })
    }

    pub fn set_version(&mut self, code: VersionCode, name: &str) -> &mut Self {
        self.root_mut().set_attr(attr::VERSION_CODE, code.get() as i32).set_attr(attr::VERSION_NAME, name);
        self
    }

    pub fn set_min_sdk(&mut self, level: ApiLevel) -> &mut Self {
        self.uses_sdk_mut().set_attr(attr::MIN_SDK_VERSION, level.get() as i32);
        self
    }

    pub fn set_target_sdk(&mut self, level: ApiLevel) -> &mut Self {
        self.uses_sdk_mut().set_attr(attr::TARGET_SDK_VERSION, level.get() as i32);
        self
    }

    /// The `<uses-sdk>` element, which is added first if missing.
    fn uses_sdk_mut(&mut self) -> &mut Element {
        let root = self.root_mut();
        if root.element("uses-sdk").is_none() {
            root.children.insert(0, crate::xml::Node::Element(Element::new("uses-sdk")));
        }
        root.element_mut("uses-sdk").expect("ensured above")
    }

    /// Requests `permission`, unless it already is.
    pub fn add_permission(&mut self, permission: &PermissionName) -> &mut Self {
        if !self.permissions().any(|p| p == permission.as_str()) {
            let element = Element::new("uses-permission").with_attr(attr::NAME, permission.as_str());
            self.root_mut().push_child(element);
        }
        self
    }
}

impl fmt::Display for Manifest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.document.fmt(f)
    }
}

/// The string value of framework attribute `def` on `element`.
fn android_str<'e>(element: &'e Element, def: &AttrDef) -> Option<&'e str> {
    element.android_attr(def)?.as_str()
}

fn is_codename(text: &str) -> bool {
    let mut bytes = text.bytes();
    bytes.next().is_some_and(|b| b.is_ascii_alphabetic()) && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
}

/// `<activity android:name="...">`.
pub fn activity(name: &ClassName) -> Element {
    Element::new("activity").with_attr(attr::NAME, name.as_str())
}

/// The intent filter of the activity the launcher starts: action `MAIN`,
/// category `LAUNCHER`.
pub fn launcher_filter() -> Element {
    Element::new("intent-filter")
        .with_child(Element::new("action").with_attr(attr::NAME, "android.intent.action.MAIN"))
        .with_child(Element::new("category").with_attr(attr::NAME, "android.intent.category.LAUNCHER"))
}

/// `<meta-data android:name="..." android:value="...">`.
pub fn meta_data(name: &str, value: impl Into<Value>) -> Element {
    Element::new("meta-data").with_attr(attr::NAME, name).with_attr(attr::VALUE, value)
}

/// A launchable `NativeActivity` that loads `lib<library>.so`, handling the
/// configuration changes a full-screen renderer usually handles itself.
pub fn native_activity(library: &str) -> Element {
    const CONFIG_CHANGES: &str =
        "orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|screenLayout|uiMode|density";
    let config_changes = attr::CONFIG_CHANGES.parse(CONFIG_CHANGES).expect("framework configChanges symbols");
    activity(&ClassName::native_activity())
        .with_attr(attr::EXPORTED, true)
        .with_attr(attr::CONFIG_CHANGES, config_changes)
        .with_child(meta_data(LIB_NAME, library))
        .with_child(launcher_filter())
}

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

    fn sample() -> Manifest {
        let mut manifest = Manifest::new(&PackageName::try_new("org.example.game").unwrap());
        manifest
            .set_version(VersionCode::try_new(3).unwrap(), "1.0")
            .add_permission(&PermissionName::android("INTERNET").unwrap())
            .add_permission(&PermissionName::android("INTERNET").unwrap());
        manifest.application_mut().set_attr(attr::HAS_CODE, false).push_child(native_activity("game"));
        manifest
    }

    #[test]
    fn reads_back_what_it_sets() {
        let manifest = sample();
        assert_eq!(manifest.package(), Some("org.example.game"));
        assert_eq!((manifest.version_code(), manifest.version_name()), (Some(3), Some("1.0")));
        assert_eq!((manifest.min_sdk(), manifest.target_sdk()), (SdkVersion::Level(24), Some(SdkVersion::Level(36))));
        assert_eq!(manifest.permissions().collect::<Vec<_>>(), ["android.permission.INTERNET"]);
        assert_eq!(manifest.launcher_activity(), Some(NATIVE_ACTIVITY));
        assert_eq!(manifest.native_activity_library(), Some(Ok("game")));
        assert!(!manifest.has_code());
    }

    #[test]
    fn round_trips_through_binary_and_text_xml() {
        let manifest = sample();
        let decoded = Manifest::decode(&manifest.document().encode(&()).unwrap()).unwrap();
        assert_eq!(decoded, manifest);
        let printed = decoded.to_string();
        assert!(printed.contains(r#"android:configChanges="density|keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode""#), "{printed}");
        assert_eq!(Manifest::parse(&printed).unwrap(), manifest);
    }

    #[test]
    fn native_activities_default_to_libmain() {
        let mut manifest = Manifest::new(&PackageName::try_new("org.example.app").unwrap());
        manifest.application_mut().push_child(activity(&ClassName::native_activity()));
        assert_eq!(manifest.native_activity_library(), Some(Ok("main")));
        let library: Value = "@string/library".parse::<crate::res::ResourceRef>().unwrap().into();
        let activity = manifest.application_mut().element_mut("activity").unwrap();
        activity.push_child(meta_data(LIB_NAME, library.clone()));
        assert_eq!(manifest.native_activity_library(), Some(Err(&library)));
    }

    #[test]
    fn launcher_aliases_are_reported_by_their_component_name() {
        let mut manifest = Manifest::new(&PackageName::try_new("org.example.alias").unwrap());
        manifest.application_mut().push_child(activity(&".MainActivity".parse().unwrap())).push_child(
            Element::new("activity-alias")
                .with_attr(attr::NAME, ".Launcher")
                .with_attr(attr::TARGET_ACTIVITY, ".MainActivity")
                .with_child(launcher_filter()),
        );
        assert_eq!(manifest.activities().count(), 1);
        assert_eq!(manifest.launcher_activity(), Some(".Launcher"));
    }

    #[test]
    fn rejects_documents_that_are_not_manifests() {
        let not_manifest = Document::new(Element::new("resources"));
        assert_eq!(
            Manifest::from_document(not_manifest),
            Err(ManifestError::NotAManifest { root: "resources".into() })
        );
        assert_eq!(
            Manifest::from_document(Document::new(Element::new("manifest"))),
            Err(ManifestError::MissingPackage)
        );
    }

    #[test]
    fn invalid_sdk_values_never_fall_back_to_defaults_or_preview_levels() {
        for attribute in [attr::MIN_SDK_VERSION, attr::TARGET_SDK_VERSION, attr::MAX_SDK_VERSION] {
            for value in [Value::Int(-1), Value::Int(0), Value::Hex(u32::MAX), Value::String("-1".into()), Value::Null]
            {
                let mut manifest = sample();
                manifest.uses_sdk_mut().set_attr(attribute, value);
                assert!(matches!(
                    Manifest::from_document(manifest.into_document()),
                    Err(ManifestError::InvalidSdkVersion { attribute: found, .. }) if found == attribute.name()
                ));
            }
        }
        let mut preview = sample();
        preview.uses_sdk_mut().set_attr(attr::MIN_SDK_VERSION, "VanillaIceCream");
        preview.validate().unwrap();
        assert!(matches!(preview.min_sdk(), SdkVersion::Codename(_)));
    }
}