cargo-rahti-native 0.0.1

Optional Windows and Android packaging for Rahti applications: initialize, check prerequisites, run and package a Tauri shell around an existing Rahti app.
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
//! The Android project patches `cargo rahti native` applies after Tauri has
//! generated it.

use super::*;

/// Tauri 2's generated manifest, in the shape this patch anchors on.
const TAURI_MANIFEST: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.demo"
        android:usesCleartextTraffic="${usesCleartextTraffic}">
        <activity android:name=".MainActivity" android:exported="true" />
    </application>
</manifest>
"#;

/// A throwaway `gen/android` with a manifest in it.
fn generated(label: &str, manifest: &str) -> std::path::PathBuf {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

    let root = std::env::temp_dir().join(format!(
        "rahti-native-android-{label}-{}-{n}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join("app/src/main")).unwrap();
    std::fs::write(root.join("app/src/main/AndroidManifest.xml"), manifest).unwrap();
    root
}

fn manifest_of(root: &std::path::Path) -> String {
    std::fs::read_to_string(root.join("app/src/main/AndroidManifest.xml")).unwrap()
}

#[test]
fn the_loopback_server_is_reachable_from_the_webview() {
    // The bug this exists for: Tauri sets `usesCleartextTraffic=false` on a
    // release build — correct for Tauri, wrong for Rahti, whose whole design
    // is the real router on `http://127.0.0.1`. Without this the release APK
    // installs, launches, and shows a blank screen while the server runs.
    let root = generated("patch", TAURI_MANIFEST);
    crate::run::allow_loopback_cleartext(&root).expect("the patch applies");

    let manifest = manifest_of(&root);
    assert!(
        manifest.contains(r#"android:networkSecurityConfig="@xml/rahti_network_security_config""#),
        "{manifest}"
    );

    let config = std::fs::read_to_string(
        root.join("app/src/main/res/xml/rahti_network_security_config.xml"),
    )
    .expect("the network security config");
    assert!(config.contains("<domain includeSubdomains=\"false\">127.0.0.1</domain>"));

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn cleartext_stays_refused_for_everything_else() {
    // Setting `usesCleartextTraffic=true` would also have fixed the blank
    // screen, and would have permitted cleartext to every host — a real
    // downgrade for an application that talks to an API over TLS.
    let root = generated("scope", TAURI_MANIFEST);
    crate::run::allow_loopback_cleartext(&root).expect("the patch applies");

    let config = std::fs::read_to_string(
        root.join("app/src/main/res/xml/rahti_network_security_config.xml"),
    )
    .unwrap();
    assert!(
        config.contains(r#"<base-config cleartextTrafficPermitted="false" />"#),
        "{config}"
    );
    // And the manifest's own flag is left as Tauri wrote it — the config takes
    // precedence, so the two cannot disagree.
    assert!(
        manifest_of(&root).contains(r#"android:usesCleartextTraffic="${usesCleartextTraffic}""#)
    );

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn applying_it_twice_adds_one_attribute() {
    // It runs on every Android build, because `gen/android` is regenerated
    // rather than reviewed and a patch that only ran once would be gone the
    // first time somebody deleted it.
    let root = generated("twice", TAURI_MANIFEST);
    crate::run::allow_loopback_cleartext(&root).expect("a first run");
    let once = manifest_of(&root);

    crate::run::allow_loopback_cleartext(&root).expect("a second run");
    assert_eq!(
        manifest_of(&root),
        once,
        "the second run changed the manifest"
    );
    assert_eq!(once.matches("networkSecurityConfig").count(), 1);

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn a_manifest_this_tool_does_not_recognise_is_reported_rather_than_guessed_at() {
    // A future Tauri that stops writing the anchor attribute must not be
    // silently half-patched: the symptom would be a blank screen in release
    // and nothing to explain it.
    let root = generated(
        "unknown",
        "<?xml version=\"1.0\"?>\n<manifest><application /></manifest>\n",
    );

    let error = crate::run::allow_loopback_cleartext(&root).expect_err("no anchor");
    assert!(
        error.to_string().contains("networkSecurityConfig"),
        "the error does not say what to add by hand: {error}"
    );

    let _ = std::fs::remove_dir_all(&root);
}

// ------------------------------------------------------- release signing

/// Tauri 2's generated Gradle file, in the shape the signing patch anchors on.
const TAURI_GRADLE: &str = r#"import java.util.Properties

plugins {
    id("com.android.application")
}

android {
    compileSdk = 36
    buildTypes {
        getByName("debug") {
            isDebuggable = true
        }
        getByName("release") {
            isMinifyEnabled = true
        }
    }
}
"#;

/// The four signing variables, set for one test and removed after.
///
/// This owns the lock rather than handing it back beside the value, and that
/// is not a style choice. `let (_signing, _guard) = …` drops in *reverse*
/// declaration order — the guard first — so the lock was released while the
/// variables were still set, and whichever test took it next read them. That
/// made the suite fail about one run in three, in a different test each time.
/// One value owning both makes the order impossible to get wrong.
struct Signing(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>);

static SIGNING_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

const SIGNING_VARS: [&str; 4] = [
    "RAHTI_NATIVE_ANDROID_KEYSTORE",
    "RAHTI_NATIVE_ANDROID_KEYSTORE_PASSWORD",
    "RAHTI_NATIVE_ANDROID_KEY_ALIAS",
    "RAHTI_NATIVE_ANDROID_KEY_PASSWORD",
];

impl Signing {
    /// All four set, for a fully configured key.
    fn set(keystore: &str) -> Self {
        let held = Signing::none();
        // SAFETY: `held` owns the lock, which is this binary's whole access
        // to these four, and holds it until it drops.
        unsafe {
            std::env::set_var("RAHTI_NATIVE_ANDROID_KEYSTORE", keystore);
            std::env::set_var("RAHTI_NATIVE_ANDROID_KEYSTORE_PASSWORD", "storepass");
            std::env::set_var("RAHTI_NATIVE_ANDROID_KEY_ALIAS", "release");
            std::env::set_var("RAHTI_NATIVE_ANDROID_KEY_PASSWORD", "keypass");
        }
        held
    }

    /// The lock, with none of the four set.
    fn none() -> Self {
        let guard = SIGNING_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: as above.
        unsafe {
            for name in SIGNING_VARS {
                std::env::remove_var(name);
            }
        }
        Signing(guard)
    }
}

impl Drop for Signing {
    fn drop(&mut self) {
        // SAFETY: this value still holds the lock; it is released after.
        unsafe {
            for name in SIGNING_VARS {
                std::env::remove_var(name);
            }
        }
    }
}

fn with_gradle(label: &str) -> std::path::PathBuf {
    let root = generated(label, TAURI_MANIFEST);
    std::fs::write(root.join("app/build.gradle.kts"), TAURI_GRADLE).unwrap();
    root
}

#[test]
fn a_release_key_reaches_the_gradle_project() {
    // The bug this exists for: Tauri reads no signing key from the environment
    // on Android, so passing `TAURI_ANDROID_KEYSTORE` does nothing and the
    // build succeeds with an *unsigned* release — which Google Play refuses
    // and which will not install.
    let root = with_gradle("signing");
    let _signing = Signing::set("C:\\keys\\release.jks");

    crate::run::configure_signing(&root).expect("the signing patch applies");

    let gradle = std::fs::read_to_string(root.join("app/build.gradle.kts")).unwrap();
    assert!(gradle.contains("signingConfigs {"), "{gradle}");
    assert!(
        gradle.contains("signingConfig = signingConfigs.getByName(\"release\")"),
        "{gradle}"
    );
    // On the release build type, and not on debug — a debug build is signed
    // with Android's own key and must not need this one.
    let release_at = gradle.find("getByName(\"release\")").unwrap();
    let applied_at = gradle.find("signingConfig = signingConfigs").unwrap();
    assert!(applied_at > release_at, "{gradle}");

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn the_key_details_go_only_to_the_ignored_properties_file() {
    let root = with_gradle("signing-secrets");
    let _signing = Signing::set("C:\\keys\\release.jks");

    crate::run::configure_signing(&root).expect("the signing patch applies");

    let properties =
        std::fs::read_to_string(root.join("keystore.properties")).expect("the properties file");
    assert!(properties.contains("keyAlias=release"), "{properties}");
    assert!(
        properties.contains("storePassword=storepass"),
        "{properties}"
    );
    // A Windows path is written with forward slashes: Gradle reads this as a
    // Java properties file, where a backslash escapes the next character.
    assert!(
        properties.contains("storeFile=C:/keys/release.jks"),
        "{properties}"
    );

    // And nowhere else.
    let gradle = std::fs::read_to_string(root.join("app/build.gradle.kts")).unwrap();
    for secret in ["storepass", "keypass", "release.jks"] {
        assert!(
            !gradle.contains(secret),
            "the Gradle file carries `{secret}`, which is committed"
        );
    }

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn applying_the_signing_patch_twice_wires_it_once() {
    let root = with_gradle("signing-twice");
    let _signing = Signing::set("C:\\keys\\release.jks");

    crate::run::configure_signing(&root).expect("a first run");
    let once = std::fs::read_to_string(root.join("app/build.gradle.kts")).unwrap();
    crate::run::configure_signing(&root).expect("a second run");
    let twice = std::fs::read_to_string(root.join("app/build.gradle.kts")).unwrap();

    assert_eq!(once, twice);
    assert_eq!(once.matches("signingConfigs {").count(), 1);

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn no_keystore_configured_changes_nothing() {
    // A debug build is signed with Android's debug key and needs none of this.
    let root = with_gradle("signing-absent");
    let _signing = Signing::none();

    crate::run::configure_signing(&root).expect("nothing to do");

    assert_eq!(
        std::fs::read_to_string(root.join("app/build.gradle.kts")).unwrap(),
        TAURI_GRADLE
    );
    assert!(!root.join("keystore.properties").exists());

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn a_half_configured_key_is_refused_rather_than_producing_an_unsigned_release() {
    let root = with_gradle("signing-partial");
    // Nothing set, then one of the four — a keystore with no password and no
    // alias, which is the shape that would otherwise produce a release nobody
    // can install.
    let _signing = Signing::none();
    // SAFETY: `_signing` holds the lock for the whole test.
    unsafe {
        std::env::set_var("RAHTI_NATIVE_ANDROID_KEYSTORE", "C:\\keys\\release.jks");
    }

    let error = crate::run::configure_signing(&root).expect_err("a half-configured key");
    assert!(error.to_string().contains("unsigned"), "{error}");

    let _ = std::fs::remove_dir_all(&root);
}

// -------------------------------------------------------- launcher icons

/// A generated Android project with the template's own launcher icons in it,
/// which is the state `cargo tauri android init` leaves behind.
fn with_template_icons(label: &str) -> (std::path::PathBuf, crate::project::Project) {
    let root = generated(label, TAURI_MANIFEST);

    for density in ["mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"] {
        let dir = root.join(format!("app/src/main/res/mipmap-{density}"));
        std::fs::create_dir_all(&dir).unwrap();
        // WebP, which is what cargo-mobile2's template actually ships.
        std::fs::write(dir.join("ic_launcher.webp"), b"the template's robot").unwrap();
    }

    // The project whose `native/icons/android` the icons are copied from.
    let project_root = root.join("project");
    std::fs::create_dir_all(project_root.join("src")).unwrap();
    std::fs::write(project_root.join("rahti.config.json"), "{}").unwrap();
    std::fs::write(
        project_root.join("Cargo.toml"),
        "[package]
name = \"app\"
version = \"1.0.0\"
",
    )
    .unwrap();

    let icons = project_root.join("native/icons");
    for icon in crate::icons::ANDROID {
        let target = icons.join(icon.path);
        std::fs::create_dir_all(target.parent().unwrap()).unwrap();
        std::fs::write(&target, icon.bytes).unwrap();
    }

    let project = crate::project::Project::at(&project_root).expect("a project");
    (root, project)
}

#[test]
fn the_applications_launcher_icons_replace_the_templates() {
    // The bug this exists for: nothing in `tauri android init` copies
    // `native/icons/` into the generated project, so an Android build wore the
    // template's robot however many times you replaced `icons/icon.png`.
    let (root, project) = with_template_icons("icons");
    crate::run::install_android_icons(&project, &root).expect("the icons install");

    let res = root.join("app/src/main/res");
    for density in ["mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"] {
        let png = res.join(format!("mipmap-{density}/ic_launcher.png"));
        assert!(png.is_file(), "mipmap-{density} did not get an icon");
        assert_ne!(
            std::fs::read(&png).unwrap(),
            b"the template's robot".to_vec()
        );
    }

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn the_templates_file_for_the_same_resource_name_is_removed() {
    // Android names a resource without its extension, so `ic_launcher.webp`
    // beside `ic_launcher.png` is two files claiming one name — `aapt2` fails
    // the build on it. Writing ours without removing theirs would trade a
    // wrong icon for no build at all.
    let (root, project) = with_template_icons("icons-clash");
    crate::run::install_android_icons(&project, &root).expect("the icons install");

    let res = root.join("app/src/main/res");
    for density in ["mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"] {
        assert!(
            !res.join(format!("mipmap-{density}/ic_launcher.webp"))
                .exists(),
            "mipmap-{density} still has the template's .webp beside ours"
        );
    }

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn the_adaptive_icon_xml_and_its_background_are_installed() {
    let (root, project) = with_template_icons("icons-adaptive");
    crate::run::install_android_icons(&project, &root).expect("the icons install");

    let res = root.join("app/src/main/res");
    assert!(res.join("mipmap-anydpi-v26/ic_launcher.xml").is_file());
    assert!(res.join("values/ic_launcher_background.xml").is_file());

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn installing_the_icons_twice_writes_them_once() {
    // It runs on every Android build; a second run must not rewrite files and
    // make Gradle think every resource changed.
    let (root, project) = with_template_icons("icons-twice");
    crate::run::install_android_icons(&project, &root).expect("a first run");

    let png = root.join("app/src/main/res/mipmap-mdpi/ic_launcher.png");
    let stamp = std::fs::metadata(&png).unwrap().modified().unwrap();

    crate::run::install_android_icons(&project, &root).expect("a second run");
    assert_eq!(
        std::fs::metadata(&png).unwrap().modified().unwrap(),
        stamp,
        "the second run rewrote an unchanged icon"
    );

    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn a_project_with_no_icon_tree_is_left_alone() {
    // A project scaffolded before the icons shipped. The build still works; it
    // wears the template's icon, which is what it did before.
    let root = generated("icons-absent", TAURI_MANIFEST);
    let project_root = root.join("project");
    std::fs::create_dir_all(&project_root).unwrap();
    std::fs::write(project_root.join("rahti.config.json"), "{}").unwrap();
    std::fs::write(
        project_root.join("Cargo.toml"),
        "[package]
name = \"app\"
version = \"1.0.0\"
",
    )
    .unwrap();
    let project = crate::project::Project::at(&project_root).expect("a project");

    crate::run::install_android_icons(&project, &root).expect("nothing to do");

    let _ = std::fs::remove_dir_all(&root);
}