App 2.16.0, server 2.6.0: over-the-air updates from our own repository
The car updates itself again, from this fork's own releases, while the repository stays private: - publish-car (flake) creates the pre-release car-<version> on the forge and attaches the APK and its .sha256. It needs a forge token that may write releases, from ~/.config/nilsmg4/forge-token or $FORGE_TOKEN; it is sent in a header and never printed. - The server relays releases and attachments (/v1/app/releases, /v1/app/assets/...), read with a read-only FORGE_TOKEN from its Secret, GitHub-shaped with download URLs back at itself. Redirects away from the forge are not followed; off (404) without a token. - The app asks its server with its own paired token, allows exactly the server's host, downloads the APK itself instead of through the DownloadManager (so the token stays in the app), verifies SHA-256 and package name, and tries a PackageInstaller session (it may install silently as the system user) before falling back to Downloads. OTA.md is rewritten for this flow; the k8s and server READMEs explain the new token. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QLJfZQZeAKAwSqViTmLzki
This commit is contained in:
@@ -1,17 +1,15 @@
|
||||
package com.evsuite.abrp;
|
||||
|
||||
import android.app.PendingIntent;
|
||||
import android.app.DownloadManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.ClipData;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageInstaller;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
import android.provider.Settings;
|
||||
import android.util.Log;
|
||||
|
||||
@@ -43,43 +41,34 @@ import java.security.MessageDigest;
|
||||
* stable build. Unstable testers get updates without manual work, and accept that channel's
|
||||
* risk.
|
||||
*
|
||||
* Security posture is the one EVProfile settled on in its own OTA work:
|
||||
* - the APK URL comes from a remote JSON document and is never trusted: https only,
|
||||
* exact-match host allowlist, checked again before it reaches the system downloader;
|
||||
* - the downloaded APK must be signed by the same certificate as the running app, or it
|
||||
* is deleted rather than offered for install;
|
||||
* - both checks fail closed.
|
||||
* Releases come from the car server (server/releases.go), which relays them from the private
|
||||
* forge repository: the car asks with its own paired token and never holds a forge
|
||||
* credential. The server only carries bytes; the checks are all here:
|
||||
* - every URL in the release list is untrusted: https only, and exactly the configured
|
||||
* server's host (no suffix match), checked again before anything is fetched;
|
||||
* - the APK must match the SHA-256 published next to it, or it is deleted;
|
||||
* - it must be this app's package, and the installer refuses any other signing key;
|
||||
* - every check fails closed.
|
||||
*/
|
||||
final class OtaUpdater {
|
||||
|
||||
private static final String TAG = "OtaUpdater";
|
||||
private static final String CACHE_PREFIX = "NilsMG4-ota-";
|
||||
|
||||
/**
|
||||
* Pre-releases live here; the unstable channel tracks them.
|
||||
*
|
||||
* This fork's own repository, deliberately: an update pulled from upstream would be
|
||||
* signed with a different key, and Android refuses to install over a platform-signed
|
||||
* build with anything but the same signature. Pointing here means the check finds
|
||||
* nothing until this repository publishes a release, which is the intended quiet.
|
||||
*
|
||||
* Disabled for now: the .invalid TLD (RFC 2606) never resolves, so every check fails
|
||||
* with "Update check failed" instead of offering upstream's builds over this one. To
|
||||
* re-enable, point this at a fork's releases API, e.g.
|
||||
* "https://api.github.com/repos/<owner>/<repo>/releases".
|
||||
*/
|
||||
private static final String RELEASES_API =
|
||||
"https://updates.invalid/repos/fatihdonmezdev/FatihsMG4/releases";
|
||||
/** The release list on the car server, for the server configured in the app. */
|
||||
static String releasesUrl(ServerConfig config) {
|
||||
return config.url + "/v1/app/releases";
|
||||
}
|
||||
|
||||
/**
|
||||
* Hosts an update may come from. The githubusercontent entries are the CDNs GitHub
|
||||
* redirects release-asset downloads to; without them the download fails.
|
||||
*/
|
||||
private static final List<String> ALLOWED_HOSTS = Arrays.asList(
|
||||
"api.github.com",
|
||||
"github.com",
|
||||
"objects.githubusercontent.com",
|
||||
"release-assets.githubusercontent.com");
|
||||
/** The one host updates may come from: the configured server's. Null if unusable. */
|
||||
static String allowedHost(ServerConfig config) {
|
||||
try {
|
||||
String host = new URI(config.url).getHost();
|
||||
return host == null ? null : host.toLowerCase(Locale.US);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static final java.util.regex.Pattern ASSET_VERSION =
|
||||
java.util.regex.Pattern.compile("-(\\d[0-9.]*?)\\.apk$",
|
||||
@@ -87,6 +76,7 @@ final class OtaUpdater {
|
||||
|
||||
private static final int TIMEOUT_MS = 10_000;
|
||||
private static final int MAX_HASH_BYTES = 16 * 1024;
|
||||
private static final long MAX_APK_BYTES = 64L * 1024 * 1024;
|
||||
|
||||
private OtaUpdater() { }
|
||||
|
||||
@@ -119,13 +109,14 @@ final class OtaUpdater {
|
||||
}
|
||||
|
||||
/**
|
||||
* True if [url] is https and points at an allowed host.
|
||||
* True if [url] is https and points at exactly [allowedHost].
|
||||
*
|
||||
* Rejects http (including an https -> http downgrade), unknown hosts, unparsable
|
||||
* URLs, and lookalikes such as "github.com.attacker.net" — the host match is exact,
|
||||
* never a suffix test.
|
||||
* Rejects http (including an https -> http downgrade), other hosts, unparsable URLs, and
|
||||
* lookalikes such as "car.example.com.attacker.net" — the host match is exact, never a
|
||||
* suffix test.
|
||||
*/
|
||||
static boolean isAllowedUrl(String url) {
|
||||
static boolean isAllowedUrl(String url, String allowedHost) {
|
||||
if (url == null || allowedHost == null) return false;
|
||||
URI uri;
|
||||
try {
|
||||
uri = new URI(url);
|
||||
@@ -134,7 +125,7 @@ final class OtaUpdater {
|
||||
}
|
||||
if (uri.getScheme() == null || !uri.getScheme().equalsIgnoreCase("https")) return false;
|
||||
String host = uri.getHost();
|
||||
return host != null && ALLOWED_HOSTS.contains(host.toLowerCase(java.util.Locale.US));
|
||||
return host != null && host.toLowerCase(Locale.US).equals(allowedHost.toLowerCase(Locale.US));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,18 +182,21 @@ final class OtaUpdater {
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks GitHub for the newest pre-release and returns it if it beats [currentVersion].
|
||||
* Runs on the caller's thread — never call from the main thread.
|
||||
* Asks the car server for the newest pre-release and returns it if it beats
|
||||
* [currentVersion]. Runs on the caller's thread — never call from the main thread.
|
||||
*/
|
||||
static Update check(String currentVersion) throws IOException {
|
||||
return check(currentVersion, (HttpURLConnection) new URL(RELEASES_API).openConnection());
|
||||
static Update check(ServerConfig config, String currentVersion) throws IOException {
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(releasesUrl(config)).openConnection();
|
||||
// The car's own token, in a header; never in a URL or a log line.
|
||||
conn.setRequestProperty("Authorization", "Bearer " + config.token);
|
||||
return check(currentVersion, conn, allowedHost(config));
|
||||
}
|
||||
|
||||
/** Connection seam for exercising real response handling without a device or network. */
|
||||
static Update check(String currentVersion, HttpURLConnection conn) throws IOException {
|
||||
static Update check(String currentVersion, HttpURLConnection conn, String allowedHost) throws IOException {
|
||||
try {
|
||||
conn.setInstanceFollowRedirects(false);
|
||||
conn.setRequestProperty("Accept", "application/vnd.github.v3+json");
|
||||
conn.setRequestProperty("Accept", "application/json");
|
||||
conn.setRequestProperty("User-Agent", "NilsMG4-Android");
|
||||
conn.setConnectTimeout(TIMEOUT_MS);
|
||||
conn.setReadTimeout(TIMEOUT_MS);
|
||||
@@ -217,7 +211,7 @@ final class OtaUpdater {
|
||||
while ((line = br.readLine()) != null) body.append(line);
|
||||
}
|
||||
|
||||
return selectUpdate(new JSONArray(body.toString()), currentVersion);
|
||||
return selectUpdate(new JSONArray(body.toString()), currentVersion, allowedHost);
|
||||
} catch (JSONException e) {
|
||||
throw new IOException("Invalid release response", e);
|
||||
} finally {
|
||||
@@ -226,7 +220,7 @@ final class OtaUpdater {
|
||||
}
|
||||
|
||||
/** Scan every asset of every pre-release; asset ordering does not imply version order. */
|
||||
static Update selectUpdate(JSONArray releases, String currentVersion) throws JSONException {
|
||||
static Update selectUpdate(JSONArray releases, String currentVersion, String allowedHost) throws JSONException {
|
||||
Update best = null;
|
||||
for (int i = 0; i < releases.length(); i++) {
|
||||
JSONObject release = releases.getJSONObject(i);
|
||||
@@ -241,24 +235,24 @@ final class OtaUpdater {
|
||||
if (version == null || !isNewer(version, currentVersion)) continue;
|
||||
if (best != null && !isNewer(version, best.versionName)) continue;
|
||||
String url = asset.optString("browser_download_url", "");
|
||||
String hashUrl = findHashUrl(assets, name);
|
||||
String hashUrl = findHashUrl(assets, name, allowedHost);
|
||||
// Keep the candidate even when the sidecar is absent so the UI can report
|
||||
// a broken release instead of incorrectly saying the app is current.
|
||||
// fetchExpectedSha256 still fails closed before any APK is downloaded.
|
||||
if (isAllowedUrl(url)) best = new Update(version, url, name, hashUrl);
|
||||
if (isAllowedUrl(url, allowedHost)) best = new Update(version, url, name, hashUrl);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static String findHashUrl(JSONArray assets, String apkName) throws JSONException {
|
||||
private static String findHashUrl(JSONArray assets, String apkName, String allowedHost) throws JSONException {
|
||||
String exact = apkName + ".sha256";
|
||||
String sums = null;
|
||||
for (int i = 0; i < assets.length(); i++) {
|
||||
JSONObject asset = assets.getJSONObject(i);
|
||||
String name = asset.optString("name", "");
|
||||
String url = asset.optString("browser_download_url", "");
|
||||
if (!isAllowedUrl(url)) continue;
|
||||
if (!isAllowedUrl(url, allowedHost)) continue;
|
||||
if (exact.equalsIgnoreCase(name)) return url;
|
||||
if ("SHA256SUMS".equalsIgnoreCase(name)) sums = url;
|
||||
}
|
||||
@@ -285,20 +279,21 @@ final class OtaUpdater {
|
||||
return value != null && value.matches("(?i)[a-f0-9]{64}");
|
||||
}
|
||||
|
||||
static String fetchExpectedSha256(Update update) throws IOException {
|
||||
if (update == null || !isAllowedUrl(update.hashUrl))
|
||||
static String fetchExpectedSha256(Update update, ServerConfig config) throws IOException {
|
||||
if (update == null || !isAllowedUrl(update.hashUrl, allowedHost(config)))
|
||||
throw new IOException("Missing SHA-256 sidecar");
|
||||
String body = readSmallText(update.hashUrl);
|
||||
String body = readSmallText(update.hashUrl, config);
|
||||
String hash = parseExpectedSha256(body, update.apkName);
|
||||
if (hash == null) throw new IOException("Invalid SHA-256 sidecar");
|
||||
return hash;
|
||||
}
|
||||
|
||||
private static String readSmallText(String initialUrl) throws IOException {
|
||||
private static String readSmallText(String initialUrl, ServerConfig config) throws IOException {
|
||||
URL current = new URL(initialUrl);
|
||||
for (int redirects = 0; redirects <= 5; redirects++) {
|
||||
if (!isAllowedUrl(current.toString())) throw new IOException("Hash URL refused");
|
||||
if (!isAllowedUrl(current.toString(), allowedHost(config))) throw new IOException("Hash URL refused");
|
||||
HttpURLConnection connection = (HttpURLConnection) current.openConnection();
|
||||
connection.setRequestProperty("Authorization", "Bearer " + config.token);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setConnectTimeout(TIMEOUT_MS);
|
||||
connection.setReadTimeout(TIMEOUT_MS);
|
||||
@@ -346,64 +341,64 @@ final class OtaUpdater {
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads into private cache. Every redirect URL is validated before it is followed.
|
||||
* Downloads the APK from the car server into the public Downloads folder, hashing it on
|
||||
* the way. Done here rather than with the system DownloadManager, so the car's token stays
|
||||
* in this app instead of another app's download database. A wrong hash deletes the file.
|
||||
* No redirects: the server streams the file itself.
|
||||
*/
|
||||
static File download(Context context, Update update, String expectedSha256,
|
||||
static File download(Update update, String expectedSha256, ServerConfig config,
|
||||
ProgressListener listener) {
|
||||
if (!isAllowedUrl(update.apkUrl)) {
|
||||
Log.w(TAG, "Refusing to download from " + update.apkUrl);
|
||||
if (!isAllowedUrl(update.apkUrl, allowedHost(config))) {
|
||||
Log.w(TAG, "Refusing to download from an unexpected host");
|
||||
return null;
|
||||
}
|
||||
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
|
||||
if (manager == null) return null;
|
||||
String publicName = downloadFileName(update.versionName);
|
||||
File publicFile = new File(Environment.getExternalStoragePublicDirectory(
|
||||
Environment.DIRECTORY_DOWNLOADS), publicName);
|
||||
if (publicFile.exists() && !publicFile.delete()) return null;
|
||||
long downloadId = -1L;
|
||||
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
|
||||
if (downloads == null || (!downloads.isDirectory() && !downloads.mkdirs())) return null;
|
||||
File target = new File(downloads, downloadFileName(update.versionName));
|
||||
HttpURLConnection connection = null;
|
||||
boolean ok = false;
|
||||
try {
|
||||
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(update.apkUrl))
|
||||
.setTitle("Nils' MG4 " + update.versionName)
|
||||
.setDescription("Downloading update")
|
||||
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
|
||||
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, publicName)
|
||||
.setAllowedOverMetered(true)
|
||||
.setAllowedOverRoaming(true);
|
||||
downloadId = manager.enqueue(request);
|
||||
while (true) {
|
||||
try (Cursor cursor = manager.query(new DownloadManager.Query().setFilterById(downloadId))) {
|
||||
if (cursor == null || !cursor.moveToFirst()) return null;
|
||||
int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
|
||||
long received = cursor.getLong(cursor.getColumnIndexOrThrow(
|
||||
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
|
||||
long total = cursor.getLong(cursor.getColumnIndexOrThrow(
|
||||
DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
|
||||
if (listener != null) listener.onProgress(total > 0
|
||||
? (int) Math.min(100, received * 100 / total) : -1);
|
||||
if (status == DownloadManager.STATUS_SUCCESSFUL) break;
|
||||
if (status == DownloadManager.STATUS_FAILED) return null;
|
||||
}
|
||||
Thread.sleep(250L);
|
||||
}
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (ParcelFileDescriptor descriptor = manager.openDownloadedFile(downloadId);
|
||||
java.io.InputStream input = new ParcelFileDescriptor.AutoCloseInputStream(descriptor)) {
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
int count;
|
||||
while ((count = input.read(buffer)) != -1) {
|
||||
digest.update(buffer, 0, count);
|
||||
}
|
||||
}
|
||||
if (!hex(digest.digest()).equalsIgnoreCase(expectedSha256)) {
|
||||
if (!publicFile.delete()) Log.w(TAG, "Could not remove invalid OTA file");
|
||||
connection = (HttpURLConnection) new URL(update.apkUrl).openConnection();
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setConnectTimeout(TIMEOUT_MS);
|
||||
connection.setReadTimeout(30_000);
|
||||
connection.setRequestProperty("Authorization", "Bearer " + config.token);
|
||||
connection.setRequestProperty("User-Agent", "NilsMG4-Android");
|
||||
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
|
||||
Log.w(TAG, "Update download returned " + connection.getResponseCode());
|
||||
return null;
|
||||
}
|
||||
return publicFile;
|
||||
long total = connection.getContentLengthLong();
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
long received = 0;
|
||||
int lastPercent = -2;
|
||||
try (java.io.InputStream in = connection.getInputStream();
|
||||
FileOutputStream out = new FileOutputStream(target, false)) {
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
int count;
|
||||
while ((count = in.read(buffer)) != -1) {
|
||||
out.write(buffer, 0, count);
|
||||
digest.update(buffer, 0, count);
|
||||
received += count;
|
||||
if (received > MAX_APK_BYTES) throw new IOException("APK too large");
|
||||
int percent = total > 0 ? (int) Math.min(100, received * 100 / total) : -1;
|
||||
if (listener != null && percent != lastPercent) {
|
||||
listener.onProgress(percent);
|
||||
lastPercent = percent;
|
||||
}
|
||||
}
|
||||
out.getFD().sync();
|
||||
}
|
||||
ok = hex(digest.digest()).equalsIgnoreCase(expectedSha256);
|
||||
if (!ok) Log.w(TAG, "Update APK does not match its SHA-256");
|
||||
return ok ? target : null;
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "Update download failed", e);
|
||||
Log.w(TAG, "Update download failed: " + e.getClass().getSimpleName());
|
||||
return null;
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
if (!ok && target.exists() && !target.delete()) Log.w(TAG, "Could not remove a bad update file");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
|
||||
Reference in New Issue
Block a user