Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions android-app/android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ android {
applicationId "com.dsmnru.pyq"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
// versionName/versionCode are bumped by the release flow only —
// tests assert well-formedness, never exact values.
versionCode 13
versionName "1.4.2"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
Expand Down
11 changes: 11 additions & 0 deletions android-app/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -104,5 +104,16 @@
nothing except that push stays silent; the decision is never
re-asked on later launches. -->
<uses-permission android:name="android.permission.INTERNET" />
<!--
In-app updater (downloadAndInstall): the app is distributed OUTSIDE
Google Play, so the release APK downloaded from the GitHub release is
handed straight to the system package installer. Android 8+ REFUSES to
resolve the installer intent unless the app declares this permission —
without it the update downloads to 100% and then never installs. The
per-user "Install unknown apps" toggle is still requested at install
time (ACTION_MANAGE_UNKNOWN_APP_SOURCES) and stays fully in the user's
control.
-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
</manifest>

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package com.dsmnru.pyq;

import java.net.URL;
import java.util.Locale;

/**
* DSMNRU PYQ — pure-JDK security policy for the in-app updater's
* download/install phase.
*
* Deliberately contains NO android.* imports so the class (and its JUnit
* test) runs on the plain JVM under `gradlew :app:testDebugUnitTest`
* without an emulator. DsmnruAppPlugin.downloadAndInstall consults this
* class for EVERY security-relevant decision:
*
* • which initial URLs may be downloaded (the Worker-supplied GitHub
* release asset URL — same allowlist as update.js);
* • which redirect hops may be followed (GitHub's own HTTPS asset CDN);
* • what a safe APK cache-file name looks like (always ends in .apk);
* • what a sane APK size is before the file is handed to the installer.
*/
final class UpdateUrlPolicy {

private UpdateUrlPolicy() {}

/** Hosts a release asset may ORIGINATE from (mirrors update.js regex). */
static final String INITIAL_HOST_GITHUB = "github.com";
static final String INITIAL_HOST_OBJECTS = "objects.githubusercontent.com";

/**
* Redirects are followed BY HAND (setInstanceFollowRedirects(false)) so
* every hop can be re-validated — HttpURLConnection's silent default
* would go anywhere the Location header says. GitHub release downloads
* redirect from github.com to its asset CDN subdomains (objects. and
* release-assets.) of githubusercontent.com: HTTPS, GitHub-owned,
* never an arbitrary host, never a scheme downgrade.
*/
static final String REDIRECT_HOST_SUFFIX = ".githubusercontent.com";

/** Upper bound on hand-followed redirects (GitHub needs exactly one). */
static final int MAX_REDIRECTS = 5;

/**
* Plausibility bounds for this app's release APK (the real v1.4.2 asset
* is ~5.7 MB). Catches HTML error pages, truncated downloads and
* runaway writes BEFORE anything is handed to the package installer.
*/
static final long MIN_APK_BYTES = 64 * 1024;
static final long MAX_APK_BYTES = 512L * 1024 * 1024;

/**
* True when {@code url} is an HTTPS URL on a host the app downloads
* updates FROM (the exact release-asset allowlist; credentials embedded
* in the URL are rejected).
*/
static boolean isTrustedUpdateUrl(String url) {
return isHttpsOnTrustedHost(url, false);
}

/**
* True when a redirect Location may be followed: HTTPS on github.com or
* any githubusercontent.com subdomain (GitHub-owned asset CDN).
*/
static boolean isTrustedRedirectTarget(String url) {
return isHttpsOnTrustedHost(url, true);
}

private static boolean isHttpsOnTrustedHost(String url, boolean allowGithubusercontentCdn) {
if (url == null || url.isEmpty()) return false;
try {
URL parsed = new URL(url);
if (!"https".equalsIgnoreCase(parsed.getProtocol())) return false;
if (parsed.getUserInfo() != null) return false; // never user:pass@host
String host = parsed.getHost() == null ? "" : parsed.getHost().toLowerCase(Locale.ROOT);
if (host.isEmpty()) return false;
if (INITIAL_HOST_GITHUB.equals(host) || INITIAL_HOST_OBJECTS.equals(host)) return true;
return allowGithubusercontentCdn
&& host.length() > REDIRECT_HOST_SUFFIX.length()
&& host.endsWith(REDIRECT_HOST_SUFFIX);
} catch (Exception malformed) {
return false;
}
}

/**
* Flatten a JS-supplied file name to a safe cache file that ALWAYS ends
* in .apk — the package installer path in the FileProvider URI. Path
* separators and other unsafe characters are replaced, the name is
* length-capped (keeping the tail so an extension survives) and any
* non-.apk extension is replaced with .apk.
*/
static String sanitizeApkFileName(String raw, String fallback) {
String name = raw == null ? "" : raw.trim();
if (name.isEmpty()) {
name = (fallback == null || fallback.trim().isEmpty()) ? "dsmnru-update.apk" : fallback.trim();
}
name = name.replaceAll("[^A-Za-z0-9 ._\\-]", "_");
if (name.length() > 96) name = name.substring(name.length() - 96);
if (!name.toLowerCase(Locale.ROOT).endsWith(".apk")) {
int dot = name.lastIndexOf('.');
if (dot > 0) name = name.substring(0, dot); // replace wrong extension
name = name + ".apk";
}
return name;
}

/**
* True when {@code bytes} is a sane size for this app's release APK:
* within the floor/ceiling, and — when the server sent a length — the
* EXACT length (a truncated download must never reach the installer).
* {@code contentLength <= 0} means "unknown" and skips the exact match.
*/
static boolean isPlausibleApkSize(long bytes, long contentLength) {
if (bytes < MIN_APK_BYTES || bytes > MAX_APK_BYTES) return false;
return contentLength <= 0 || bytes == contentLength;
}

/** ZIP local-file-header magic — the fastest "is this even an APK" sniff. */
static boolean looksLikeZip(byte[] header, int length) {
return length >= 4 && header[0] == 'P' && header[1] == 'K' && header[2] == 0x03 && header[3] == 0x04;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package com.dsmnru.pyq;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
* Plain-JVM behaviour tests for the in-app updater's download security
* policy ({@link UpdateUrlPolicy} — pure JDK, no Android APIs, so this runs
* under `gradlew :app:testDebugUnitTest` without an emulator).
*
* Covers the updater-fix requirements: trusted GitHub URLs, rejected
* untrusted/HTTP URLs, redirect-hop validation, .apk file-name sanitizing,
* APK size plausibility (including the real v1.4.2 asset size) and ZIP
* magic detection.
*/
public class UpdateUrlPolicyTest {

// ── trusted INITIAL download URLs ───────────────────────────────────

@Test
public void acceptsTrustedGithubReleaseUrls() {
assertTrue(UpdateUrlPolicy.isTrustedUpdateUrl(
"https://github.com/Lav-developer/PYQ/releases/download/v1.4.2/dsmnru-pyq.apk"));
assertTrue(UpdateUrlPolicy.isTrustedUpdateUrl(
"https://objects.githubusercontent.com/github-production-release-asset-2e65be/977278444/a?X-Amz-Signature=abc"));
}

@Test
public void rejectsNullEmptyAndMalformedUrls() {
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl(null));
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl(""));
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("not a url"));
}

@Test
public void rejectsUntrustedSchemesAndHosts() {
// plain HTTP is never allowed
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl(
"http://github.com/Lav-developer/PYQ/releases/download/v1.4.2/dsmnru-pyq.apk"));
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("http://objects.githubusercontent.com/x.apk"));
// arbitrary domains and look-alike hosts
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("https://evil.example.com/dsmnru-pyq.apk"));
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("https://github.com.evil.example.com/dsmnru-pyq.apk"));
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("https://githubusercontent.com/x.apk"));
// embedded credentials
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("https://user:pass@github.com/x.apk"));
// non-http(s) schemes
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("file:///data/local/tmp/malicious.apk"));
// CDN subdomains are redirect targets only, never initial sources
assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl(
"https://raw.githubusercontent.com/Lav-developer/PYQ/main/x.apk"));
}

