diff --git a/PLAN.md b/PLAN.md index adefa18..ae608bd 100644 --- a/PLAN.md +++ b/PLAN.md @@ -305,10 +305,21 @@ Steps: 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 + - Done 2026-12-03: downgrades and digests. Installing an older release + than the installed one is refused unless `--downgrade` (coreapps + install/plan, coreapp install; the plan says what it goes back from); + a failed start still rolls back. After pulling a release, coreapps + records its registry digest in the marker and `.env` + (`IMAGE_DIGEST=@sha256:...`, written by coreapps, not `templatize`, + which reads any `@...@` on a line as a variable), and the compose + file runs `image:${IMAGE_VERSION}${IMAGE_DIGEST:-}`, so a re-pushed + tag can't change an installed app, even on a recreate; installing the + same release again with another digest is refused and the tag is put + back on the installed image. Folder deploys have it empty. Tested on + dev.fedcom.net with a registry on the Core and a `file://` repository + (install, refusal, `--downgrade`, upgrade, re-pushed tag refused, + recreate), with pub-test from gitea.federated.computer (pinned), and + hello (empty) 4. Email (2026-12-03): `needs = ["email"]` (`coreapp new --email`) gives the app its own mail account for sending: an LDAP entry `uid=coreapp-,ou=people` with `objectClass: account`, diff --git a/README.md b/README.md index 86b371a..e2e5f4e 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ each new app explains the files and the settings it gets. | `coreapp signin [path]` | Sign in to it as a browser would, with the Core's test account (`coreapp.test@`, made on the VM's Core when first needed), starting at `path` (default `/login`), and show each step; `--cookies ` keeps the app's cookies, `--code` gets a code for apps that start sign-in in the browser, `--remove-account` removes the account | | `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 install [--downgrade] [@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; an older release than the installed one only with `--downgrade`) | | `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` | @@ -114,8 +114,13 @@ 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. +gets the token only for each pull, so the Core keeps no docker login. +The Core runs the image it pulled at install, by its digest +(`image:version@sha256:...`), so pushing the tag again can't change an +installed app; installing that release again then is refused. Installing an +older release than the installed one is refused too (it may not understand +the newer one's data) unless you add `--downgrade`. 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 diff --git a/TEST.md b/TEST.md index 8c2b9ae..a3f64a9 100644 --- a/TEST.md +++ b/TEST.md @@ -433,7 +433,23 @@ has a `coreapp.toml` with a published, public `image` (e.g. after `/federated/services//.coreapp` has `source`, `tag`, `commit`. 2. Publish a newer version, then `coreapp update `: "Updated", the old image is gone from the Core. Again: "at the newest release". -3. `coreapp install @v`: installs that tag. +3. `coreapp install @v` with a newer one installed: + "is older, and may not understand the data ... add --downgrade", nothing + changed. `coreapp install --downgrade @v`: the plan + says "Goes back from the installed v", then installs that tag; the + newer image is gone from the Core. +3a. Digest: after installing, "Image: :@sha256:..."; the + marker has `digest=`, the `.env` `IMAGE_DIGEST=@sha256:...`, `docker + compose config --images` and the container's image are + `:@sha256:...`. Push another image to the same tag, then + install that release again: "isn't the image installed here ... the + release was changed after it was published", the app keeps running, + `:` on the Core is the installed image again, and + `docker compose up --force-recreate` runs it. An app deployed from a + folder has `IMAGE_DIGEST=` (empty) and runs `:`. + (Tested with a registry on the Core, `docker run -p 127.0.0.1:5000:5000 + registry:2`, `image = "localhost:5000/"`, and a `file://` + repository as below.) 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`) @@ -459,8 +475,9 @@ has a `coreapp.toml` with a published, public `image` (e.g. after 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). +`core/coreapps` as a module and replacing `REPO_URL`, `normalize_url`, +`resolve` and `GIT_ENV["GIT_ALLOW_PROTOCOL"]` for `file://` (only in the +test). ## Publishing (coreapp publish) diff --git a/bin/coreapp b/bin/coreapp index c72dfe1..72f2d10 100755 --- a/bin/coreapp +++ b/bin/coreapp @@ -24,9 +24,11 @@ # remove the test account from the Core # coreapp remove uninstall it from the Core (asks first) # coreapp list the apps on the Core installed this way -# coreapp install [@tag] +# coreapp install [--downgrade] [@tag] # install a published app from its repository, as -# a Core's owner would (shows what it needs first) +# a Core's owner would (shows what it needs first; +# --downgrade: allow an older release than the +# installed one) # coreapp update update an app installed from a repository to its # newest release # coreapp login give the Core a token for private apps from host @@ -410,14 +412,16 @@ cmd_list() { # --- install, update (published apps) ----------------------------------- cmd_install() { - local source="${1:-}" plan key value answer addon="" + local source plan key value answer addon="" downgrade="" local -A info=() + if [[ "${1:-}" == --downgrade ]]; then downgrade=--downgrade; shift; fi + source="${1:-}" [[ $# -eq 1 && "$source" == https://* ]] \ - || die "Usage: coreapp install [@tag] (default: its newest release)" + || die "Usage: coreapp install [--downgrade] [@tag] (default: its newest release)" init_core sync_installer echo "Reading $source..." - plan="$(core "$REMOTE_INSTALLER/coreapps plan $(printf '%q' "$source")")" || exit 1 + plan="$(core "$REMOTE_INSTALLER/coreapps plan $downgrade $(printf '%q' "$source")")" || exit 1 while IFS='=' read -r key value; do info[$key]="$value"; done <<< "$plan" echo @@ -425,7 +429,10 @@ cmd_install() { 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 + if [[ -n "${info[downgrade_from]:-}" ]]; then + echo " Goes back from the installed ${info[downgrade_from]}, keeping its settings and data," + echo " which the older version may not understand." + elif [[ "${info[state]}" == update ]]; then echo " Updates the installed ${info[name]}, keeping its settings and data." else echo " Installs it at ${info[url]}" @@ -438,7 +445,7 @@ cmd_install() { fi read -r -p "Install it? [y/N] " answer [[ "$answer" =~ ^[Yy] ]] || die "Not installed." - core "$REMOTE_INSTALLER/coreapps install $addon $(printf '%q' "$source")" + core "$REMOTE_INSTALLER/coreapps install $addon $downgrade $(printf '%q' "$source")" } cmd_update() { diff --git a/core/coreapps b/core/coreapps index cbd6cc1..78575b6 100755 --- a/core/coreapps +++ b/core/coreapps @@ -9,11 +9,12 @@ own templates, so what an app can do on the Core is decided here, not by whoever wrote the app. coreapps manifest check /coreapp.toml, print its values -coreapps plan what install would do on this Core -coreapps install [--addon-ok] [--recreate] +coreapps plan [--downgrade] what install would do on this Core +coreapps install [--addon-ok] [--recreate] [--downgrade] install the app, or update it (--recreate: a new container even if - nothing changed) + nothing changed; --downgrade: allow an + older release than the installed one) coreapps update [--addon-ok] update an app installed from a repository to its newest release coreapps remove uninstall an app installed by coreapps @@ -413,6 +414,10 @@ def normalize_url(url): return f"{scheme}://{host.lower()}/{path}" +def is_release(tag): + return bool(re.fullmatch(r"v[0-9]+(?:\.[0-9]+)*", tag or "")) + + def version_key(tag): return [int(part) for part in tag[1:].split(".")] @@ -528,7 +533,7 @@ def marker_value(name, key): return "" -def plan(m, origin=None): +def plan(m, origin=None, downgrade=False): """What installing m would do here, or Refused.""" name = m["name"] domain, tier = federated_settings() @@ -565,6 +570,18 @@ def plan(m, origin=None): 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.") + # An older release may not understand what the newer one left in + # its database and /data + installed_tag = marker_value(name, "tag") + if origin and is_release(installed_tag) and is_release(origin["tag"]) \ + and version_key(origin["tag"]) < version_key(installed_tag): + if not downgrade: + raise Refused( + f"'{name}' has {installed_tag} installed; {origin['tag']} is older, and may " + "not understand the data the newer version left (its database and /data). " + "To install it anyway, add --downgrade (if it fails to start, the update " + "rolls back).") + p["downgrade_from"] = installed_tag else: p["new_needs"] = list(m["needs"]) for key in ("source", "tag", "commit"): @@ -669,8 +686,8 @@ def make_service_folder(m, p, source, origin): write(os.path.join(new, MARKER), "# Installed by coreapps; delete with coreapps remove\n" f"needs={' '.join(m['needs'])}\n" - + "".join(f"{key}={origin[key]}\n" for key in ("source", "tag", "commit") - if origin)) + + "".join(f"{key}={origin[key]}\n" for key in ("source", "tag", "commit", "digest") + if origin and origin.get(key))) shutil.rmtree(final, ignore_errors=True) os.rename(new, final) @@ -726,6 +743,32 @@ def ensure_image(m, pull=False): + (hint or " Is it published?")) +def image_digest(m): + """The registry's digest of the pulled image:version (sha256:...), or "".""" + out = run(["docker", "image", "inspect", "--format", "{{json .RepoDigests}}", + f"{m['image']}:{m['version']}"]) + + def short(repo): + return repo.removeprefix("docker.io/").removeprefix("library/") + try: + digests = json.loads(out.stdout) if out.returncode == 0 else [] + except ValueError: + digests = [] + for d in digests or []: + repo, _, digest = d.partition("@") + if short(repo) == short(m["image"]) and re.fullmatch(r"sha256:[0-9a-f]{64}", digest): + return digest + return "" + + +def set_env(name, key, value): + """key=value in the app's .env, replacing it or added at the end.""" + path = f"{APPS}/{name}/.env" + with open(path) as f: + lines = [line for line in f.read().splitlines() if not line.startswith(key + "=")] + write(path, "\n".join(lines + [f"{key}={value}"]) + "\n", 0o600) + + def image_user(ref): """The uid:gid the image runs as, or None for root (or unknown).""" user = run(["docker", "image", "inspect", "-f", "{{.Config.User}}", ref]).stdout.strip() @@ -756,6 +799,9 @@ def prepare_data(m): def compose_up(m, log, recreate=False): name = m["name"] prepare_data(m) + # A release runs the image it was installed with (image:version@digest), + # even if the tag is pushed again; a folder's image by its tag + set_env(name, "IMAGE_DIGEST", "@" + m["digest"] if m.get("digest") else "") run_logged(["docker", "compose", "-f", f"{APPS}/{name}/docker-compose.yml", "-p", name, "up", "-d", "--remove-orphans", *(["--force-recreate"] if recreate else [])], log, @@ -793,12 +839,12 @@ done ''' -def install(arg, addon_ok, recreate=False): +def install(arg, addon_ok, recreate=False, downgrade=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) + p = plan(m, origin, downgrade) return install_app(m, p, folder, origin, addon_ok, recreate) @@ -813,6 +859,8 @@ def install_app(m, p, folder, origin, addon_ok, recreate): say(f"{m['title']} {m['version']} from {origin['source']} ({origin['tag']}, " f"commit {origin['commit'][:12]})") ensure_image(m, pull=bool(origin)) + if origin: + pin_release(m, p, origin) state, note = icon_check(folder) if state != "ok": say(f"Note: {note}") @@ -858,6 +906,26 @@ def install_app(m, p, folder, origin, addon_ok, recreate): return 0 +def pin_release(m, p, origin): + """Record the pulled release's digest (m and the marker), or refuse if + the release installed here has changed in its registry since.""" + name, ref = m["name"], f"{m['image']}:{m['version']}" + digest = image_digest(m) + if not digest: + raise Refused(f"Can't read the registry's digest of {ref}.") + before = marker_value(name, "digest") if p["state"] == "update" else "" + if before and before != digest and marker_value(name, "tag") == origin["tag"]: + # Put the tag back on the installed image, and drop the changed one + run(["docker", "tag", f"{m['image']}@{before}", ref]) + run(["docker", "image", "rm", f"{m['image']}@{digest}"]) + raise Refused(f"{ref} in its registry isn't the image installed here (installed " + f"{before[:19]}..., now {digest[:19]}...): the release was changed after " + f"it was published. {name} keeps running the installed one. A new " + "version should have a new tag.") + m["digest"] = origin["digest"] = digest + say(f"Image: {ref}@{digest}") + + # Kept during an update, to put back if it fails ROLLBACK_FILES = [".env", "docker-compose.yml"] @@ -1261,12 +1329,14 @@ def main(args): return 0 if os.geteuid() != 0: raise Refused("Run coreapps as root on the Core.") + downgrade = "--downgrade" in rest + rest = [a for a in rest if a != "--downgrade"] if cmd == "plan" and len(rest) == 1: 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) + p = plan(m, origin, downgrade) for key in ("name", "title", "description", "version", "image"): print(f"{key}={m[key]}") print(f"needs={' '.join(m['needs'])}") @@ -1278,7 +1348,7 @@ def main(args): recreate = "--recreate" in rest folders = [a for a in rest if a not in ("--addon-ok", "--recreate")] if len(folders) == 1: - return install(folders[0], addon_ok, recreate) + return install(folders[0], addon_ok, recreate, downgrade) if cmd == "update" and rest: names = [a for a in rest if a != "--addon-ok"] if len(names) == 1: diff --git a/core/templates/docker-compose.yml.in b/core/templates/docker-compose.yml.in index 8f36a47..b21d4d1 100644 --- a/core/templates/docker-compose.yml.in +++ b/core/templates/docker-compose.yml.in @@ -1,6 +1,6 @@ services: {{NAME}}: - image: @CONTAINER@:${IMAGE_VERSION} + image: @CONTAINER@:${IMAGE_VERSION}${IMAGE_DIGEST:-} container_name: {{NAME}} hostname: {{NAME}}.@DOMAIN@ restart: always diff --git a/skills/coreapp/SKILL.md b/skills/coreapp/SKILL.md index 3d8e213..47b91d3 100644 --- a/skills/coreapp/SKILL.md +++ b/skills/coreapp/SKILL.md @@ -458,7 +458,11 @@ and image, the Core needs a token for the host first, `coreapp login 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). +and database). A Core keeps running the image it installed, by digest: a +release can't be fixed by pushing its tag again (installing it again is +refused), so publish a new version. Going back to an older release needs +`coreapp install --downgrade @v`; the user decides that, since +the older version may not understand the newer one's data. ## Reporting back