diff --git a/PLAN.md b/PLAN.md index ac7a3c7..ab016b8 100644 --- a/PLAN.md +++ b/PLAN.md @@ -234,14 +234,61 @@ Steps: manifest inspect` reported "no such manifest" for an image that existed, so the check uses `docker buildx imagetools inspect`, and any error but "not found" stops the publish - - [ ] David: publish a test app to gitea.federated.computer - (`docker login` with a `write:package` token) + - Tested 2026-12-03 by David: `coreapp publish` of + `gitea.federated.computer/david/pub-test:0.1.0` worked (package and + tag `v0.1.0` in Gitea). The account `david` isn't visible anonymously + (its profile, repository and API answer 404 without a login), so its + packages probably can't be pulled without one either: see "Private + repositories and packages" under step 3 - [ ] Run the workflow on a repository with a runner - - [ ] Pin the image by digest in what the Core installs? Private - packages need a pull token on the Core -3. [ ] Install from a URL on the Core: `coreapps install [@tag]` - (git clone at the tag, read `coreapp.toml` and `icon.png` only, pull the - image). Show the source and what the app needs before installing + +3. Install from a repository (2026-12-03): `coreapps plan|install + [@tag]` and `coreapps update `; on the + workstation `coreapp install ` (shows the app, its source and needs, + asks) and `coreapp update `. The installer fetches only the tag's + commit (depth 1, no blobs but `coreapp.toml` and `icon.png`, which must be + regular files; a link is ignored), with git limited to https, no password + prompts and no system or root git settings. The default tag is the newest + numeric release (`v1.2.3`, compared as numbers); `version` must match the + tag; the image is always pulled for a repository install (never a + same-named image built on the Core). The marker records `source`, `tag` + and `commit`; installing the same name from another repository is + refused. Tested on dev.fedcom.net with a stand-in repository (file://, + the https rule relaxed for the test) and nginx 1.27/1.28 as the image: + plan, install, update, "already newest", the other-repository refusal, + remove; and, on the workstation, tag selection, the version check, the + link icon and URL checks. Found and fixed: docker lists + `docker.io/library/nginx` as `nginx`, so old images weren't deleted; + `remove` force-deleted images, which could untag one another app uses + - End to end with a real repository and registry: done with David's + private pub-test (below) + - Private repositories and packages (2026-12-03; Coreapps are "private" + apps, so their repositories usually are): `coreapps login + ` (token on stdin), `logout`, `logins`; on the workstation + `coreapp login ` asks for user and token. Tokens by host in + `/etc/coreapps/credentials` (dir 700, file 600, outside `/opt/coreapps`, + which deploys replace). git gets the token as an `http..extraHeader` + in its environment, for that host only (never in a URL or an error); + docker gets it in a config made for each pull, so no docker login stays + on the Core. `login` checks the token with the host's registry + (`/v2/`, then its token endpoint) and saves nothing if it's rejected. + Tested 2026-12-03: a wrong token for gitea.federated.computer is + rejected, file modes, logout, bad input, and David's private + repository and image without a token both stop with "coreapp login" + hints. Found: David's packages can't be pulled without a login + (`unauthorized: reqPackageAccess`) + - Tested 2026-12-03 by David: `coreapp login gitea.federated.computer` + with a read-only token, then `coreapp install + https://gitea.federated.computer/david/pub-test` from the private + repository and package: installed at `https://pub-test.dev.fedcom.net/` + (HTTP 200), `list` shows the source `@v0.1.0`, no docker login left + on the Core + - [ ] Tokens per host+owner, if a Core needs several accounts on one host + - [ ] Superpanel would manage these tokens + - [ ] Downgrades: installing an older tag is allowed (`@v1.0.0`); an app's + data may not survive that. Refuse, or warn? + - [ ] Pin the image digest at install (from the registry at that moment) + so a re-pushed tag can't change what's installed 4. [ ] Email and AI needs (findings below), then other services: PowerDNS records beyond the wildcard, if an app needs other hostnames 5. The skill (moved ahead of 2-4, 2026-12-03): `skills/coreapp/SKILL.md`, diff --git a/README.md b/README.md index c0028bf..751d5cd 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,9 @@ each new app explains the files and the settings it gets. | `coreapp check` | It answers at `https://.` with a valid certificate | | `coreapp status` / `logs [-f]` / `shell [command]` | Its container, its log, a shell in it (or one command, without a terminal) | | `coreapp list` | The apps on the Core installed this way | +| `coreapp install [@tag]` | Install a published app from its repository on the Core, as its owner would: shows what it is and needs, asks, then installs (default: the newest release tag) | +| `coreapp update ` | Update an app installed from a repository to its newest release | +| `coreapp login ` / `logout ` / `logins` | Give the Core a token for private apps from a host (asks for the user and token), forget it, list them | | `coreapp publish [--platform ]` | Build the release image, push it to the registry in `coreapp.toml` (`image:version`, never replacing a published version) and tag the commit `v` | | `coreapp remove` | Uninstall it from the Core, with its database and sign-in client (asks first) | @@ -94,6 +97,18 @@ To publish, set `image` to your registry (for Gitea, (`.gitea/workflows/publish.yml`) that does the same when a `v*` tag is pushed, for repositories with a runner that can use Docker. +A published app installs on any Core from its repository: `coreapp install +https://gitea.example.com/owner/app` runs the installer there with the URL. +It reads only `coreapp.toml` and `icon.png` at the newest release tag +(`v1.2.3`; or name one with `@v1.2.3`), checks that the tag matches +`version`, and pulls the image from its registry. The repository and the +image can be private: `coreapp login gitea.example.com` gives the Core a +token for that host (for Gitea, one with read access to repositories and +packages), which the installer uses for the repository and the image. It +keeps tokens in `/etc/coreapps/credentials` on the Core (root only); docker +gets the token only for each pull, so the Core keeps no docker login. This +is what Superpanel's Coreapps screen would do. + Installing and removing go through the Core's own `installapp` and `uninstallapp`, so the app shows up in Superpanel. The installer gives apps no `MONITOR` line, so they aren't added to Federated's external monitoring. diff --git a/TEST.md b/TEST.md index 8e89484..2b6ae4a 100644 --- a/TEST.md +++ b/TEST.md @@ -292,6 +292,49 @@ then says which needs it has. Apps with an address outside 192.168.5.0/24 get a new one on their next update (the container moves; the app keeps working), and apps with sign-in get their client copy. +## Installing from a repository (coreapp install, update) + +Needs a public git repository over https whose release tag `v` +has a `coreapp.toml` with a published, public `image` (e.g. after +`coreapp publish`). + +1. `coreapp install https:////`: shows the title, + version, source with tag and commit, image, needs and URL, and asks. + Answering no installs nothing. Yes: " <version> from <url> + (v<version>, commit ...)", "Pulling ...", "Installed: https://...". + `coreapp list` shows `<url>@v<version>`; on the Core, + `/federated/services/<name>/.coreapp` has `source`, `tag`, `commit`. +2. Publish a newer version, then `coreapp update <name>`: "Updated", the + old image is gone from the Core. Again: "at the newest release". +3. `coreapp install <url>@v<old version>`: installs that tag. +4. Refused with a message, nothing changed: + - a URL with a password (`https://u:p@host/o/r`), `http://`, `ssh://`, + or one level only (`https://host/repo`) + - a repository without `v1.2.3` tags (unless `@<tag>` is given), a tag + that doesn't exist, `@main` + - a tag whose `coreapp.toml` has another `version` + - `image = "localhost/..."` at the tag + - the same app name from another repository + - a private repository, or an image that can't be pulled +5. `icon.png` that's a symbolic link in the repository: the default icon is + used. +6. Private: with a private repository and package, `coreapp install <url>` + stops with "If it's private, give this Core a token for <host>: coreapp + login <host>". `coreapp login <host>` with a wrong token: "rejected the + token", nothing saved. With a read-only token (Gitea: repositories and + packages, read): "Saved a token ... (its registry accepts it)", then + `coreapp install <url>` works; `coreapp logins` lists the host (no + token shown); on the Core `/etc/coreapps` is 700, `credentials` 600, and + `/root/.docker/config.json` has no entry for the host. `coreapp logout + <host>`: installing fails again. +7. `coreapp remove` in the app's folder (or `coreapps remove <name>` on the + Core) removes it like any other. + +Without a public repository, the fetch can be tested on a local bare +repository (`git config uploadpack.allowFilter true`) by loading +`core/coreapps` as a module and replacing `REPO_URL`, `normalize_url` and +`GIT_ENV["GIT_ALLOW_PROTOCOL"]` for `file://` (only in the test). + ## Publishing (coreapp publish) With a throwaway registry on the workstation diff --git a/bin/coreapp b/bin/coreapp index ec0272d..bbbc3a2 100755 --- a/bin/coreapp +++ b/bin/coreapp @@ -15,12 +15,20 @@ # coreapp shell [command] a shell in its container, or run one command there # coreapp remove uninstall it from the Core (asks first) # coreapp list the apps on the Core installed this way +# coreapp install <https://host/owner/repo>[@tag] +# install a published app from its repository, as +# a Core's owner would (shows what it needs first) +# coreapp update <name> update an app installed from a repository to its +# newest release +# coreapp login <host> give the Core a token for private apps from host +# (asks for the user and token); logout <host>, +# logins: forget one, list them # coreapp publish [--platform <list>] # build the release image and push it to the # registry in coreapp.toml, and tag the commit # -# Run everything but `new` and `list` in the app's folder (the one with -# coreapp.toml). COREAPP_VM picks the VM (default coreserver). +# Run deploy, check, status, logs, shell, remove and publish in the app's +# folder (the one with coreapp.toml). COREAPP_VM picks the VM (default coreserver). set -euo pipefail @@ -38,7 +46,8 @@ VM="${COREAPP_VM:-coreserver}" die() { echo "$*" >&2; exit 1; } usage() { - sed -n '/^# coreapp /s/^# //p' "${BASH_SOURCE[0]}" + # The command list at the top of this file, continuation lines included + sed -n '/^# coreapp new/,/^#$/{/^#$/d;s/^# //p}' "${BASH_SOURCE[0]}" } # --- The Core ------------------------------------------------------------- @@ -319,6 +328,79 @@ cmd_list() { core "$REMOTE_INSTALLER/coreapps list" } +# --- install, update (published apps) ----------------------------------- + +cmd_install() { + local source="${1:-}" plan key value answer addon="" + local -A info=() + [[ $# -eq 1 && "$source" == https://* ]] \ + || die "Usage: coreapp install <https://host/owner/repo>[@tag] (default: its newest release)" + init_core + sync_installer + echo "Reading $source..." + plan="$(core "$REMOTE_INSTALLER/coreapps plan $(printf '%q' "$source")")" || exit 1 + while IFS='=' read -r key value; do info[$key]="$value"; done <<< "$plan" + + echo + echo " ${info[title]} ${info[version]}${info[description]:+: ${info[description]}}" + echo " From: ${info[source]} (${info[tag]}, commit ${info[commit]:0:12})" + echo " Image: ${info[image]}:${info[version]}" + echo " Needs: ${info[needs]:-nothing from the Core}" + if [[ "${info[state]}" == update ]]; then + echo " Updates the installed ${info[name]}, keeping its settings and data." + else + echo " Installs it at ${info[url]}" + fi + echo + if [[ "${info[addon]}" == yes ]]; then + echo "This Core's tier is '${info[tier]}'. Installing records '${info[name]}' as an add-on" + echo "app (ADDON_APPS in /etc/federated), which Federated may bill for." + addon=--addon-ok + fi + read -r -p "Install it? [y/N] " answer + [[ "$answer" =~ ^[Yy] ]] || die "Not installed." + core "$REMOTE_INSTALLER/coreapps install $addon $(printf '%q' "$source")" +} + +cmd_update() { + local name="${1:-}" + [[ $# -eq 1 && "$name" =~ ^[a-z][a-z0-9-]*$ ]] || die "Usage: coreapp update <name>" + init_core + sync_installer + core "$REMOTE_INSTALLER/coreapps update $name" +} + +cmd_login() { + local host="${1:-}" user token + [[ $# -eq 1 && "$host" =~ ^[a-z0-9][a-z0-9.:-]*$ ]] \ + || die "Usage: coreapp login <host> (e.g. coreapp login gitea.federated.computer)" + echo "The Core in '$VM' keeps this token to install private apps from $host:" + echo "their repositories and images. For Gitea, make a token for it with read" + echo "access to repositories and packages (Settings > Applications)." + read -r -p "User on $host: " user + [[ "$user" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "'$user' isn't a user name." + read -r -s -p "Token: " token + echo + init_core + sync_installer + # On stdin, so it's never in a command line + printf '%s\n' "$token" | core "$REMOTE_INSTALLER/coreapps login $host $user" +} + +cmd_logout() { + local host="${1:-}" + [[ $# -eq 1 && "$host" =~ ^[a-z0-9][a-z0-9.:-]*$ ]] || die "Usage: coreapp logout <host>" + init_core + sync_installer + core "$REMOTE_INSTALLER/coreapps logout $host" +} + +cmd_logins() { + init_core + sync_installer + core "$REMOTE_INSTALLER/coreapps logins" +} + # --- publish ---------------------------------------------------------------- # A registry image name from the repository's git remote, as a suggestion: @@ -425,6 +507,11 @@ case "$cmd" in remove | rm) cmd_remove ;; list | ls) cmd_list ;; publish) cmd_publish "$@" ;; + install) cmd_install "$@" ;; + update) cmd_update "$@" ;; + login) cmd_login "$@" ;; + logout) cmd_logout "$@" ;; + logins) cmd_logins ;; help | -h | --help) usage ;; *) usage >&2; exit 1 ;; esac diff --git a/core/coreapps b/core/coreapps index e0fb102..9145121 100755 --- a/core/coreapps +++ b/core/coreapps @@ -9,18 +9,33 @@ own templates, so what an app can do on the Core is decided here, not by whoever wrote the app. coreapps manifest <dir> check <dir>/coreapp.toml, print its values -coreapps plan <dir> what install would do on this Core -coreapps install [--addon-ok] [--recreate] <dir> +coreapps plan <source> what install would do on this Core +coreapps install [--addon-ok] [--recreate] <source> install the app, or update it (--recreate: a new container even if nothing changed) +coreapps update [--addon-ok] <name> update an app installed from a + repository to its newest release coreapps remove <name> uninstall an app installed by coreapps coreapps list the apps installed by coreapps +coreapps login <host> <user> keep a token (read from stdin) for + installing private apps from host +coreapps logout <host> forget host's token +coreapps logins the hosts this Core has tokens for + +<source> is a folder with coreapp.toml (and icon.png), or a git +repository: https://host/owner/repo[@tag]. A private repository, and a +private image, need a token for their host (coreapps login): a Gitea token +with read access to repositories and packages. From a repository, only +coreapp.toml and icon.png are read, at the tag (default: the newest +release tag, v1.2.3), whose version must match; the image is pulled from +its registry. `manifest` also works off the Core. install exits with 3 if this Core's tier would record the app as a billable add-on and --addon-ok isn't given. """ +import base64 import json import os import re @@ -31,6 +46,7 @@ import tempfile import time import tomllib import urllib.error +import urllib.parse import urllib.request HERE = os.path.dirname(os.path.realpath(__file__)) @@ -71,6 +87,24 @@ FIELDS = { } REQUIRED = ["name", "title", "version", "image", "port"] +# Repositories apps are installed from: https only, no user or password in +# the URL. Tags: v + a version; releases (picked by default) are numeric. +REPO_URL = r"https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._-]+){2,}?(?:\.git)?/?" +TAG = r"v[A-Za-z0-9][A-Za-z0-9._-]{0,63}" +RELEASE_TAG = r"v[0-9]+(?:\.[0-9]+)*" +# git for untrusted repositories: https only, never asks for a password, +# ignores the system's and root's git settings +GIT_ENV = {"PATH": "/usr/bin:/bin", "GIT_TERMINAL_PROMPT": "0", + "GIT_ALLOW_PROTOCOL": "https", "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", "HOME": "/nonexistent", + "LC_ALL": "C"} +GIT_TIMEOUT = 120 +# Tokens for private repositories and registries, by host (root only) +CREDENTIALS = "/etc/coreapps/credentials" +HOST = r"[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[0-9]{1,5})?" +LOGIN_USER = r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}" +TOKEN = r"[A-Za-z0-9._~+/=-]{8,512}" + class Refused(Exception): """The app can't be installed as it is; the message says why.""" @@ -85,6 +119,8 @@ def say(*args): def read_manifest(folder): """coreapp.toml in folder, checked, with defaults filled in.""" path = os.path.join(folder, "coreapp.toml") + if os.path.islink(path): + raise Refused("coreapp.toml is a symbolic link; it has to be a file.") try: with open(path, "rb") as f: data = tomllib.load(f) @@ -215,7 +251,245 @@ def pick_address(name): raise Refused(f"No free address left in {PREFIX}{FIRST}-{LAST}.") -def plan(m): +# --- Tokens for private apps ---------------------------------------------------- + +def read_credentials(): + try: + with open(CREDENTIALS, "rb") as f: + data = tomllib.load(f) + except FileNotFoundError: + return {} + except tomllib.TOMLDecodeError as e: + raise Refused(f"{CREDENTIALS} isn't valid: {e}") + return {host: c for host, c in data.items() + if isinstance(c, dict) and re.fullmatch(LOGIN_USER, str(c.get("user", ""))) + and re.fullmatch(TOKEN, str(c.get("token", "")))} + + +def write_credentials(creds): + os.makedirs(os.path.dirname(CREDENTIALS), mode=0o700, exist_ok=True) + os.chmod(os.path.dirname(CREDENTIALS), 0o700) + text = ("# Tokens coreapps uses to install private apps, by host. Manage with\n" + "# coreapps login / logout.\n") + for host in sorted(creds): + text += f'\n["{host}"]\nuser = "{creds[host]["user"]}"\ntoken = "{creds[host]["token"]}"\n' + new = CREDENTIALS + ".new" + fd = os.open(new, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + f.write(text) + os.rename(new, CREDENTIALS) + + +def basic_auth(host): + """'user:token' in base64 for host, or None.""" + c = read_credentials().get(host) + if not c: + return None + return base64.b64encode(f"{c['user']}:{c['token']}".encode()).decode() + + +def url_host(url): + return url.split("://", 1)[1].split("/", 1)[0].lower() + + +def check_token(host, user, token): + """Whether host's registry accepts the token: True, False, or None + (couldn't tell).""" + auth = "Basic " + base64.b64encode(f"{user}:{token}".encode()).decode() + + def get(url): + req = urllib.request.Request(url, headers={"Authorization": auth}) + try: + with urllib.request.urlopen(req, timeout=15) as r: + return r.status, r.headers + except urllib.error.HTTPError as e: + return e.code, e.headers + except (urllib.error.URLError, OSError): + return None, {} + + status, headers = get(f"https://{host}/v2/") + if status == 200: + return True + challenge = (headers or {}).get("WWW-Authenticate", "") + m = re.search(r'realm="([^"]+)"', challenge) + if status == 401 and challenge.lower().startswith("bearer") and m: + service = re.search(r'service="([^"]+)"', challenge) + realm = m.group(1) + (f"?service={urllib.parse.quote(service.group(1))}" if service else "") + status, _ = get(realm) + if status == 200: + return True + if status in (401, 403): + return False + return False if status in (401, 403) else None + + +def login(host, user): + host = host.lower() + if not re.fullmatch(HOST, host): + raise Refused(f"'{host}' isn't a host name (like gitea.example.com).") + if not re.fullmatch(LOGIN_USER, user): + raise Refused(f"'{user}' isn't a user name.") + token = sys.stdin.readline().strip() + if not re.fullmatch(TOKEN, token): + raise Refused("That isn't a token (8-512 letters, digits and . _ ~ + / = -).") + ok = check_token(host, user, token) + if ok is False: + raise Refused(f"{host} rejected the token for {user}. Nothing was saved.") + creds = read_credentials() + creds[host] = {"user": user, "token": token} + write_credentials(creds) + say(f"Saved a token for {user}@{host}" + + (" (its registry accepts it)." if ok else " (couldn't check it with its registry).")) + return 0 + + +def logout(host): + creds = read_credentials() + if creds.pop(host.lower(), None) is None: + say(f"No token for {host}.") + return 0 + write_credentials(creds) + say(f"Forgot the token for {host}.") + return 0 + + +def list_logins(): + creds = read_credentials() + if not creds: + say("No tokens: this Core installs public apps only.") + for host in sorted(creds): + say(f"{host} (user {creds[host]['user']})") + return 0 + + +# --- Where an app comes from: a folder or a repository ------------------------ + +def normalize_url(url): + """https://Host/owner/repo.git/ -> https://host/owner/repo""" + url = url.rstrip("/") + if url.endswith(".git"): + url = url[:-4] + scheme, _, rest = url.partition("://") + host, _, path = rest.partition("/") + return f"{scheme}://{host.lower()}/{path}" + + +def version_key(tag): + return [int(part) for part in tag[1:].split(".")] + + +def git(args, cwd=None, auth=None): + """git with GIT_ENV; auth: (url prefix, base64 user:token) to send as a + header (in the environment, so it's never in a URL or an error).""" + env = dict(GIT_ENV) + if auth: + env.update({"GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": f"http.{auth[0]}/.extraHeader", + "GIT_CONFIG_VALUE_0": f"Authorization: Basic {auth[1]}"}) + try: + out = subprocess.run(["git", *args], cwd=cwd, env=env, capture_output=True, + timeout=GIT_TIMEOUT) + except subprocess.TimeoutExpired: + raise Refused(f"git {args[0]} took longer than {GIT_TIMEOUT} s.") + return out + + +def git_blob(folder, commit, path, limit, auth=None): + """A regular file's bytes at commit, or None if it isn't one (missing, + a link, a folder) or is bigger than limit. (Fetched on demand, so it may + need the repository's token.)""" + out = git(["ls-tree", commit, "--", path], cwd=folder, auth=auth) + fields = out.stdout.decode().split() + if out.returncode != 0 or len(fields) < 3 or fields[0] != "100644" or fields[1] != "blob": + return None + size = git(["cat-file", "-s", fields[2]], cwd=folder, auth=auth) + if size.returncode != 0 or int(size.stdout or 0) > limit: + return None + blob = git(["cat-file", "blob", fields[2]], cwd=folder, auth=auth) + return blob.stdout if blob.returncode == 0 else None + + +def fetch_repo(arg, staging): + """coreapp.toml and icon.png from a repository at a tag, into staging. + Returns the source's details.""" + url, _, tag = arg.partition("@") + if not re.fullmatch(REPO_URL, url): + raise Refused(f"'{url}' isn't a repository address coreapps installs from: " + "https://host/owner/repo (no user or password in it).") + url = normalize_url(url) + host = url_host(url) + token = basic_auth(host) + auth = (f"https://{host}", token) if token else None + no_access = ("" if token else + f" If it's private, give this Core a token for {host}: coreapp login {host}.") + if tag and not re.fullmatch(TAG, tag): + raise Refused(f"'{tag}' isn't a release tag (v and a version, like v1.2.0).") + if not tag: + out = git(["ls-remote", "--tags", "--refs", url], auth=auth) + if out.returncode != 0: + raise Refused(f"Couldn't read {url}: {out.stderr.decode().strip() or 'no answer'}." + + no_access) + tags = [line.split("refs/tags/", 1)[1] for line in out.stdout.decode().splitlines() + if "refs/tags/" in line] + releases = [t for t in tags if re.fullmatch(RELEASE_TAG, t)] + if not releases: + raise Refused(f"{url} has no release tags (like v1.2.0). Publish a release " + "(coreapp publish tags it), or name a tag: <url>@<tag>.") + tag = max(releases, key=version_key) + git(["init", "-q", "--bare", staging + "/git"]) + out = git(["fetch", "-q", "--depth", "1", "--filter=blob:none", "--no-tags", url, + f"refs/tags/{tag}"], cwd=staging + "/git", auth=auth) + if out.returncode != 0: + raise Refused(f"Couldn't fetch {tag} from {url}: {out.stderr.decode().strip()}" + + no_access) + commit = git(["rev-parse", "FETCH_HEAD^{commit}"], cwd=staging + "/git").stdout.decode().strip() + manifest = git_blob(staging + "/git", commit, "coreapp.toml", 64 * 1024, auth) + if manifest is None: + raise Refused(f"{url} has no coreapp.toml (a file, up to 64 KB) at {tag}.") + with open(os.path.join(staging, "coreapp.toml"), "wb") as f: + f.write(manifest) + icon = git_blob(staging + "/git", commit, "icon.png", 1024 * 1024, auth) + if icon is not None: + with open(os.path.join(staging, "icon.png"), "wb") as f: + f.write(icon) + shutil.rmtree(staging + "/git") + return {"source": url, "tag": tag, "commit": commit} + + +def resolve(arg, staging): + """The folder to read the app from, and where it came from.""" + if arg.startswith("https://"): + return staging, fetch_repo(arg, staging) + if not os.path.isdir(arg): + raise Refused(f"'{arg}' is neither a folder nor an https:// repository.") + return arg, {} + + +def check_release(m, origin): + """A repository's app: its version is the tag's, its image can be pulled.""" + if not origin: + return + if "v" + m["version"] != origin["tag"]: + raise Refused(f"At {origin['tag']}, coreapp.toml says version = \"{m['version']}\"; " + "a release's tag and version have to match.") + if m["image"].startswith("localhost/"): + raise Refused(f"image = \"{m['image']}\" is a local image, which can't be " + "installed from a repository. Publish it to a registry first " + "(coreapp publish).") + + +def marker_value(name, key): + try: + with open(os.path.join(SERVICES, name, MARKER)) as f: + for line in f: + if line.startswith(key + "="): + return line.split("=", 1)[1].strip() + except OSError: + pass + return "" + + +def plan(m, origin=None): """What installing m would do here, or Refused.""" name = m["name"] domain, tier = federated_settings() @@ -246,8 +520,17 @@ def plan(m): "removing them would delete what the app keeps there. " "Remove the app and install it again to do that.") p["new_needs"] = [n for n in m["needs"] if n not in before] + # Another repository's app of the same name would take over this + # one's data, database and sign-in client + installed_from = marker_value(name, "source") + if origin and installed_from and installed_from != origin["source"]: + raise Refused(f"'{name}' on this Core was installed from {installed_from}, " + f"not {origin['source']}. Remove it first to install this one.") else: p["new_needs"] = list(m["needs"]) + for key in ("source", "tag", "commit"): + if origin: + p[key] = origin[key] return p @@ -277,7 +560,7 @@ def icon_from(folder): """The app's icon.png if it's a reasonable PNG, else the default.""" path = os.path.join(folder, "icon.png") try: - if os.path.getsize(path) <= 1024 * 1024: + if not os.path.islink(path) and os.path.getsize(path) <= 1024 * 1024: with open(path, "rb") as f: if f.read(8) == b"\x89PNG\r\n\x1a\n": return path @@ -286,7 +569,7 @@ def icon_from(folder): return os.path.join(TEMPLATES, "icon.png") -def make_service_folder(m, p, source): +def make_service_folder(m, p, source, origin): """/federated/services/<name>/ in the Core's generic format, from m.""" values = { "NAME": m["name"], "TITLE": m["title"], "DESCRIPTION": m["description"], @@ -319,7 +602,9 @@ def make_service_folder(m, p, source): shutil.copyfile(os.path.join(source, "coreapp.toml"), os.path.join(new, "coreapp.toml")) write(os.path.join(new, MARKER), "# Installed by coreapps; delete with coreapps remove\n" - f"needs={' '.join(m['needs'])}\n") + f"needs={' '.join(m['needs'])}\n" + + "".join(f"{key}={origin[key]}\n" for key in ("source", "tag", "commit") + if origin)) shutil.rmtree(final, ignore_errors=True) os.rename(new, final) @@ -345,17 +630,34 @@ def run_logged(cmd, log, failure): raise Refused(f"{failure} (whole log on the Core: {log}).") -def ensure_image(m): +def ensure_image(m, pull=False): + """The image on this Core. pull: always from its registry (a release is + what's published, not a same-named image built here).""" ref = f"{m['image']}:{m['version']}" - if run(["docker", "image", "inspect", ref]).returncode == 0: + if not pull and run(["docker", "image", "inspect", ref]).returncode == 0: return if m["image"].startswith("localhost/"): raise Refused(f"The image {ref} isn't on this Core, and localhost/ images " "can't be pulled. coreapp deploy copies it here.") say(f"Pulling {ref}...") - out = run(["docker", "pull", "-q", ref]) + registry = m["image"].split("/", 1)[0] + token = basic_auth(registry) + # The token goes in a docker config just for this pull, so the Core + # keeps no docker login + with tempfile.TemporaryDirectory(prefix="coreapps-docker-") as config: + env = dict(os.environ) + if token: + key = "https://index.docker.io/v1/" if registry == "docker.io" else registry + fd = os.open(os.path.join(config, "config.json"), os.O_WRONLY | os.O_CREAT, 0o600) + with os.fdopen(fd, "w") as f: + json.dump({"auths": {key: {"auth": token}}}, f) + env["DOCKER_CONFIG"] = config + out = run(["docker", "pull", "-q", ref], env=env) if out.returncode != 0: - raise Refused(f"Couldn't pull {ref}: {out.stderr.strip()}") + hint = ("" if token else + f" If it's private, give this Core a token for {registry}: coreapp login {registry}.") + raise Refused(f"Couldn't pull {ref}: {out.stderr.strip().rstrip('.')}." + + (hint or " Is it published?")) def image_user(ref): @@ -425,17 +727,27 @@ done ''' -def install(folder, addon_ok, recreate=False): - m = read_manifest(folder) - p = plan(m) +def install(arg, addon_ok, recreate=False): + with tempfile.TemporaryDirectory(prefix="coreapps-") as staging: + folder, origin = resolve(arg, staging) + m = read_manifest(folder) + check_release(m, origin) + p = plan(m, origin) + return install_app(m, p, folder, origin, addon_ok, recreate) + + +def install_app(m, p, folder, origin, addon_ok, recreate): name = m["name"] if p["addon"] == "yes" and not addon_ok: say(f"This Core's tier is '{p['tier']}': installing records '{name}' as an " "add-on app (ADDON_APPS in /etc/federated), which Federated may bill for. " "Run again with --addon-ok to install anyway.") return 3 - ensure_image(m) - make_service_folder(m, p, folder) + if origin: + say(f"{m['title']} {m['version']} from {origin['source']} ({origin['tag']}, " + f"commit {origin['commit'][:12]})") + ensure_image(m, pull=bool(origin)) + make_service_folder(m, p, folder, origin) if p["state"] == "new": say(f"Installing {name} at {p['address']} (the Core's installapp)...") @@ -462,12 +774,32 @@ def install(folder, addon_ok, recreate=False): return 0 +def short_name(image): + """The image's name as docker lists it (docker.io/library/x is x).""" + for prefix in ("docker.io/library/", "docker.io/"): + if image.startswith(prefix): + return image[len(prefix):] + return image + + +def image_tags(image): + """The tags of image on this Core.""" + out = run(["docker", "image", "ls", "--format", "{{.Repository}} {{.Tag}}"]) + return [tag for repo, _, tag in (line.partition(" ") for line in out.stdout.splitlines()) + if repo == short_name(image) and tag != "<none>"] + + +def remove_images(image, keep=None): + """image's tags on this Core except keep. Without force: docker refuses + to delete one a container uses (another app may use the same image).""" + for tag in image_tags(image): + if tag != keep: + run(["docker", "image", "rm", f"{short_name(image)}:{tag}"]) + + def remove_old_images(m): """The app's images with other versions, now that this one runs.""" - out = run(["docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}", m["image"]]) - for ref in out.stdout.split(): - if ref != f"{m['image']}:{m['version']}": - run(["docker", "image", "rm", ref]) + remove_images(m["image"], keep=m["version"]) def wait_until_answering(m, p): @@ -494,6 +826,26 @@ def wait_until_answering(m, p): "its log is above).") +def update(name, addon_ok): + """An app installed from a repository, to its newest release.""" + if not re.fullmatch(FIELDS["name"], name) or not is_ours(name): + raise Refused(f"No app called '{name}' installed by coreapps on this Core.") + source = marker_value(name, "source") + if not source: + raise Refused(f"'{name}' was installed from a folder, not a repository; " + "update it the same way (coreapp deploy).") + with tempfile.TemporaryDirectory(prefix="coreapps-") as staging: + folder, origin = resolve(source, staging) + if origin["tag"] == marker_value(name, "tag"): + say(f"{name} is at the newest release, {origin['tag']}.") + return 0 + m = read_manifest(folder) + check_release(m, origin) + if m["name"] != name: + raise Refused(f"At {origin['tag']}, {source} is the app '{m['name']}', not '{name}'.") + return install_app(m, plan(m, origin), folder, origin, addon_ok, False) + + def remove(name): if not re.fullmatch(FIELDS["name"], name): raise Refused(f"'{name}' isn't an app name.") @@ -509,9 +861,7 @@ def remove(name): run_logged([FEDERATED + "/bin/uninstallapp", name], log, "uninstallapp failed") shutil.rmtree(folder) if image: - ids = run(["docker", "image", "ls", "-q", image]).stdout.split() - for image_id in sorted(set(ids)): - run(["docker", "image", "rm", "-f", image_id]) + remove_images(image) # uninstallapp made superpanel's catalog while the folder was still # there, so it would still offer the app: make it again, as installapp # does @@ -530,12 +880,14 @@ def list_apps(): continue service = os.path.join(SERVICES, name, "service") state = run(["docker", "inspect", "-f", "{{.State.Status}}", name]).stdout.strip() + source = marker_value(name, "source") rows.append((name, service_value(service, "VERSION"), - service_value(service, "INTERNAL_IP"), state or "not running")) + service_value(service, "INTERNAL_IP"), state or "not running", + f"{source}@{marker_value(name, 'tag')}" if source else "(from a folder)")) if not rows: say("No apps installed by coreapps.") for row in rows: - say("%-24s %-12s %-16s %s" % row) + say("%-24s %-12s %-14s %-12s %s" % row) return 0 @@ -556,7 +908,14 @@ def main(args): if os.geteuid() != 0: raise Refused("Run coreapps as root on the Core.") if cmd == "plan" and len(rest) == 1: - p = plan(read_manifest(rest[0])) + with tempfile.TemporaryDirectory(prefix="coreapps-") as staging: + folder, origin = resolve(rest[0], staging) + m = read_manifest(folder) + check_release(m, origin) + p = plan(m, origin) + for key in ("name", "title", "description", "version", "image"): + print(f"{key}={m[key]}") + print(f"needs={' '.join(m['needs'])}") for key, value in p.items(): print(f"{key}={' '.join(value) if isinstance(value, list) else value}") return 0 @@ -566,8 +925,18 @@ def main(args): folders = [a for a in rest if a not in ("--addon-ok", "--recreate")] if len(folders) == 1: return install(folders[0], addon_ok, recreate) + if cmd == "update" and rest: + names = [a for a in rest if a != "--addon-ok"] + if len(names) == 1: + return update(names[0], "--addon-ok" in rest) if cmd == "remove" and len(rest) == 1: return remove(rest[0]) + if cmd == "login" and len(rest) == 2: + return login(rest[0], rest[1]) + if cmd == "logout" and len(rest) == 1: + return logout(rest[0]) + if cmd == "logins" and not rest: + return list_logins() if cmd == "list" and not rest: return list_apps() sys.stderr.write(__doc__.split("\n\n", 2)[2].strip() + "\n") diff --git a/skills/coreapp/SKILL.md b/skills/coreapp/SKILL.md index ae70371..661eaed 100644 --- a/skills/coreapp/SKILL.md +++ b/skills/coreapp/SKILL.md @@ -296,8 +296,18 @@ Actions runner that can use Docker and the secrets `REGISTRY_USER` and `REGISTRY_TOKEN`. When porting an existing app, copy it from a new app (`coreapp new x`) if the user wants it. -Installing a published app on a Core from its repository URL isn't -available yet; for now, apps are installed with `coreapp deploy`. +To check a release the way a Core's owner will get it: +`coreapp install https://<gitea-host>/<owner>/<repo>` installs it on the +Core in the VM from the repository (the newest `v*` tag; `@v1.2.0` for +another), pulling the published image, and `coreapp update <name>` moves it +to a newer release. Coreapps are often private: for a private repository +and image, the Core needs a token for the host first, `coreapp login +<gitea-host>`, which asks for a user name and a read-only token +(repositories and packages). That's the user's to enter, not yours. The Core +only reads `coreapp.toml` and `icon.png` from the repository; `version` has +to match the tag. On the same Core, `coreapp deploy` from the folder and +`coreapp install` from the repository update the same app (same name, data +and database). ## Reporting back