// ── redirect hops (followed by hand, re-validated per hop) ──────────

@Test
public void acceptsGithubOwnedRedirectTargets() {
assertTrue(UpdateUrlPolicy.isTrustedRedirectTarget(
"https://objects.githubusercontent.com/github-production-release-asset-2e65be/977278444/a?sig=1"));
assertTrue(UpdateUrlPolicy.isTrustedRedirectTarget(
"https://release-assets.githubusercontent.com/github-production-release-asset/a?sig=1"));
assertTrue(UpdateUrlPolicy.isTrustedRedirectTarget(
"https://github.com/Lav-developer/PYQ/releases/download/v1.4.2/dsmnru-pyq.apk"));
}

@Test
public void rejectsUntrustedRedirectTargets() {
assertFalse(UpdateUrlPolicy.isTrustedRedirectTarget("http://objects.githubusercontent.com/x")); // downgrade
assertFalse(UpdateUrlPolicy.isTrustedRedirectTarget("https://objects.githubusercontent.com.evil.com/x"));
assertFalse(UpdateUrlPolicy.isTrustedRedirectTarget("https://evil.com/?u=https://github.com"));
assertFalse(UpdateUrlPolicy.isTrustedRedirectTarget(null));
}

// ── APK cache-file names always end in .apk ─────────────────────────

