Publish signed F-Droid releases with a QR catalog on k8s-ng
This commit is contained in:
1 parent
d77b06d108
commit
5d7e3a3dc2
14 files changed
+754
No files matched your search
@@ -0,0 +1,64 @@
|
||||
# F-Droid repository
|
||||
|
||||
Open `https://fdroid.hexor.cy/` to browse the apps and scan the QR code to
|
||||
add the repository in F-Droid. The QR code includes the signing certificate
|
||||
fingerprint. The public catalog is generated from the signed index at
|
||||
`https://fdroid.hexor.cy/fdroid/repo/`. Gitea and GitHub Releases supply
|
||||
the signed Android APKs. Every five minutes the publisher
|
||||
checks the latest stable release and publishes a signed index when the inputs
|
||||
change. Both the publisher and BusyBox HTTP server run on the node labelled
|
||||
`kubernetes.io/hostname=master`. Data lives in `/data/k8s/fdroidserver`.
|
||||
Traefik terminates TLS and routes requests to the read-only HTTP server.
|
||||
|
||||
## Set up the repository signing key once
|
||||
|
||||
Create a Bitwarden item named exactly `k8s/fdroidserver/secrets` in the vault
|
||||
collection readable by the External Secrets bot. Add these **Hidden** custom fields:
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| `keystorepass` | A generated 32-character alphanumeric password |
|
||||
| `keystore-base64` | The entire PKCS#12 file, base64-encoded on one line |
|
||||
|
||||
In a private directory on a trusted machine with a JDK, generate the key and
|
||||
enter the password from Bitwarden when prompted:
|
||||
|
||||
```sh
|
||||
umask 077
|
||||
keytool -genkeypair -storetype PKCS12 -keystore fdroid-repo.p12 \
|
||||
-alias fdroidrepo -keyalg RSA -keysize 3072 -sigalg SHA256withRSA \
|
||||
-validity 10000 -dname 'CN=F-Droid Repository'
|
||||
```
|
||||
|
||||
On macOS, copy the field value directly to the clipboard:
|
||||
|
||||
```sh
|
||||
openssl base64 -A -in fdroid-repo.p12 | pbcopy
|
||||
```
|
||||
|
||||
Keep a protected backup of the keystore and its password. Clients identify
|
||||
the repository by this key. To restore the exact file on macOS, copy the
|
||||
`keystore-base64` field and run the following in a private directory:
|
||||
|
||||
```sh
|
||||
umask 077
|
||||
pbpaste | openssl base64 -d -A -out restored.p12
|
||||
```
|
||||
|
||||
To get the SHA-256 fingerprint for sharing with
|
||||
users, run `keytool -list -v -keystore fdroid-repo.p12 -alias fdroidrepo`.
|
||||
The APK signing keys stay with the projects' release pipelines.
|
||||
|
||||
## Add an application
|
||||
|
||||
1. Add its GitHub or Gitea repository URL (with or without a trailing
|
||||
`/releases`), Android package name and release signing certificate SHA-256 to
|
||||
`sources.json`. Use `assetPattern` when a release contains multiple APK
|
||||
variants. Obtain the fingerprint from a trusted release with
|
||||
`apksigner verify --print-certs app.apk`.
|
||||
2. Add `metadata/<packageName>.yml` and list it in the metadata ConfigMap
|
||||
generator in `kustomization.yaml`. Set `AllowedAPKSigningKeys` to the same
|
||||
fingerprint.
|
||||
3. Publish a signed APK as a release asset. Increase the Android `versionCode`
|
||||
for each new binary. Argo CD applies the configuration and the next
|
||||
scheduled job picks up the release.
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Render the public landing page from the published F-Droid v2 index."""
|
||||
|
||||
import re
|
||||
from html import escape, unescape
|
||||
from textwrap import shorten
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
|
||||
|
||||
def localized(value):
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
locales = ("ru", "ru-RU", *(key for key in value if key.startswith("ru-")),
|
||||
"en-US", "en", *value)
|
||||
return next((value[key] for key in locales if value.get(key)), None)
|
||||
|
||||
|
||||
def asset_url(file):
|
||||
name = (file or {}).get("name", "").removeprefix("/")
|
||||
if not name or any(part in ("", ".", "..") for part in name.split("/")):
|
||||
return None
|
||||
return "/fdroid/repo/" + quote(name, safe="/")
|
||||
|
||||
|
||||
def app_card(package_id, package):
|
||||
metadata = package["metadata"]
|
||||
name = localized(metadata.get("name")) or package_id
|
||||
summary = localized(metadata.get("summary"))
|
||||
if not summary:
|
||||
description = localized(metadata.get("description")) or ""
|
||||
summary = shorten(unescape(re.sub(r"<[^>]+>", " ", description)), 180, placeholder="…")
|
||||
icon = asset_url(localized(metadata.get("icon")))
|
||||
if icon:
|
||||
icon_html = f'<img class="app-icon" src="{icon}" width="48" height="48" alt="">'
|
||||
else:
|
||||
icon_html = f'<span class="monogram" aria-hidden="true">{escape(name[:1].upper())}</span>'
|
||||
|
||||
versions = package.get("versions", {}).values()
|
||||
latest = max(versions, key=lambda it: it["manifest"]["versionCode"], default={})
|
||||
manifest = latest.get("manifest", {})
|
||||
version = manifest.get("versionName") or manifest.get("versionCode")
|
||||
version_html = f'<p class="version">Версия {escape(str(version))}</p>' if version else ""
|
||||
file = latest.get("file", {})
|
||||
download = asset_url(file)
|
||||
download_html = ""
|
||||
if download:
|
||||
size = file.get("size")
|
||||
size_text = f" · {size / 1_000_000:.1f} МБ".replace(".", ",") if size else ""
|
||||
download_html = f'<a class="download" href="{download}" download>Скачать APK{size_text}</a>'
|
||||
|
||||
return f"""<article>
|
||||
<header>{icon_html}<div><h3>{escape(name)}</h3>{version_html}</div></header>
|
||||
<p class="summary">{escape(summary)}</p>
|
||||
{download_html}
|
||||
</article>"""
|
||||
|
||||
|
||||
STYLE = """
|
||||
:root { color-scheme: light; --ink: #15291f; --muted: #4e6257; --green: #165c3a; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: #f7f9f5; color: var(--ink); font: 16px/1.55 Inter, system-ui, sans-serif; }
|
||||
main { width: min(940px, calc(100% - 32px)); margin: clamp(20px, 6vw, 72px) auto; }
|
||||
.intro { background: #e5efe3; border: 1px solid #cddccc; border-radius: 24px; padding: clamp(24px, 5vw, 56px);
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) minmax(150px, 198px); align-items: start; gap: 32px; }
|
||||
.type { color: var(--green); margin: 0; font-weight: 650; }
|
||||
h1, h2, h3 { line-height: 1.12; margin: 0; overflow-wrap: anywhere; }
|
||||
h1 { font-size: clamp(42px, 7vw, 72px); letter-spacing: -.055em; margin: .14em 0 .3em; }
|
||||
.instruction { margin: 0 0 22px; max-width: 49ch; }
|
||||
a { color: var(--green); text-underline-offset: .22em; }
|
||||
a:focus-visible, summary:focus-visible { outline: 3px solid #137050; outline-offset: 4px; }
|
||||
.open { display: inline-block; padding: 11px 18px; background: var(--green); color: white;
|
||||
font-weight: 650; border-radius: 9px; text-decoration: none; }
|
||||
.open:hover { background: #10462d; }
|
||||
.qr { background: white; padding: 9px; width: 100%; max-width: 198px; border-radius: 12px; justify-self: end; }
|
||||
.qr img { display: block; width: 100%; height: auto; image-rendering: pixelated; }
|
||||
details { margin-top: 15px; font-size: .875rem; color: var(--muted); }
|
||||
summary { width: fit-content; cursor: pointer; color: var(--green); }
|
||||
details p { margin: 10px 0 4px; }
|
||||
.address { overflow-wrap: anywhere; font: .84rem/1.55 ui-monospace, monospace; user-select: all; }
|
||||
section { margin-top: clamp(30px, 5vw, 50px); }
|
||||
h2 { font-size: clamp(25px, 4vw, 34px); letter-spacing: -.035em; }
|
||||
.grid { margin-top: 20px; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
|
||||
article { display: flex; flex-direction: column; align-items: flex-start; border-radius: 17px;
|
||||
border: 1px solid #d9e2d9; padding: 24px; background: white; min-width: 0; }
|
||||
header { display: flex; align-items: center; gap: 14px; }
|
||||
.app-icon, .monogram { width: 48px; height: 48px; flex: 0 0 48px; border-radius: 10px; }
|
||||
.app-icon { object-fit: contain; }
|
||||
.monogram { display: grid; place-items: center; color: var(--green); background: #e9f1e8; font-size: 25px; font-weight: 650; }
|
||||
h3 { font-size: 1.35rem; letter-spacing: -.025em; }
|
||||
.version { margin: 3px 0 0; color: var(--muted); font-size: .84rem; }
|
||||
.summary { color: var(--muted); margin: 15px 0; overflow-wrap: anywhere; }
|
||||
.download { margin-top: auto; font-size: .91rem; font-weight: 600; }
|
||||
@media (max-width: 610px) {
|
||||
.intro, .grid { grid-template-columns: minmax(0, 1fr); }
|
||||
.intro { gap: 20px; }
|
||||
.qr { max-width: 152px; justify-self: start; }
|
||||
article { padding: 20px; }
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def write_catalog(repo, listing, fingerprint):
|
||||
address = urlsplit(listing["repo"]["address"].rstrip("/"))
|
||||
if address.scheme != "https" or not address.hostname or address.query or address.fragment:
|
||||
raise ValueError("Expected a canonical HTTPS F-Droid repository URL")
|
||||
if not re.fullmatch(r"[0-9a-fA-F]{64}", fingerprint):
|
||||
raise ValueError("Invalid F-Droid repository fingerprint")
|
||||
query = "fingerprint=" + fingerprint.upper()
|
||||
https_link = escape(urlunsplit(address._replace(query=query)))
|
||||
app_link = escape(urlunsplit(address._replace(scheme="fdroidrepos", query=query)))
|
||||
title = escape(localized(listing["repo"].get("name")) or address.hostname)
|
||||
packages = listing["packages"]
|
||||
ordered = sorted(packages, key=lambda key: (localized(packages[key]["metadata"].get("name")) or key).casefold())
|
||||
cards = "\n".join(app_card(key, packages[key]) for key in ordered)
|
||||
catalog = f'<div class="grid">{cards}</div>' if cards else "<p>Пока нет приложений.</p>"
|
||||
|
||||
page = f"""<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>{title} — репозиторий F-Droid</title>
|
||||
<style>{STYLE}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="intro">
|
||||
<div>
|
||||
<p class="type">Репозиторий F-Droid</p>
|
||||
<h1>{title}</h1>
|
||||
<p class="instruction">Откройте ссылку в F-Droid на телефоне или отсканируйте QR-код.
|
||||
Подтвердите добавление репозитория, чтобы получать обновления приложений.</p>
|
||||
<a class="open" href="{app_link}">Открыть в F-Droid</a>
|
||||
<details><summary>Добавить вручную</summary>
|
||||
<p>В настройках F-Droid откройте «Репозитории», нажмите «+» и вставьте этот адрес.</p>
|
||||
<a class="address" href="{https_link}">{https_link}</a>
|
||||
</details>
|
||||
</div>
|
||||
<div class="qr"><img src="/fdroid/repo/index.png" width="180" height="180" alt="QR-код для добавления репозитория в F-Droid"></div>
|
||||
</div>
|
||||
<section aria-labelledby="apps">
|
||||
<h2 id="apps">Приложения</h2>
|
||||
{catalog}
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
(repo / "index.html").write_text(page, encoding="utf-8")
|
||||
@@ -0,0 +1,23 @@
|
||||
apiVersion: external-secrets.io/v1
|
||||
kind: ExternalSecret
|
||||
metadata:
|
||||
name: fdroidserver-signing
|
||||
spec:
|
||||
refreshInterval: 1h
|
||||
secretStoreRef:
|
||||
name: vaultwarden-fields
|
||||
kind: ClusterSecretStore
|
||||
target:
|
||||
name: fdroidserver-signing
|
||||
creationPolicy: Owner
|
||||
deletionPolicy: Retain
|
||||
data:
|
||||
- secretKey: keystore.p12
|
||||
remoteRef:
|
||||
key: k8s/fdroidserver/secrets
|
||||
property: keystore-base64
|
||||
decodingStrategy: Base64
|
||||
- secretKey: keystorepass
|
||||
remoteRef:
|
||||
key: k8s/fdroidserver/secrets
|
||||
property: keystorepass
|
||||
@@ -0,0 +1,31 @@
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: fdroidserver
|
||||
annotations:
|
||||
cert-manager.io/cluster-issuer: letsencrypt
|
||||
traefik.ingress.kubernetes.io/router.entrypoints: websecure
|
||||
spec:
|
||||
ingressClassName: traefik
|
||||
rules:
|
||||
- host: fdroid.hexor.cy
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Exact
|
||||
backend:
|
||||
service:
|
||||
name: fdroidserver-web
|
||||
port:
|
||||
name: http
|
||||
- path: /fdroid/repo
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: fdroidserver-web
|
||||
port:
|
||||
name: http
|
||||
tls:
|
||||
- hosts:
|
||||
- fdroid.hexor.cy
|
||||
secretName: fdroidserver-tls
|
||||
@@ -0,0 +1,20 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: fdroidserver
|
||||
resources:
|
||||
- storage.yaml
|
||||
- external-secret.yaml
|
||||
- publisher.yaml
|
||||
- web.yaml
|
||||
- ingress.yaml
|
||||
configMapGenerator:
|
||||
- name: fdroidserver-config
|
||||
files:
|
||||
- sources.json
|
||||
- repo.yml
|
||||
- sync_releases.py
|
||||
- catalog.py
|
||||
- name: fdroidserver-metadata
|
||||
files:
|
||||
- metadata/cy.hexor.furumi.yml
|
||||
- metadata/cy.hexor.tsunagi.yml
|
||||
@@ -0,0 +1,7 @@
|
||||
License: WTFPL
|
||||
SourceCode: https://gt.hexor.cy/Furumi/furumi_android
|
||||
IssueTracker: https://gt.hexor.cy/Furumi/furumi_android/issues
|
||||
Name: Furumi
|
||||
Summary: Play music from a Furumi server
|
||||
Description: Stream your music library and download tracks for offline listening.
|
||||
AllowedAPKSigningKeys: a30d218d74337e47ddd3ff4e464f4b507183111502e74e88d7fdac6e84943763
|
||||
@@ -0,0 +1,7 @@
|
||||
License: WTFPL
|
||||
SourceCode: https://github.com/house-of-vanity/tsunagi
|
||||
IssueTracker: https://github.com/house-of-vanity/tsunagi/issues
|
||||
Name: tsunagi
|
||||
Summary: Connect your devices over a mesh VPN
|
||||
Description: Join a private mesh network using a network name and a shared secret.
|
||||
AllowedAPKSigningKeys: 83751404a5a66089700aa310d4433756b992f08320007077a1e292f3a0d7a18f
|
||||
@@ -0,0 +1,87 @@
|
||||
apiVersion: batch/v1
|
||||
kind: CronJob
|
||||
metadata:
|
||||
name: fdroidserver-publish
|
||||
spec:
|
||||
schedule: "*/5 * * * *"
|
||||
concurrencyPolicy: Forbid
|
||||
successfulJobsHistoryLimit: 1
|
||||
failedJobsHistoryLimit: 3
|
||||
jobTemplate:
|
||||
spec:
|
||||
backoffLimit: 1
|
||||
activeDeadlineSeconds: 1800
|
||||
template:
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
restartPolicy: Never
|
||||
nodeSelector:
|
||||
kubernetes.io/hostname: master
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 1000
|
||||
runAsGroup: 1000
|
||||
fsGroup: 1000
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: publish
|
||||
image: registry.gitlab.com/fdroid/docker-executable-fdroidserver@sha256:70c3761a76bd30c63911ff1af4f3857573ac43891e6ecf72eac76b19c931e4c0
|
||||
command: [python3, /config/sync_releases.py]
|
||||
workingDir: /data
|
||||
env:
|
||||
- name: HOME
|
||||
value: /tmp
|
||||
- name: ANDROID_HOME
|
||||
value: /opt/android-sdk
|
||||
- name: PATH
|
||||
value: /home/vagrant/fdroidserver:/usr/local/bin:/usr/bin:/bin:/opt/android-sdk/build-tools/32.0.0
|
||||
# fdroid update records its upstream Git revision in its status output.
|
||||
- name: GIT_CONFIG_COUNT
|
||||
value: "1"
|
||||
- name: GIT_CONFIG_KEY_0
|
||||
value: safe.directory
|
||||
- name: GIT_CONFIG_VALUE_0
|
||||
value: /home/vagrant/fdroidserver
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: [ALL]
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 256Mi
|
||||
limits:
|
||||
memory: 1Gi
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /data
|
||||
- name: config
|
||||
mountPath: /config
|
||||
readOnly: true
|
||||
- name: metadata
|
||||
mountPath: /config/metadata
|
||||
readOnly: true
|
||||
- name: signing
|
||||
mountPath: /secrets
|
||||
readOnly: true
|
||||
- name: tmp
|
||||
mountPath: /tmp
|
||||
volumes:
|
||||
- name: data
|
||||
hostPath:
|
||||
path: /data/k8s/fdroidserver
|
||||
type: Directory
|
||||
- name: config
|
||||
configMap:
|
||||
name: fdroidserver-config
|
||||
- name: metadata
|
||||
configMap:
|
||||
name: fdroidserver-metadata
|
||||
- name: signing
|
||||
secret:
|
||||
secretName: fdroidserver-signing
|
||||
defaultMode: 0440
|
||||
- name: tmp
|
||||
emptyDir: {}
|
||||
@@ -0,0 +1,5 @@
|
||||
repo_url: https://fdroid.hexor.cy/fdroid/repo
|
||||
repo_name: Hexor
|
||||
repo_description: Android releases from Hexor's projects.
|
||||
repo_keyalias: fdroidrepo
|
||||
archive_older: 0
|
||||
@@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"url": "https://gt.hexor.cy/Furumi/furumi_android/",
|
||||
"packageName": "cy.hexor.furumi",
|
||||
"signerSha256": "a30d218d74337e47ddd3ff4e464f4b507183111502e74e88d7fdac6e84943763",
|
||||
"assetPattern": "furumi-android-*.apk"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/house-of-vanity/tsunagi/releases",
|
||||
"packageName": "cy.hexor.tsunagi",
|
||||
"signerSha256": "83751404a5a66089700aa310d4433756b992f08320007077a1e292f3a0d7a18f",
|
||||
"assetPattern": "tsunagi-android-*-arm64-v8a.apk"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,47 @@
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: fdroidserver-storage-prepare
|
||||
annotations:
|
||||
argocd.argoproj.io/hook: PreSync
|
||||
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation,HookSucceeded
|
||||
spec:
|
||||
backoffLimit: 2
|
||||
template:
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
restartPolicy: Never
|
||||
nodeSelector:
|
||||
kubernetes.io/hostname: master
|
||||
securityContext:
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: prepare
|
||||
image: docker.io/library/busybox:1.37.0@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
|
||||
command:
|
||||
- sh
|
||||
- -ec
|
||||
- |
|
||||
mkdir -p /data/public
|
||||
chown 1000:1000 /data /data/public
|
||||
chmod 0700 /data
|
||||
chmod 0755 /data/public
|
||||
if [ "$(readlink /data/public/index.html)" != fdroid/repo/index.html ]; then
|
||||
ln -sfn fdroid/repo/index.html /data/public/index.html
|
||||
fi
|
||||
securityContext:
|
||||
runAsUser: 0
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: [ALL]
|
||||
add: [CHOWN, DAC_OVERRIDE, FOWNER]
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /data
|
||||
volumes:
|
||||
- name: data
|
||||
hostPath:
|
||||
path: /data/k8s/fdroidserver
|
||||
type: DirectoryOrCreate
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Import signed release APKs and atomically publish an F-Droid repository."""
|
||||
|
||||
import fcntl
|
||||
import fnmatch
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import Request, urlopen
|
||||
import uuid
|
||||
|
||||
import qrcode
|
||||
|
||||
from catalog import write_catalog
|
||||
|
||||
|
||||
DATA = Path(os.environ.get("FDROID_DATA_ROOT", "/data")).resolve()
|
||||
CONFIG = Path(os.environ.get("FDROID_CONFIG_DIR", "/config")).resolve()
|
||||
SECRETS = Path(os.environ.get("FDROID_SECRET_DIR", "/secrets")).resolve()
|
||||
PRIVATE = DATA / ".fdroid"
|
||||
SNAPSHOTS = DATA / "public/snapshots"
|
||||
CURRENT = DATA / "public/fdroid/repo"
|
||||
|
||||
|
||||
def latest_url(page):
|
||||
url = urlsplit(page)
|
||||
match = re.fullmatch(r"/([\w.-]+)/([\w.-]+)(?:/releases)?/?", url.path, re.ASCII)
|
||||
if (url.scheme != "https" or not url.hostname or url.username or url.password
|
||||
or url.query or url.fragment or not match
|
||||
or any(part in {".", ".."} for part in match.groups())):
|
||||
raise ValueError(f"Expected an HTTPS repository or releases page: {page}")
|
||||
api = ("https://api.github.com" if url.netloc.lower() == "github.com"
|
||||
else f"https://{url.netloc}/api/v1")
|
||||
owner, project = match.groups()
|
||||
return f"{api}/repos/{owner}/{project}/releases/latest"
|
||||
|
||||
|
||||
def fetch(url):
|
||||
if urlsplit(url).scheme != "https":
|
||||
raise ValueError(f"Expected an HTTPS download: {url}")
|
||||
return urlopen(Request(url, headers={"User-Agent": "homelab-fdroid-sync"}), timeout=60)
|
||||
|
||||
|
||||
def releases(sources, previous):
|
||||
assets = {}
|
||||
unavailable = []
|
||||
for source in sources:
|
||||
package = source["packageName"]
|
||||
if not re.fullmatch(r"[a-zA-Z][\w]*(?:\.[a-zA-Z][\w]*)+", package, re.ASCII):
|
||||
raise ValueError(f"Invalid Android package name: {package}")
|
||||
signer = source["signerSha256"].replace(":", "").lower()
|
||||
if not re.fullmatch(r"[a-f0-9]{64}", signer) or package in assets:
|
||||
raise ValueError(f"Invalid signer or duplicate source for {package}")
|
||||
url = latest_url(source["url"])
|
||||
try:
|
||||
with fetch(url) as response:
|
||||
release = json.load(response)
|
||||
except (HTTPError, URLError, TimeoutError) as exc:
|
||||
print(f"Cannot read latest release for {package}: {exc}", file=sys.stderr)
|
||||
unavailable.append(package)
|
||||
cached = previous.get(package, {})
|
||||
assets[package] = (cached if cached.get("signer") == signer
|
||||
else {"signer": signer, "tag": None, "files": []})
|
||||
continue
|
||||
selected = []
|
||||
for asset in release["assets"]:
|
||||
name = asset["name"]
|
||||
if name.endswith(".apk") and fnmatch.fnmatchcase(name, source.get("assetPattern", "*.apk")):
|
||||
selected.append({k: asset.get(k) for k in (
|
||||
"name", "id", "size", "browser_download_url", "updated_at", "uuid", "digest"
|
||||
)})
|
||||
if release["draft"] or release["prerelease"]:
|
||||
raise ValueError(f"Unexpected non-stable release for {package}")
|
||||
if not selected:
|
||||
print(f"No matching APK in latest release for {package}", file=sys.stderr)
|
||||
assets[package] = {
|
||||
"tag": release["tag_name"], "signer": signer,
|
||||
"files": sorted(selected, key=lambda a: a["name"]),
|
||||
}
|
||||
return assets, unavailable
|
||||
|
||||
|
||||
def config_hash():
|
||||
digest = hashlib.sha256()
|
||||
inputs = [CONFIG / "repo.yml", CONFIG / "sources.json", SECRETS / "keystore.p12",
|
||||
Path(__file__), Path(__file__).with_name("catalog.py")]
|
||||
metadata = CONFIG / "metadata"
|
||||
for root, dirs, files in os.walk(metadata, followlinks=True):
|
||||
# Kubernetes projected volumes also expose hidden links to rotating revisions.
|
||||
dirs[:] = sorted(name for name in dirs if not name.startswith("."))
|
||||
inputs.extend(Path(root) / name for name in sorted(files) if not name.startswith("."))
|
||||
for file in inputs:
|
||||
digest.update(str(file.relative_to(CONFIG) if file.is_relative_to(CONFIG) else file.name).encode())
|
||||
digest.update(b"\0" + hashlib.sha256(file.read_bytes()).digest())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def verify(apk, package, signer):
|
||||
certs = subprocess.check_output(
|
||||
["apksigner", "verify", "--print-certs", str(apk)], text=True, errors="replace")
|
||||
fingerprints = re.findall(r"^Signer #\d+ certificate SHA-256 digest: ([\da-fA-F]+)$", certs, re.M)
|
||||
if [fp.lower() for fp in fingerprints] != [signer]:
|
||||
raise ValueError(f"Unexpected APK signing certificate for {package}")
|
||||
badging = subprocess.check_output(
|
||||
["aapt", "dump", "badging", str(apk)], text=True, errors="replace")
|
||||
manifest = re.search(r"^package: name='([^']+)' versionCode='(\d+)'", badging, re.M)
|
||||
if not manifest or manifest[1] != package:
|
||||
raise ValueError(f"APK manifest does not identify {package}")
|
||||
return manifest[2]
|
||||
|
||||
|
||||
def import_apk(file, package, signer, work, known):
|
||||
apk = work / "download.apk"
|
||||
digest = hashlib.sha256()
|
||||
with fetch(file["browser_download_url"]) as response, apk.open("wb") as output:
|
||||
while block := response.read(1024 * 1024):
|
||||
digest.update(block)
|
||||
output.write(block)
|
||||
sha = digest.hexdigest()
|
||||
if apk.stat().st_size != file["size"] or (file["digest"] and file["digest"] != "sha256:" + sha):
|
||||
raise ValueError(f"Release asset size or digest mismatch: {file['name']}")
|
||||
version = verify(apk, package, signer)
|
||||
name = f"{package}_{version}.apk"
|
||||
if name in known and known[name] != sha:
|
||||
raise ValueError(f"{name} already has different content; publish a higher versionCode")
|
||||
if name not in known:
|
||||
apk.rename(work / "repo" / name)
|
||||
known[name] = sha
|
||||
print(f"Verified {file['name']} as {name}", flush=True)
|
||||
|
||||
|
||||
def index(work, known):
|
||||
shutil.copytree(CONFIG / "metadata", work / "metadata", ignore=shutil.ignore_patterns(".*"))
|
||||
config = (CONFIG / "repo.yml").read_text().rstrip() + "\n"
|
||||
config += f"keystore: {json.dumps(str(SECRETS / 'keystore.p12'))}\n"
|
||||
config += "keystorepass: {env: FDROID_PASS}\nkeypass: {env: FDROID_PASS}\n"
|
||||
path = work / "config.yml"
|
||||
path.write_text(config)
|
||||
path.chmod(0o600)
|
||||
password = (SECRETS / "keystorepass").read_text().rstrip("\r\n")
|
||||
subprocess.run(["fdroid", "update"], cwd=work, check=True, env={**os.environ, "FDROID_PASS": password})
|
||||
repo = work / "repo"
|
||||
listing = json.loads((repo / "index-v2.json").read_text())
|
||||
published = {version["file"]["name"].lstrip("/"): version["file"]["sha256"]
|
||||
for package in listing["packages"].values() for version in package["versions"].values()}
|
||||
if known != published:
|
||||
raise ValueError("Generated F-Droid index does not contain the verified APK set")
|
||||
certs = subprocess.check_output(
|
||||
["keytool", "-printcert", "-rfc", "-jarfile", str(repo / "entry.jar")], text=True)
|
||||
leaf = re.search(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", certs, re.S)
|
||||
if not leaf:
|
||||
raise ValueError("Missing signing certificate in F-Droid entry.jar")
|
||||
fingerprint = hashlib.sha256(ssl.PEM_cert_to_DER_cert(leaf[0])).hexdigest().upper()
|
||||
address = listing["repo"]["address"].rstrip("/")
|
||||
qrcode.make(f"{address}?fingerprint={fingerprint}").save(repo / "index.png")
|
||||
write_catalog(repo, listing, fingerprint)
|
||||
|
||||
|
||||
def sync():
|
||||
current = CURRENT.resolve(strict=True) if CURRENT.is_symlink() else None
|
||||
state = json.loads((PRIVATE / f"{current.name}.json").read_text()) if current else {}
|
||||
previous_assets = state.get("assets", {})
|
||||
assets, unavailable = releases(json.loads((CONFIG / "sources.json").read_text()), previous_assets)
|
||||
if not current and not any(release["files"] for release in assets.values()):
|
||||
raise RuntimeError("No release APK is available for initial publication")
|
||||
config = config_hash()
|
||||
if state.get("assets") == assets and state.get("config") == config:
|
||||
print("Published releases and repository configuration are up to date")
|
||||
return unavailable
|
||||
|
||||
# A killed Job can leave a private staging directory behind. The lock excludes live writers.
|
||||
work = PRIVATE / "work"
|
||||
if work.exists():
|
||||
shutil.rmtree(work)
|
||||
work.mkdir(mode=0o700)
|
||||
repo = work / "repo"
|
||||
repo.mkdir()
|
||||
try:
|
||||
# Preserve previous versions only while their source and signing certificate are trusted.
|
||||
trusted = {package for package, release in assets.items()
|
||||
if previous_assets.get(package, {}).get("signer") == release["signer"]}
|
||||
known = {name: sha for name, sha in state.get("apks", {}).items()
|
||||
if name.rsplit("_", 1)[0] in trusted}
|
||||
for name in known:
|
||||
os.link(current / name, repo / name)
|
||||
if current:
|
||||
# fdroid reads the previous v2 index to preserve first-seen timestamps.
|
||||
shutil.copyfile(current / "index-v2.json", repo / "index-v2.json")
|
||||
for package, release in assets.items():
|
||||
previous = previous_assets.get(package, {})
|
||||
for file in release["files"]:
|
||||
if previous.get("signer") != release["signer"] or file not in previous.get("files", []):
|
||||
import_apk(file, package, release["signer"], work, known)
|
||||
index(work, known)
|
||||
generation = uuid.uuid4().hex
|
||||
next_state = {"assets": assets, "config": config, "apks": known}
|
||||
(PRIVATE / f"{generation}.json").write_text(json.dumps(next_state))
|
||||
repo.rename(SNAPSHOTS / generation)
|
||||
link = work / "next"
|
||||
link.symlink_to(f"../snapshots/{generation}", target_is_directory=True)
|
||||
os.replace(link, CURRENT)
|
||||
print(f"Published {len(known)} APK(s) to /fdroid/repo", flush=True)
|
||||
for old in SNAPSHOTS.iterdir():
|
||||
if old.name != generation and (current is None or old.name != current.name):
|
||||
shutil.rmtree(old)
|
||||
(PRIVATE / f"{old.name}.json").unlink(missing_ok=True)
|
||||
finally:
|
||||
shutil.rmtree(work)
|
||||
return unavailable
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
PRIVATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
SNAPSHOTS.mkdir(parents=True, exist_ok=True)
|
||||
CURRENT.parent.mkdir(parents=True, exist_ok=True)
|
||||
with (PRIVATE / "lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
unavailable = sync()
|
||||
if unavailable:
|
||||
sys.exit("Release APIs unavailable, will retry: " + ", ".join(unavailable))
|
||||
@@ -0,0 +1,68 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: fdroidserver-web
|
||||
spec:
|
||||
replicas: 1
|
||||
progressDeadlineSeconds: 1800
|
||||
selector:
|
||||
matchLabels:
|
||||
app: fdroidserver-web
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: fdroidserver-web
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
nodeSelector:
|
||||
kubernetes.io/hostname: master
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 65534
|
||||
runAsGroup: 65534
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: httpd
|
||||
image: docker.io/library/busybox:1.37.0@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec
|
||||
command: [httpd, -f, -p, "8080", -h, /www]
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 8080
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /fdroid/repo/entry.jar
|
||||
port: http
|
||||
periodSeconds: 10
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: [ALL]
|
||||
resources:
|
||||
requests:
|
||||
cpu: 10m
|
||||
memory: 8Mi
|
||||
limits:
|
||||
memory: 32Mi
|
||||
volumeMounts:
|
||||
- name: public
|
||||
mountPath: /www
|
||||
readOnly: true
|
||||
volumes:
|
||||
- name: public
|
||||
hostPath:
|
||||
path: /data/k8s/fdroidserver/public
|
||||
type: Directory
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: fdroidserver-web
|
||||
spec:
|
||||
selector:
|
||||
app: fdroidserver-web
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
targetPort: http
|
||||
@@ -132,3 +132,9 @@ apps:
|
||||
namespace: mtproxy
|
||||
wave: 6 # after secret-stores and prom-stack
|
||||
skipDryRunOnMissingResource: true
|
||||
- name: fdroidserver
|
||||
project: apps
|
||||
path: k8s-ng/apps/fdroidserver
|
||||
namespace: fdroidserver
|
||||
wave: 6 # after Gitea and secret-stores
|
||||
skipDryRunOnMissingResource: true
|
||||
Reference in new issue
Block a user