@Test
public void apkFileNamesAreSanitizedAndAlwaysEndInApk() {
assertEquals("dsmnru-pyq-1.4.2.apk",
UpdateUrlPolicy.sanitizeApkFileName("dsmnru-pyq-1.4.2.apk", "dsmnru-update.apk"));
assertEquals("dsmnru-update.apk", UpdateUrlPolicy.sanitizeApkFileName("", "dsmnru-update.apk"));
assertEquals("dsmnru-update.apk", UpdateUrlPolicy.sanitizeApkFileName(null, null));
assertEquals("weird name_.apk", UpdateUrlPolicy.sanitizeApkFileName("weird name?.apk", "dsmnru-update.apk"));
assertEquals(".._.._etc_passwd.apk", UpdateUrlPolicy.sanitizeApkFileName("../../etc/passwd.apk", "dsmnru-update.apk"));
// a wrong extension is REPLACED, and a missing one is appended
assertEquals("update.apk", UpdateUrlPolicy.sanitizeApkFileName("update.pdf", "dsmnru-update.apk"));
assertEquals("update.apk", UpdateUrlPolicy.sanitizeApkFileName("update", "dsmnru-update.apk"));
}

// ── APK size plausibility ───────────────────────────────────────────

@Test
public void plausibleApkSizes() {
assertTrue(UpdateUrlPolicy.isPlausibleApkSize(5704283L, 5704283L)); // the REAL v1.4.2 asset
assertTrue(UpdateUrlPolicy.isPlausibleApkSize(5704283L, -1L)); // unknown length → skip exact match
assertFalse(UpdateUrlPolicy.isPlausibleApkSize(0L, -1L)); // empty file
assertFalse(UpdateUrlPolicy.isPlausibleApkSize(1024L, -1L)); // below floor (HTML error page)
assertFalse(UpdateUrlPolicy.isPlausibleApkSize(5704282L, 5704283L)); // truncated by one byte
assertFalse(UpdateUrlPolicy.isPlausibleApkSize(Long.MAX_VALUE, -1L)); // runaway write
}

// ── ZIP magic (fast "is this even an APK" sniff) ────────────────────

@Test
public void zipMagicDetection() {
assertTrue(UpdateUrlPolicy.looksLikeZip(new byte[]{'P', 'K', 3, 4, 0, 0}, 6));
assertFalse(UpdateUrlPolicy.looksLikeZip(new byte[]{'<', 'h', 't', 'm', 'l'}, 5)); // an error page is not an APK
assertFalse(UpdateUrlPolicy.looksLikeZip(new byte[]{'P', 'K'}, 2));
}

// ── redirect budget ─────────────────────────────────────────────────

@Test
public void redirectBudgetIsBoundedAndSufficient() {
assertTrue(UpdateUrlPolicy.MAX_REDIRECTS > 0);
assertTrue(UpdateUrlPolicy.MAX_REDIRECTS <= 10); // bounded; GitHub needs exactly one
}
}
10 changes: 8 additions & 2 deletions android-app/test/fcm.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,14 @@ test('Gradle wires firebase-messaging and keeps google-services conditional', ()
assert.match(gradle, /apply plugin: 'com\.google\.gms\.google-services'/,
'google-services plugin applied when google-services.json exists');
assert.match(gradle, /google-services\.json/, 'apply is guarded by the presence of google-services.json');
assert.match(gradle, /versionCode 12/, 'current production versionCode is 12');
assert.match(gradle, /versionName \"1\.4\.1\"/, 'current production versionName is 1.4.1');
// Version metadata is bumped by the release flow on purpose — pinning the
// exact values here made this Firebase-wiring test fail on every
// legitimate bump (it broke when production moved to 1.4.2/13). Assert
// well-formed metadata instead; which exact version ships is owned by the
// release process, and the updater treats versions purely as data
// (see update-install.test.mjs).
assert.match(gradle, /^ versionCode \d+$/m, 'integer versionCode present');
assert.match(gradle, /^ versionName "\d+\.\d+\.\d+"$/m, 'semver versionName present');
// Consistent package identity + stable debug signature (update-in-place).
assert.match(gradle, /applicationId "com\.dsmnru\.pyq"/, 'single applicationId preserved');
assert.match(gradle, /signingConfig signingConfigs\.debug/, 'debug buildType uses the shared debug signing config');
Expand Down
Loading