diff --git a/PLAN.md b/PLAN.md index cbcb15e..ba783da 100644 --- a/PLAN.md +++ b/PLAN.md @@ -109,94 +109,182 @@ What we learned provisioning (2026-12-02/03): - superpanel's catalog lists `services/*/service`, so an app installed this way shows up in the Core's dashboard. -### Design (proposed) +### Design -An app is a folder in the generic format, kept anywhere on the workstation -(its own git repo). A `coreapp` command, run inside that folder, works -against the Core in the local VM (`coreapp-vm ip`): +An app is a folder (its own git repo) on the workstation; `coreapp`, run +inside it, works against the Core in the local VM (`coreapp-vm ip`): `new`, +`deploy` (build, `docker save | ssh docker load`, install or update), +`check`, `status`, `logs`, `shell`, `list`, `remove`. Since 2026-12-03 the +folder has only `coreapp.toml`, the Dockerfile, the code and an icon; the +Core side is made by the installer (see Coreapps below). -- `coreapp new `: scaffold the folder: `service`, - `docker-compose.yml.in` with the traefik labels, `env.in`, `install`, a - placeholder `icon.png`, a `Dockerfile` with a minimal web server, and a - README. Its `INTERNAL_IP` comes from 192.168.200.0/24, well away from - Federated's 192.168.0.x, and different for each app made on this machine. -- `coreapp deploy`: build the image locally (`docker build`), copy it to the - Core (`docker save | ssh docker load`, no registry needed), copy the folder - to `/federated/services//`, then `installapp -n ` the first - time. Later deploys re-render `docker-compose.yml` but keep `.env` (its - random secrets), and restart the app. -- `coreapp status`, `coreapp logs [-f]`, `coreapp shell`: on the Core. -- `coreapp check`: the app answers at `https://./` as its - `MONITOR` line says, with a valid certificate. -- `coreapp remove`: `uninstallapp ` and remove its services folder. - -Built and tested 2026-12-03 with a test app `hello` (busybox httpd): -new, deploy (first install and redeploy), check, status, logs, remove all -work against dev.fedcom.net; `https://hello.dev.fedcom.net/` answers through -the relay. +Built 2026-12-03 and tested against dev.fedcom.net: plain apps, a +database (`--postgres`), sign-in (`--sso`), both. David signed in to +sso-demo and team-visits in a browser. What we learned: - `/federated/bin/start ` only starts apps in the fixed `CORE_APPS` / `EXTRA_APPS` lists in `lib/functions.sh`; for anything else it prints its usage. So `installapp` installs a new app but doesn't start it, and - `start all` skips it. `coreapp deploy` starts it with the same - `docker compose ... up -d`; `restart: always` covers reboots + `start all` skips it. The installer starts it with the same + `docker compose ... up -d`; `restart: always` covers reboots. `bin/stop` + doesn't know them either, so when a dependency (postgresql, authelia) is + upgraded, coreapps' apps keep running; they reconnect - `installapp` / `uninstallapp` call `update_monitors`, which registers or removes the app's `MONITOR` URL with Federated's external monitoring - (blackboxregistrar.monitoreast.fedcom.net). Dev apps get registered too -- `uninstallapp` runs with `set -x`; its trace includes the monitoring - registrar's bearer token (in plain text in `lib/functions.sh`) and the - Core's email addresses. coreapp keeps the trace in - `~/.local/share/coreapp-dev/logs/` (mode 600) -- `uninstallapp` only stops a generic app if the app has an `uninstall` - script (sourced, so no `exit`); the template has one + (blackboxregistrar.monitoreast.fedcom.net). Decided 2026-12-03: apps in + development aren't registered, so the installer writes no `MONITOR` +- `installapp` and `uninstallapp` run with `set -x`; the trace includes the + monitoring registrar's bearer token (in plain text in `lib/functions.sh`), + the Core's email addresses and the app's secrets. The installer keeps + their output in `/federated/logs/coreapps/` (mode 600) +- `uninstallapp` only stops a generic app if it has an `uninstall` script + (sourced, so no `exit`) +- `uninstallapp` makes Superpanel's catalog before the services folder is + deleted, so the installer makes it again afterwards +- Databases: the app's own user and database (`coreapp_`, because + PostgreSQL reserves `pg_*` and Federated's apps have their own names) on + the Core's PostgreSQL, made with `docker exec postgresql psql -U postgres` + as Federated's installers do. `postgresql.` resolves to the + container on the `core` network (Docker's DNS); outside it, it's the + public IP +- Sign-in: the OIDC client `coreapp-` goes in Authelia's + `idproviders.yml` between `### coreapp- begin/end` markers (secret + hashed with the running Authelia's `authelia crypto hash generate + pbkdf2`), checked with `authelia validate-config` before Authelia + restarts (the old file is put back if the check fails). `installapp`'s + `apply_authelia_2fa_policy` applies the Core's 2FA policy to it. The app + reaches `https://authelia.` through traefik (`extra_hosts` to + traefik's address; Federated's apps use the public IP, which here would + loop out through the relay) +- Image names must include the registry: `coreapp/x` means Docker Hub, so a + Core that had to pull it (after its boot-time prune, say) would get + whatever is published there. Dev images are `localhost/coreapp/`, + which can't be pulled -- Decided 2026-12-03: apps in development are not registered with - Federated's monitoring. `coreapp deploy` drops `MONITOR` from the copy of - `service` on the Core -- [ ] Document the app format fully in the README (done in each app's README) -Databases (2026-12-03): `coreapp new --postgres ` adds -`DEPENDS="postgresql"`, DB_* settings in `env.in` (random password), an -`install` that creates the user and database on the Core's PostgreSQL -(`docker exec postgresql psql -U postgres`, as Federated's own installers -do) and an `uninstall` that drops them, and a Python example (psycopg) -that counts visits. Tested with `guest-book`: deploy, the count goes up, -a redeploy and a reboot of the Core keep the data, remove drops the database -and user. `postgresql.` resolves to the PostgreSQL container on the -`core` network (Docker's DNS); outside it, it's the public IP. +### How Federated adds an app to every Core -Sign-in (2026-12-03): `coreapp new --sso `. Its `install` registers -the OIDC client `coreapp-` in Authelia's `idproviders.yml` between -`### coreapp- begin/end` markers (secret from `.env`, hashed with the -running Authelia's `authelia crypto hash generate pbkdf2`), checks the -result with `authelia validate-config`, restores the old file if that fails, -and restarts Authelia; `uninstall` removes the block. `installapp`'s -`apply_authelia_2fa_policy` then applies the Core's 2FA policy to it. -The app reaches `https://authelia.` through traefik -(`extra_hosts` to `@TRAEFIK_IP@`, which the template's `install` and -coreapp's redeploy both provide; Federated's apps use the public IP, which -here would loop out through the relay). The example is a standard-library -Python OIDC client (code flow with PKCE). -Tested with `sso-demo`: install, redeploy, remove and reinstall each leave -one (or no) client block, a valid config, and the other clients and -Nextcloud working; `/login` redirects to Authelia with PKCE. +From the Core repo's history, e.g. immich: +- The Core repo (`gitea.federated.computer/Federated_Computer/Core`) gets + `services//` in the generic format, with `CONTAINER` a public image + (most are on Docker Hub; Federated's own under `federatedcomputer/`) and + an `INTERNAL_IP` in 192.168.0.x not used by another app +- `lib/functions.sh`: the app goes into `EXTRA_APPS`, or `bin/start` and + `start all` won't start it +- `services/superpanel/tiers.json`: the tiers (good, better, best) that + include it +- Work happens on branches with pull requests into `master`; Cores run the + `release` branch, which `upgrade` pulls nightly -A real sign-in to sso-demo with a Core account in a browser worked -(2026-12-03, tested by David). -- `bin/stop` and `bin/start` don't know apps outside Federated's lists, so - when a dependency (postgresql, authelia) is upgraded, coreapp apps keep - running instead of being stopped and restarted; they reconnect -Both together (2026-12-03): overlays no longer replace `service`; each -names the Core apps it needs in `.depends`, merged into `DEPENDS`. The -sign-in code is a module (`oidc.py`) any example imports; -`templates/postgres-sso` is the combined example (sign-in, each person's -visits in PostgreSQL). Tested with `team-visits`: database, Authelia client -`coreapp-team-visits`, `DEPENDS="postgresql authelia"`, `/login` to Authelia. +## Coreapps: apps from the developer's own repository -Signing in to team-visits and sso-demo (with the oidc.py code) in a browser -worked (2026-12-03, tested by David). -- [ ] Later: apps published for other Cores (registry, submitting to - Federated) +Decided 2026-12-03 (David): a developer publishes an app to their own Gitea +repository. A Core's owner installs it in Superpanel, in a new Coreapps +screen (Superpanel doesn't have one yet), by giving the repository's URL. +A Claude Code skill helps developers make apps that use the Core's +services: Traefik, Authelia, PowerDNS (`.`), email and the AI +features. + +Rules that follow from it: +- An app from any URL must not run code as root on the Core. So the app's + repository has no `install` scripts or compose file: only `coreapp.toml`, + an image and an icon. The installer (`core/coreapps`, trusted, written by + us or Federated) checks the manifest and makes everything else from its + own templates. Values from the manifest go into shell-sourced and YAML + files, so each is limited to safe characters +- Images are built outside the Core (CI in the developer's Gitea, pushed to + its container registry); the Core only pulls `image:version` +- Each Core picks the app's address itself (192.168.200.10-250, free on + that Core) +- Apps live in `/federated/services//` with a `.coreapp` marker, so + Superpanel's catalog and the Core's `installapp`/`uninstallapp` see them. + That folder is Federated's git checkout; untracked folders survive + `git pull`, but a `git clean` would delete them. Ask Federated + +Steps: +1. Done 2026-12-03: `coreapp.toml` and the installer. `coreapp deploy` + puts the installer in `/opt/coreapps` on the Core and runs + `coreapps install`. Tested on dev.fedcom.net: new apps with no needs, + postgres, and postgres + sso (`trial-app`); updates (a new version, + adding a need, the three apps deployed before coreapp.toml); refusals + (Federated's app names, the Core's hostnames, dropping a need, bad + manifest values); remove (database, Authelia client, image and catalog + entry gone) + - [ ] David: sign in to `https://trial-app.dev.fedcom.net/` in a browser +2. [ ] Publishing: a Gitea Actions workflow in new apps that builds the image + on a version tag and pushes it to the repository's Gitea registry; and + `coreapp publish` for developers without a runner. Pin the image by + digest in what the Core installs? Private registries need a pull token +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 +4. [ ] Email and AI needs (findings below), then other services: PowerDNS + records beyond the wildcard, if an app needs other hostnames +5. [ ] The skill: a Claude Code skill in coreapp-dev (installed by + `update.sh`) that teaches `coreapp.toml`, the needs, the `coreapp` + commands and testing against the VM +6. [ ] The Coreapps screen in Superpanel (Federated's code: needs their + agreement). Until then, the installer could run as a small web app behind + Authelia, for admins only + +Later: +- [ ] Uninstalling a need without removing the app (now refused) +- [ ] `bin/start` / `bin/stop` don't know coreapps' apps (see "Tell + Federated"); `restart: always` covers reboots +- [ ] Trust: a list of reviewed apps, or signed releases, and a warning in + Superpanel for others +- [ ] Monitoring for published apps (dev apps aren't registered) + +### What the Core offers apps (studied 2026-12-03) + +Superpanel (`federatedcomputer/superpanel` 26.12.01, a Go binary, at +192.168.0.85; its `.env` has LDAP, SMTP, Authelia client and +`STORE_DB_URL`). Its AI features: +- `/ai/settings` (and `/models`): the LLM provider and model (Anthropic, + OpenAI, OpenRouter, custom), stored in Hermes's `.env` + (`HERMES_LLM_PROVIDER`, `HERMES_LLM_API_KEY`, `HERMES_LLM_MODEL`). The + AI Settings toggle runs `installapp hermes` +- `/ai/terminal` (`/stream`): a chat with Hermes, through Hermes's API + (`HERMES_API_URL=http://192.168.0.92:8642`, `/v1/chat/completions`, + bearer `HERMES_API_KEY`) +- `/api/mcp-apps`: which apps the AI can use; `/api/mcp/validate`: the + forward-auth check for `mcphub.`, with per-user tokens in + `superpanel/data/mcp_tokens` +- On dev.fedcom.net hermes and mcpserver aren't installed + +hermes (`nousresearch/hermes-agent`, 192.168.0.92, no traefik route): the +agent. It uses mcpserver-hub (`http://192.168.0.91:8080/sse`) for tools. + +mcpserver (`federatedcomputer/mcpserver` 1.8.8, 192.168.0.90 per-app +endpoints at `mcpserver.` with basic auth; mcpserver-hub at .91, +`mcphub.`, one endpoint for all apps, auth through Superpanel). It +only knows a fixed list of apps (`MCPSERVER_APPS` in `lib/mcpserver.sh`, +"keep in sync with APPS in the mcpserver image's entrypoint.py"): listmonk, +nextcloud, espocrm, baserow, bookstack, n8n, immich, gitea, plane, erpnext, +kimai, matomo, wordpress, vaultwarden. An app is linked with +`installapp-mcpserver `, which calls `config_mcpserver_` in the +app's lib file. So a coreapp can't offer tools to the AI today. + +What an `ai` need could be: +- The app offers tools: it serves MCP (streamable HTTP) on a path, and the + hub lists it. Needs mcpserver to accept a generic upstream (a URL and a + token per app) instead of its fixed list. Ask Federated +- The app uses the model: through Hermes's OpenAI-compatible API. But that + key is Superpanel's (full agent, all tools); an app would need its own, + limited key, or the provider's key, which is the owner's money. Decide + with Federated + +Email (docker-mailserver 16.0.1 at 192.168.0.16, accounts in LDAP): Core +apps send through `mail.:587` (STARTTLS) as `fcore` (or `admin`) +with the Core's admin password (`MAIL_PASSWORD=$ADMINPASS`, e.g. in +`lib/bookstack.sh`; `SMTPUSER` in `get_appvars`). A coreapp must not get +the admin password, so an `email` need has to create its own mail account +for the app (an LDAP user allowed to send as `@`). To study: +how `lib/mail.sh` and Superpanel create accounts. + +PowerDNS: `*.` already points every app hostname at the Core, and +traefik gets certificates through the DNS challenge, so apps need nothing +from PowerDNS for `.`. ## SDK packaging diff --git a/README.md b/README.md index 272e223..ef71bf0 100644 --- a/README.md +++ b/README.md @@ -50,29 +50,47 @@ coreapp deploy # build, copy to the Core, install (or update) coreapp check # https://my-app./ answers, valid certificate ``` -An app is a folder in the format Federated Core installs apps from -(`/federated/services//` on the Core): `service`, -`docker-compose.yml.in`, `env.in`, `install`, `uninstall`, `icon.png`, plus -the app's own `Dockerfile`. The README in each new app explains the files. +An app is a folder (its own git repository) with a `coreapp.toml`, a +`Dockerfile`, the app's code and an `icon.png`: + +```toml +name = "my-app" # https://my-app. +title = "My App" +image = "localhost/coreapp/my-app" # where the Core gets the image +version = "0.1.0" +port = 8080 # the port it serves HTTP on +health = "/" # a path that answers when it's up +needs = ["postgres", "sso"] # its own database; sign-in with Core accounts +``` + +The app has no scripts or compose file: the Core side is made by +coreapp-dev's installer, `coreapps` (`core/` here, `/opt/coreapps` on the +Core). It checks `coreapp.toml`, picks a free address on that Core, writes +the app in the Core's generic format (`/federated/services//`), and +sets up what it needs: the traefik route and certificate, its settings and +secrets, its database, its Authelia client. So what an app can do on a Core +is decided by the installer, not by whoever wrote the app. The README in +each new app explains the files and the settings it gets. | Command | Does | |---|---| -| `coreapp new ` | Make an app in `./`; it gets an address in 192.168.200.x on the Core | +| `coreapp new ` | Make an app in `./` | | `coreapp new --postgres ` | The same, with its own database on the Core's PostgreSQL (a Python example app that uses it) | | `coreapp new --sso ` | The same, with sign-in through the Core's Authelia (OpenID Connect; a Python example app) | | `coreapp new --postgres --sso ` | Both: a database and sign-in (the example counts each person's visits) | -| `coreapp deploy` | Build its image, copy it to the Core over SSH, install it, or update it keeping its `.env` | -| `coreapp check` | It answers at its `MONITOR` URL with a valid certificate | +| `coreapp deploy` | Build its image, copy it to the Core over SSH, install it, or update it keeping its settings and data | +| `coreapp check` | It answers at `https://.` with a valid certificate | | `coreapp status` / `logs [-f]` / `shell` | Its container, its log, a shell in it | -| `coreapp remove` | Uninstall it from the Core (asks first) | +| `coreapp list` | The apps on the Core installed this way | +| `coreapp remove` | Uninstall it from the Core, with its database and sign-in client (asks first) | `COREAPP_VM` picks the VM (default `coreserver`). -Installing and removing an app go through the Core's own `installapp` and -`uninstallapp`. Those would also add its `MONITOR` URL to Federated's -external monitoring, so `coreapp deploy` copies `service` to the Core without -the `MONITOR` line: apps in development aren't monitored. `coreapp check` -uses the line from your folder. +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. +The Core's scripts print secrets in their traces; their output is kept in +`/federated/logs/coreapps/` on the Core. ## VM commands @@ -110,8 +128,11 @@ stay installed. | `libvirt/network-hook.sh` | NAT and firewall rules for the `coreapp` network | | `bin/coreapp-vm` | Creates and manages CoreServer VMs (`coreapp-vm help`) | | `bin/coreapp` | Makes, deploys and tests apps (`coreapp help`) | +| `core/coreapps` | The installer that runs on the Core (`coreapps help`) | +| `core/templates/` | The Core's generic app files it makes from `coreapp.toml` | +| `core/needs//` | What each need adds: `env.in` (settings), `setup` and `teardown` (run on the Core), `depends` (the Core app it uses), `compose` (added to the container) | | `templates/app/` | What `coreapp new` starts from | -| `templates/postgres/`, `templates/sso/` | Laid over it by `--postgres` / `--sso`: their files replace the base's; `*.append` files are added to the base file, `.remove` lists base files to drop, `.depends` the Core apps it needs (merged into `DEPENDS`) | +| `templates/postgres/`, `templates/sso/` | Example apps laid over it by `--postgres` / `--sso`: their files replace the base's; `*.append` files are added to the base file, `.remove` lists base files to drop, `.needs` goes into `needs` | | `templates/postgres-sso/` | The example app when both are used | | `uninstall.sh` | Removes what coreapp-dev set up | | [PLAN.md](PLAN.md), [TEST.md](TEST.md) | What's next, and how to test it | diff --git a/TEST.md b/TEST.md index 72e2b33..3d5f231 100644 --- a/TEST.md +++ b/TEST.md @@ -10,6 +10,7 @@ a temporary folder. Run these on a machine or VM you don't mind changing. cd ~/Projects/coreapp-dev for f in install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh; do bash -n "$f"; done shellcheck -x install.sh update.sh uninstall.sh bin/coreapp-vm bin/coreapp libvirt/network-hook.sh +python3 -m py_compile core/coreapps && rm -rf core/__pycache__ ``` ## install.sh @@ -140,77 +141,123 @@ On a machine you can rebuild (it removes the network every VM uses): `~/.config/coreapp-dev`. 4. `bash install.sh` puts everything back. +## The installer (coreapps), off the Core + +`coreapps manifest ` checks a `coreapp.toml` without a Core. With a +folder holding a valid one (`coreapp new x` makes one), each of these +changes is refused with a message saying what's allowed, and exit 1: + +- `port = "8080"` (a string), `port = 0` +- `image = "coreapp/x"` (no registry, which would mean Docker Hub) +- `title = "A $(reboot)"`, a `description` with `"` or `` ` `` +- `name = "x-"`, `name = "X"`, `name = "mail"` (one of the Core's hostnames) +- an unknown setting (`extra = 1`), `needs = ["redis"]` +- a missing `version` + +`needs = ["sso", "postgres"]` is accepted and printed in setup order +(`needs=postgres sso`). `coreapps plan ` off the Core (not root) says +to run it as root on the Core. + ## Apps (coreapp) Against a Core in the VM (`coreapp-vm list` shows it running). These install -a test app on that Core. It must not be registered with Federated's -monitoring: `/federated/services/hello/service` on the Core has no -`MONITOR` line, and `~/.local/share/coreapp-dev/logs/hello-install.log` has -no `blackboxregistrar` request. +test apps on that Core. None may be registered with Federated's monitoring: +the generated `/federated/services//service` has no `MONITOR` line. +The Core's own scripts trace secrets, so their output goes to +`/federated/logs/coreapps/-.log` on the Core +(folder mode 700, files 600), never to the terminal unless a step fails. -1. `cd $(mktemp -d) && coreapp new hello`: `./hello` has `service`, +1. `cd $(mktemp -d) && coreapp new hello`: `./hello` has `coreapp.toml`, + `Dockerfile`, `.dockerignore`, `icon.png`, `www/`, `README.md` and + nothing else, with no `{{...}}` left (`grep -r '{{' hello` prints + nothing). `coreapp new hello` again refuses; so does `coreapp new x-`. +2. `cd hello && coreapp deploy`: updates `/opt/coreapps` on the Core, + builds, copies the image, prints `Installing hello at 192.168.200.x` + (the first free address there) and `Installed: https://hello./`. + On the Core, `/federated/services/hello/` has `service`, `docker-compose.yml.in`, `env.in`, `install`, `uninstall`, `icon.png`, - `Dockerfile`, `www/`, `README.md`, with no `{{...}}` left - (`grep -r '{{' hello` prints nothing). `coreapp new hello` again refuses. - `~/.local/share/coreapp-dev/app-addresses` has `hello 192.168.200.x`. -2. `cd hello && coreapp deploy`: builds, copies the image, installs, - prints `Deployed: https://hello./`. On the Core, - `/federated/apps/hello/.env` is root's, mode 600, with `IMAGE_VERSION` - equal to `VERSION` and a random `APP_SECRET`. + `coreapp.toml` and `.coreapp` (`needs=`); `/federated/apps/hello/.env` + is root's, mode 600, with `IMAGE_VERSION` equal to `version` and a + random `APP_SECRET`. Superpanel's catalog + (`/federated/apps/superpanel/data/catalog.json`) lists `hello`. 3. `coreapp check`: `OK: HTTP 200, valid certificate.` (the first certificate can take a minute). -4. Change `www/index.html`, `coreapp deploy`: says "Updating it...", the - container is recreated, the page shows the change, `APP_SECRET` is +4. Change `www/index.html`, `coreapp deploy`: "Updating hello to 0.1.0", + the container is recreated, the page shows the change, `.env` is unchanged. `coreapp deploy` again: "The Core already has this image." -5. `coreapp status`, `coreapp logs`, `coreapp shell` (exit with `exit`). -6. `coreapp remove`, answering y: on the Core, `/federated/apps/hello`, - `/federated/services/hello`, the container and the `coreapp/hello` - image are gone. Nothing from `uninstallapp`'s trace is printed; it's in - `~/.local/share/coreapp-dev/logs/hello-remove.log` (mode 600). -7. Collisions: an app named like one of Federated's (`coreapp new nextcloud`, - deploy) is refused; so is an `INTERNAL_IP` another container uses. +5. Raise `version` to 0.2.0, `coreapp deploy`: "Updated"; the container + runs `:0.2.0`; `docker image ls localhost/coreapp/hello` on the Core lists + only 0.2.0. +6. `coreapp status` (address and port), `coreapp logs`, `coreapp shell` + (exit with `exit`), `coreapp list` (all apps installed by coreapps). +7. `coreapp remove`, answering y: on the Core, `/federated/apps/hello`, + `/federated/services/hello`, the container and the image are gone, and + the catalog no longer lists `hello`. +8. Refused, with nothing changed on the Core: + - `name = "nextcloud"` (one of Federated's apps) or `name = "mail"` + - `image = "localhost/coreapp/nope"` with no such image on the Core + (change `image`, and skip coreapp's build by running + `coreapp-vm ssh /opt/coreapps/coreapps install ` on a copy) + - with the app installed with `needs = ["postgres"]`, deploying with + `needs = []` ("drops needs postgres") +9. On a Core whose tier isn't enterprise, deploying a new app asks before + it's recorded as an add-on; answering no deploys nothing. ### With a database 1. `coreapp new --postgres guest-book`: has `app.py`, no `www/`; - `service` has `DEPENDS="postgresql"`; `env.in` has `DB_NAME=coreapp_guest_book` - and a random `DB_PASSWORD`; the README has a Database section. + `coreapp.toml` has `needs = ["postgres"]` and `health = "/health"`; the + README has a Database section. 2. `coreapp deploy`, `coreapp check`. Loading the page several times (`curl -s https://guest-book./ | grep visits`) counts up. On the Core, `docker exec postgresql psql -U postgres -l` lists `coreapp_guest_book`, - owned by `coreapp_guest_book`. + owned by `coreapp_guest_book`; `.env` has `DB_*`. 3. Change `app.py`, `coreapp deploy`: the change shows, the count continues. 4. `virsh -c qemu:///system reboot coreserver`: once the Core is up, the app answers and the count continues (its log may show "Waiting for the database" first). 5. `coreapp remove`: the `coreapp_guest_book` database and user are gone too. +Adding a need later: install `coreapp new notes` (no needs), then set +`needs = ["postgres"]` and deploy: "Updating", `.env` gains `DB_*` (the +other values unchanged), the database `coreapp_notes` exists, the container +has the `DB_*` variables, `.coreapp` says `needs=postgres`. + ### With sign-in -1. `coreapp new --sso sso-demo`: has `app.py`, no `www/`; `service` has - `DEPENDS="authelia"`; `docker-compose.yml.in` has `extra_hosts` with - `@TRAEFIK_IP@`; `env.in` has `OIDC_*`; `app.py` and `oidc.py`; the README - has a Sign-in section. +1. `coreapp new --sso sso-demo`: has `app.py` and `oidc.py`, no `www/`; + `needs = ["sso"]`; the README has a Sign-in section. 2. `coreapp deploy`, `coreapp check`. On the Core, `idproviders.yml` has one `### coreapp-sso-demo begin` block; Authelia is healthy; `docker exec authelia authelia validate-config` is OK; no `*.bak` is - left; the rendered compose file maps `authelia.` to traefik's - address. + left; `/federated/apps/sso-demo/docker-compose.yml` maps + `authelia.` to traefik's address (`extra_hosts`). 3. `https://sso-demo./login` redirects to `https://authelia./api/oidc/authorization?...client_id=coreapp-sso-demo...code_challenge_method=S256`. 4. In a browser, sign in with a Core account: the page says "Signed in as ..." with the account's email and groups. "Sign out" goes back to the sign-in link. -5. Redeploy: still one client block. `coreapp remove`: none, Authelia - healthy, other clients (Nextcloud) still work. Deploy again: one block. +5. Redeploy: still one client block, and Authelia isn't restarted + (`docker inspect -f '{{.State.StartedAt}}' authelia` unchanged). + `coreapp remove`: no block, Authelia healthy, other clients (Nextcloud) + still work. Deploy again: one block. ### With both -1. `coreapp new --postgres --sso team-visits`: `service` has - `DEPENDS="postgresql authelia"`; `env.in` has `DB_*` and `OIDC_*`; - `install` creates the database and registers the client; `uninstall` - undoes both; `app.py` imports `oidc` and `psycopg`. -2. `coreapp deploy`, `coreapp check`. In a browser, sign in: the page shows - your name and "Your visits", which counts up on reload. Another account - gets its own count; "people who have visited" counts both. +1. `coreapp new --postgres --sso team-visits`: `needs = ["postgres", + "sso"]`; `app.py` imports `oidc` and `psycopg`. +2. `coreapp deploy`, `coreapp check`. On the Core, `service` has + `DEPENDS="postgresql authelia"`, `.env` has `DB_*` and `OIDC_*`. In a + browser, sign in: the page shows your name and "Your visits", which + counts up on reload. Another account gets its own count; "people who have + visited" counts both. 3. `coreapp remove`: the database, user and Authelia client are gone. + +### Apps deployed before coreapp.toml + +An app deployed by an older coreapp (its own `service`, `install`, ... and +an empty `.coreapp` marker on the Core) moves over by replacing those files +with a `coreapp.toml` with the same name, image and needs. `coreapp deploy` +then updates it: same address, `.env` and data unchanged, no needs set up +again (they're read from its `DEPENDS`), Authelia not restarted; `.coreapp` +then says which needs it has. diff --git a/bin/coreapp b/bin/coreapp index 9764988..3bc1e65 100755 --- a/bin/coreapp +++ b/bin/coreapp @@ -12,26 +12,23 @@ # coreapp logs [-f] its log # coreapp shell a shell in its container # coreapp remove uninstall it from the Core (asks first) +# coreapp list the apps on the Core installed this way # -# Run everything but `new` in the app's folder. COREAPP_VM picks the VM -# (default coreserver). +# Run everything but `new` and `list` in the app's folder (the one with +# coreapp.toml). COREAPP_VM picks the VM (default coreserver). set -euo pipefail SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" TEMPLATES="$(dirname "$SELF_DIR")/templates" TEMPLATE="$TEMPLATES/app" +# The installer that runs on the Core (coreapps), and where it goes there +INSTALLER="$(dirname "$SELF_DIR")/core" +REMOTE_INSTALLER=/opt/coreapps DATA="$HOME/.local/share/coreapp-dev" -# The INTERNAL_IP given to each app made on this machine: "name ip" lines -ADDRESSES="$DATA/app-addresses" -# Apps get addresses here, away from Federated's apps in 192.168.0.x (both -# are in the Core's 192.168.0.0/16 network) -PREFIX=192.168.200 SSH_KEY="$DATA/ssh/id_ed25519" KNOWN_HOSTS="$DATA/ssh/known_hosts" VM="${COREAPP_VM:-coreserver}" -# What the Core installs an app from; the rest of the folder stays here -CORE_FILES=(service docker-compose.yml.in env.in install uninstall icon.png timers services upgrade) die() { echo "$*" >&2; exit 1; } @@ -77,45 +74,57 @@ core_domain() { # --- The app in the current folder --------------------------------------- -# NAME is the app's id (its folder on the Core); TITLE is NAME in service -NAME="" TITLE="" CONTAINER="" VERSION="" INTERNAL_IP="" MONITOR="" HIDDEN="" PORTS="" +# From coreapp.toml, as checked by the installer +NAME="" TITLE="" VERSION="" IMAGE="" PORT="" HEALTH="" NEEDS="" load_app() { - [[ -f service && -f install ]] \ - || die "No app here: run this in an app's folder (one with service and install), or make one with coreapp new ." - # service is shell variables, as the Core reads it - set +u - # shellcheck source=/dev/null - . ./service - set -u - TITLE="$NAME" - NAME="$(sed -n 's/^installGeneric[[:space:]]\{1,\}\([a-z0-9-]*\).*/\1/p' install | head -n 1)" - [[ -n "$NAME" ]] || die "install doesn't say which app it is (installGeneric )." - [[ -n "$CONTAINER" && -n "$VERSION" && -n "$INTERNAL_IP" ]] \ - || die "service needs CONTAINER, VERSION and INTERNAL_IP." + local values key value + [[ -f coreapp.toml ]] \ + || die "No app here: run this in an app's folder (one with coreapp.toml), or make one with coreapp new ." + values="$(python3 "$INSTALLER/coreapps" manifest .)" || exit 1 + while IFS='=' read -r key value; do + case "$key" in + name) NAME="$value" ;; + title) TITLE="$value" ;; + version) VERSION="$value" ;; + image) IMAGE="$value" ;; + port) PORT="$value" ;; + health) HEALTH="$value" ;; + needs) NEEDS="$value" ;; + esac + done <<< "$values" init_core } -image() { echo "$CONTAINER:$VERSION"; } +image() { echo "$IMAGE:$VERSION"; } + +# Put the installer on the Core, as this coreapp-dev has it +sync_installer() { + tar -C "$INSTALLER" --exclude=__pycache__ --exclude=.claude -cf - . | core " + set -e + rm -rf $REMOTE_INSTALLER.new && mkdir -p $REMOTE_INSTALLER.new + tar --no-same-owner -xf - -C $REMOTE_INSTALLER.new + rm -rf $REMOTE_INSTALLER && mv $REMOTE_INSTALLER.new $REMOTE_INSTALLER" +} + +# Run the installer on the Core with this app's coreapp.toml and icon.png, +# copied to a temporary folder there: coreapps [options] +installer() { + local files=(coreapp.toml) + [[ -f icon.png ]] && files+=(icon.png) + tar -cf - "${files[@]}" | core " + d=\$(mktemp -d) && tar --no-same-owner -xf - -C \$d || exit 1 + $REMOTE_INSTALLER/coreapps $* \$d; status=\$? + rm -rf \$d; exit \$status" +} # --- new -------------------------------------------------------------------- -next_address() { - local n - for n in $(seq 10 250); do - if ! grep -qs " $PREFIX\.$n\$" "$ADDRESSES"; then - echo "$PREFIX.$n" - return - fi - done - die "All addresses in $PREFIX.10-250 are taken (see $ADDRESSES)." -} - # Lay an overlay over the app in $1: its files replace the app's, except # *.append (added to the end of the app's file), .remove (app files it -# doesn't use) and .depends (apps it needs, for DEPENDS in service) +# doesn't use) and .needs (what it needs from the Core, for coreapp.toml) apply_overlay() { local app="$1" overlay="$2" f - tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude=.depends \ + tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude=.needs \ --exclude='*.append' -cf - . | tar -C "$app" -xf - for f in "$overlay"/*.append; do [[ -e "$f" ]] && cat "$f" >> "$app/$(basename "$f" .append)" @@ -126,7 +135,7 @@ apply_overlay() { } cmd_new() { - local name="" postgres="" sso="" title ip dbname f depends="" what="" + local name="" postgres="" sso="" title dbname f needs="" what="" local overlays=() while [[ $# -gt 0 ]]; do case "$1" in @@ -139,8 +148,8 @@ cmd_new() { done [[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE" [[ -n "$name" ]] || die "Usage: coreapp new [--postgres] [--sso] (lowercase letters, digits and -)" - [[ "$name" =~ ^[a-z][a-z0-9-]{1,30}$ ]] \ - || die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter. It becomes https://$name.." + [[ "$name" =~ ^[a-z]([a-z0-9-]{0,29}[a-z0-9])$ ]] \ + || die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter and not ending with -. It becomes https://$name.." [[ ! -e "$name" ]] || die "./$name already exists." # In this order; with both, the combined example app goes on top @@ -151,15 +160,7 @@ cmd_new() { [[ -d "$f" ]] || die "The template $f is missing." done - ip="$(grep -s "^$name " "$ADDRESSES" | cut -d' ' -f2 || true)" - if [[ -z "$ip" ]]; then - ip="$(next_address)" - mkdir -p "$DATA" - echo "$name $ip" >> "$ADDRESSES" - fi - # "my-app" -> "My App". Database names: no "-", and a prefix, because - # PostgreSQL reserves names starting with pg_ and Federated's apps have - # their own databases (nextcloud, superpanel, ...) + # "my-app" -> "My App". The database name is the installer's (coreapps) title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')" dbname="coreapp_${name//-/_}" @@ -167,61 +168,47 @@ cmd_new() { tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf - for f in "${overlays[@]}"; do apply_overlay "$name" "$f" - [[ -f "$f/.depends" ]] && depends="$depends $(cat "$f/.depends")" + [[ -f "$f/.needs" ]] && needs="$needs, \"$(cat "$f/.needs")\"" done - depends="${depends# }" - sed -i "s/^DEPENDS=.*/DEPENDS=\"$depends\"/" "$name/service" + sed -i "s/^needs = .*/needs = [${needs#, }]/" "$name/coreapp.toml" + # The example apps with a database or sign-in have a /health path + [[ ${#overlays[@]} -gt 0 ]] && sed -i 's|^health = .*|health = "/health"|' "$name/coreapp.toml" while IFS= read -r -d '' f; do - sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{IP}}/$ip/g" \ - -e "s/{{DBNAME}}/$dbname/g" "$f" + sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{DBNAME}}/$dbname/g" "$f" done < <(find "$name" -type f ! -name '*.png' -print0) - [[ -n "$postgres" ]] && what=", database $dbname" - [[ -n "$sso" ]] && what="$what, sign-in through Authelia" - echo "Made $title in ./$name (address on the Core: $ip$what)." + [[ -n "$postgres" ]] && what=", with a database" + [[ -n "$sso" ]] && what="$what, with sign-in through Authelia" + echo "Made $title in ./$name$what." echo "Next: cd $name && coreapp deploy" } # --- deploy ----------------------------------------------------------------- cmd_deploy() { - local domain info state theirs tier used local_id core_id f log files=() + local plan state tier answer local_id core_id addon="" load_app - domain="$(core_domain)" - # What the Core has: is the app installed, is the name or address taken? - info="$(core " - . /etc/federated - echo \"tier \$TIER\" - [ -d /federated/apps/$NAME ] && echo installed || echo new - if [ -f /federated/services/$NAME/service ]; then - echo \"theirs \$(sed -n 's/^CONTAINER=//p' /federated/services/$NAME/service)\" - fi - docker network inspect core -f '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{println}}{{end}}' \ - | grep ' $INTERNAL_IP/' | sed 's/^/used /' || true - ")" - tier="$(sed -n 's/^tier //p' <<< "$info")" - state="$(grep -xE 'installed|new' <<< "$info")" - theirs="$(sed -n 's/^theirs //p' <<< "$info")" - used="$(sed -n 's/^used \([^ ]*\) .*/\1/p' <<< "$info" | grep -vx "$NAME" || true)" - - if [[ -n "$theirs" && "$theirs" != "$CONTAINER" ]]; then - die "The Core already has an app called '$NAME' ($theirs). Pick another name." - fi - if [[ -n "$used" ]]; then - die "$INTERNAL_IP is already used on the Core by: $used. Change INTERNAL_IP in service (and docker-compose.yml.in)." - fi - if [[ "$state" == new && "${tier,,}" != enterprise && "$HIDDEN" != true ]]; then + echo "Updating the installer on the Core ($REMOTE_INSTALLER)..." + sync_installer + # What installing would do (and whether the Core refuses it: name taken...) + plan="$(installer plan)" || exit 1 + state="$(sed -n 's/^state=//p' <<< "$plan")" + tier="$(sed -n 's/^tier=//p' <<< "$plan")" + if grep -qx 'addon=yes' <<< "$plan"; then echo "This Core's tier is '$tier'. Installing records '$NAME' as an add-on app" echo "(ADDON_APPS in /etc/federated), which Federated may bill for." - read -r -p "Install anyway? [y/N] " f - [[ "$f" =~ ^[Yy] ]] || die "Not deployed. HIDDEN=true in service keeps an app off that list." + read -r -p "Install anyway? [y/N] " answer + [[ "$answer" =~ ^[Yy] ]] || die "Not deployed." + addon=--addon-ok fi echo "Building $(image)..." docker build -q -t "$(image)" . > /dev/null + # localhost/ images exist only where they're copied; others the Core can + # pull, but while developing, the one just built is the one to test local_id="$(docker image inspect -f '{{.Id}}' "$(image)")" core_id="$(core "docker image inspect -f '{{.Id}}' $(image) 2> /dev/null || true")" if [[ "$local_id" != "$core_id" ]]; then @@ -231,82 +218,21 @@ cmd_deploy() { echo "The Core already has this image." fi - echo "Copying the app to /federated/services/$NAME..." - for f in "${CORE_FILES[@]}"; do [[ -e "$f" ]] && files+=("$f"); done - tar -cf - "${files[@]}" | core " - set -e - d=/federated/services/$NAME - rm -rf \$d.new && mkdir -p \$d.new && tar --no-same-owner -xf - -C \$d.new - # No MONITOR on the Core: installapp would register it with Federated's - # external monitoring, which apps in development shouldn't be in - sed -i '/^MONITOR=/d' \$d.new/service - rm -rf \$d && mv \$d.new \$d" - - if [[ "$state" == new ]]; then - echo "Installing it (the Core's installapp)..." - mkdir -p "$DATA/logs" - log="$DATA/logs/$NAME-install.log" - # installapp traces what it runs, tokens included: keep that private - : > "$log" && chmod 600 "$log" - if ! core "/federated/bin/installapp -n $NAME" > "$log" 2>&1; then - tail -n 20 "$log" >&2 - die "installapp failed (whole log: $log)." - fi - # installapp's start step only knows Federated's own apps (the list in - # /federated/lib/functions.sh), so start it the way the Core does - core "docker compose -f /federated/apps/$NAME/docker-compose.yml -p $NAME up -d 2>&1 | grep -v '^ *Container ' || true" - else - # Keep .env (its random secrets); redo the compose file, which may have - # changed, and the version - echo "Updating it..." - core " - set -e - cd /federated - . /etc/federated - . lib/helpers.sh - . services/$NAME/service - # The same extra values the template's install provides - TRAEFIK_IP=\"\$(sed -n 's/^INTERNAL_IP=//p' services/traefik/service)\" - templatize services/$NAME/docker-compose.yml.in > apps/$NAME/docker-compose.yml - sed -i 's/^IMAGE_VERSION=.*/IMAGE_VERSION=$VERSION/' apps/$NAME/.env - docker compose -f apps/$NAME/docker-compose.yml -p $NAME up -d --remove-orphans 2>&1 | grep -v '^ *Container .* Running\$' || true" - fi - - if [[ "$(core "docker inspect -f '{{.State.Status}}' $NAME 2> /dev/null || true")" != running ]]; then - core "docker logs --tail 20 $NAME 2>&1" >&2 || true - die "$NAME isn't running on the Core (its log is above, if it has one)." - fi - # Running isn't answering: wait until it answers on its own address and - # port (PORTS in service), from the Core, as traefik reaches it - if [[ -n "$PORTS" ]]; then - echo -n "Waiting for it to answer on $INTERNAL_IP:${PORTS%% *}..." - if ! core "for i in \$(seq 1 30); do - curl -s -o /dev/null --max-time 2 http://$INTERNAL_IP:${PORTS%% *}/ && exit 0 - sleep 2 - done; exit 1"; then - echo - core "docker logs --tail 20 $NAME 2>&1" >&2 || true - die "$NAME runs but doesn't answer on port ${PORTS%% *} after a minute (its log is above)." - fi - echo " it does." - fi - echo "Deployed: https://$NAME.$domain/ (coreapp check tests it)" + # Install, or update (which recreates the container if the image changed, + # even under the same version) + installer install $addon || exit 1 + [[ "$state" == new ]] && echo "(coreapp check tests it from the internet.)" + return 0 } # --- check, status, logs, shell, remove ------------------------------------ cmd_check() { - local domain url expect result code verify tries=24 + local domain url result code verify tries=24 load_app domain="$(core_domain)" - url="https://$NAME.$domain/" - expect="http_2xx" - if [[ -n "$MONITOR" ]]; then - url="${MONITOR%%|*}" - url="${url//@DOMAIN@/$domain}" - [[ "$MONITOR" == *"|"* ]] && expect="${MONITOR#*|}" - fi - echo "Checking $url (expecting $expect)..." + url="https://$NAME.$domain$HEALTH" + echo "Checking $url (expecting HTTP 2xx and a valid certificate)..." # A new app's certificate can take a minute: traefik gets it from Let's # Encrypt through the Core's DNS while true; do @@ -335,8 +261,9 @@ cmd_status() { domain="$(core_domain)" core "docker ps -a --filter name='^$NAME\$' --format 'Container: {{.Names}} {{.Status}} image {{.Image}}' [ -n \"\$(docker ps -aq --filter name='^$NAME\$')\" ] || echo 'Not installed on the Core.'" - echo "App: $TITLE $VERSION ($CONTAINER)" - echo "Address on the Core: $INTERNAL_IP" + echo "App: $TITLE $(image)" + echo "Address on the Core: $(core "sed -n 's/^INTERNAL_IP=//p' /federated/services/$NAME/service 2> /dev/null"), port $PORT" + echo "Needs: ${NEEDS:-nothing}" echo "URL: https://$NAME.$domain/" } @@ -355,25 +282,20 @@ cmd_shell() { } cmd_remove() { - local answer log + local answer load_app echo "This uninstalls $NAME from the Core in '$VM', with its settings and data" - echo "there. This folder stays as it is." + echo "there${NEEDS:+ (and what it has in: $NEEDS)}. This folder stays as it is." read -r -p "Remove it? [y/N] " answer [[ "$answer" =~ ^[Yy] ]] || die "Not removed." - mkdir -p "$DATA/logs" - log="$DATA/logs/$NAME-remove.log" - # uninstallapp traces what it runs, tokens included: keep that private - : > "$log" && chmod 600 "$log" - if ! core " - set -e - if [ -d /federated/apps/$NAME ]; then /federated/bin/uninstallapp $NAME; fi - rm -rf /federated/services/$NAME - docker image ls -q '$CONTAINER' | xargs -r docker image rm -f" > "$log" 2>&1; then - tail -n 20 "$log" >&2 - die "Removing failed (whole log: $log)." - fi - echo "Removed $NAME from the Core." + sync_installer + core "$REMOTE_INSTALLER/coreapps remove $NAME" +} + +cmd_list() { + init_core + sync_installer + core "$REMOTE_INSTALLER/coreapps list" } cmd="${1:-help}" @@ -386,6 +308,7 @@ case "$cmd" in logs) cmd_logs "$@" ;; shell) cmd_shell ;; remove | rm) cmd_remove ;; + list | ls) cmd_list ;; help | -h | --help) usage ;; *) usage >&2; exit 1 ;; esac diff --git a/core/coreapps b/core/coreapps new file mode 100755 index 0000000..236a020 --- /dev/null +++ b/core/coreapps @@ -0,0 +1,541 @@ +#!/usr/bin/env python3 +"""Install apps described by a coreapp.toml on this Federated Core. + +Runs on the Core as root (coreapp-dev puts it in /opt/coreapps). An app is +a coreapp.toml, an icon.png and an image: the app's repository has no +scripts or compose file of its own. This program checks the manifest and +makes the Core's generic app format (/federated/services//) from its +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] install the app, or update it +coreapps remove uninstall an app installed by coreapps +coreapps list the apps installed by coreapps + +`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 json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import time +import tomllib +import urllib.error +import urllib.request + +HERE = os.path.dirname(os.path.realpath(__file__)) +TEMPLATES = os.path.join(HERE, "templates") +NEEDS_DIR = os.path.join(HERE, "needs") +FEDERATED = "/federated" +SERVICES = FEDERATED + "/services" +APPS = FEDERATED + "/apps" +LOGS = FEDERATED + "/logs/coreapps" +# Marks a services folder as made by coreapps (and holds what it set up) +MARKER = ".coreapp" +# Addresses for apps, away from Federated's 192.168.0.x (all in the core +# network's 192.168.0.0/16) +PREFIX = "192.168.200." +FIRST, LAST = 10, 250 +# Hostnames on the Core that aren't apps in /federated/services or lib +RESERVED = {"www", "mail", "ns1", "ns2", "autodiscover", "autoconfig", + "panel", "dashboard", "mcphub", "api", "admin"} +# What an app can ask for, in the order they're set up +NEEDS = ["postgres", "sso"] + +# What coreapp.toml may contain. Values end up in shell-sourced and YAML +# files on the Core, so each is limited to characters that are safe there. +FIELDS = { + "name": r"[a-z](?:[a-z0-9-]{0,29}[a-z0-9])", + "title": r"[A-Za-z0-9][A-Za-z0-9 .,!?()&+_-]{0,39}", + "description": r"[^\"$`\\@\x00-\x1f\x7f]{0,200}", + "version": r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}", + # The registry is part of the name (localhost/... for images that only + # exist on this Core), so it's never Docker Hub by accident + "image": (r"(?:localhost|[a-z0-9-]+(?:\.[a-z0-9-]+)+)(?::[0-9]{1,5})?" + r"(?:/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+"), + "port": None, + "health": r"/[A-Za-z0-9._~/-]{0,100}", + "docs": r"(?:https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~/%+-]*)?)?", + "needs": None, +} +REQUIRED = ["name", "title", "version", "image", "port"] + + +class Refused(Exception): + """The app can't be installed as it is; the message says why.""" + + +def say(*args): + print(*args, flush=True) + + +# --- coreapp.toml ------------------------------------------------------------- + +def read_manifest(folder): + """coreapp.toml in folder, checked, with defaults filled in.""" + path = os.path.join(folder, "coreapp.toml") + try: + with open(path, "rb") as f: + data = tomllib.load(f) + except FileNotFoundError: + raise Refused(f"No coreapp.toml in {folder}.") + except tomllib.TOMLDecodeError as e: + raise Refused(f"coreapp.toml isn't valid TOML: {e}") + + unknown = sorted(set(data) - set(FIELDS)) + if unknown: + raise Refused(f"coreapp.toml: unknown setting(s) {', '.join(unknown)} " + f"(it knows {', '.join(FIELDS)}).") + missing = [k for k in REQUIRED if k not in data] + if missing: + raise Refused(f"coreapp.toml needs {', '.join(missing)}.") + + m = {"description": "", "health": "/", "docs": "", "needs": []} + for key, value in data.items(): + if key == "port": + if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= 65535: + raise Refused("coreapp.toml: port must be a number from 1 to 65535.") + elif key == "needs": + if not isinstance(value, list) or not all(isinstance(v, str) for v in value): + raise Refused('coreapp.toml: needs must be a list, like needs = ["postgres", "sso"].') + bad = [v for v in value if v not in NEEDS] + if bad: + raise Refused(f"coreapp.toml: needs: unknown {', '.join(bad)} " + f"(it knows {', '.join(NEEDS)}).") + value = [n for n in NEEDS if n in value] + else: + if not isinstance(value, str) or not re.fullmatch(FIELDS[key], value): + raise Refused(f"coreapp.toml: {key} = {value!r} isn't allowed. " + + HINTS.get(key, "")) + m[key] = value + if m["name"] in RESERVED: + raise Refused(f"'{m['name']}' is one of the Core's own hostnames. Pick another name.") + m["dbname"] = "coreapp_" + m["name"].replace("-", "_") + return m + + +HINTS = { + "name": "Use 2-31 lowercase letters, digits and -, starting with a letter " + "and not ending with -. It becomes https://..", + "title": "Up to 40 letters, digits, spaces and . , ! ? ( ) & + _ -", + "description": "Up to 200 characters, without \" $ ` \\ @ or line breaks.", + "version": "Letters, digits, . _ and - (it's the image's tag).", + "image": "Include the registry: localhost/coreapp/ for an image you " + "copy to the Core, or e.g. gitea.example.com/owner/.", + "health": "A path, like /health.", + "docs": "An https:// address.", +} + + +# --- This Core ------------------------------------------------------------------ + +def run(cmd, **kw): + return subprocess.run(cmd, text=True, capture_output=True, **kw) + + +def federated_settings(): + """/etc/federated's values (it's shell, so let bash read it).""" + out = run(["bash", "-c", '. /etc/federated; echo "$DOMAIN"; echo "$TIER"']) + if out.returncode != 0: + raise Refused("This isn't a Federated Core (no /etc/federated).") + domain, tier = (out.stdout.splitlines() + ["", ""])[:2] + return domain, tier + + +def service_value(path, key): + """A value from a generic app's service file, without running it.""" + try: + with open(path) as f: + for line in f: + m = re.match(rf'{key}=(["\']?)(.*)\1\s*$', line.strip()) + if m: + return m.group(2) + except OSError: + pass + return "" + + +def is_ours(name): + folder = os.path.join(SERVICES, name) + if os.path.exists(os.path.join(folder, MARKER)): + return True + return False + + +def marker_needs(name): + """What coreapps set up for an installed app (from its marker).""" + folder = os.path.join(SERVICES, name) + try: + with open(os.path.join(folder, MARKER)) as f: + for line in f: + if line.startswith("needs="): + return line.split("=", 1)[1].split() + except OSError: + return [] + # Folders deployed before coreapp.toml: tell from DEPENDS + depends = service_value(os.path.join(folder, "service"), "DEPENDS").split() + return [n for n in NEEDS if read_text(NEEDS_DIR, n, "depends").strip() in depends] + + +def used_addresses(): + used = set() + out = run(["docker", "network", "inspect", "core", "-f", + "{{range .Containers}}{{.IPv4Address}} {{end}}"]) + for cidr in out.stdout.split(): + used.add(cidr.split("/")[0]) + for name in os.listdir(SERVICES): + ip = service_value(os.path.join(SERVICES, name, "service"), "INTERNAL_IP") + if ip: + used.add(ip) + return used + + +def pick_address(name): + """The app's address: the one it has, or the first free one.""" + if is_ours(name): + ip = service_value(os.path.join(SERVICES, name, "service"), "INTERNAL_IP") + if ip: + return ip + used = used_addresses() + for n in range(FIRST, LAST + 1): + if PREFIX + str(n) not in used: + return PREFIX + str(n) + raise Refused(f"No free address left in {PREFIX}{FIRST}-{LAST}.") + + +def plan(m): + """What installing m would do here, or Refused.""" + name = m["name"] + domain, tier = federated_settings() + if not domain: + raise Refused("This Core isn't provisioned yet (no DOMAIN in /etc/federated).") + if os.path.exists(os.path.join(SERVICES, name)) and not is_ours(name): + raise Refused(f"This Core already has an app called '{name}' " + f"({service_value(os.path.join(SERVICES, name, 'service'), 'CONTAINER') or 'Federated'}). " + "Pick another name.") + if os.path.exists(os.path.join(FEDERATED, "lib", name + ".sh")): + raise Refused(f"'{name}' is the name of one of Federated's apps. Pick another name.") + installed = os.path.isdir(os.path.join(APPS, name)) + if installed and not is_ours(name): + raise Refused(f"/federated/apps/{name} exists but wasn't installed by coreapps.") + p = { + "state": "update" if installed else "new", + "domain": domain, + "tier": tier, + "address": pick_address(name), + "url": f"https://{name}.{domain}/", + } + p["addon"] = "yes" if p["state"] == "new" and tier.lower() != "enterprise" else "no" + if installed: + before = marker_needs(name) + dropped = [n for n in before if n not in m["needs"]] + if dropped: + raise Refused(f"The new coreapp.toml drops needs {', '.join(dropped)}; " + "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] + else: + p["new_needs"] = list(m["needs"]) + return p + + +# --- Making the app's files --------------------------------------------------- + +def read_text(*parts): + try: + with open(os.path.join(*parts)) as f: + return f.read() + except FileNotFoundError: + return "" + + +def fill(text, values): + for key, value in values.items(): + text = text.replace("{{" + key + "}}", value) + return text + + +def write(path, text, mode=0o644): + with open(path, "w") as f: + f.write(text) + os.chmod(path, mode) + + +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: + with open(path, "rb") as f: + if f.read(8) == b"\x89PNG\r\n\x1a\n": + return path + except OSError: + pass + return os.path.join(TEMPLATES, "icon.png") + + +def make_service_folder(m, p, source): + """/federated/services// in the Core's generic format, from m.""" + values = { + "NAME": m["name"], "TITLE": m["title"], "DESCRIPTION": m["description"], + "DOCS": m["docs"], "IMAGE": m["image"], "VERSION": m["version"], + "IP": p["address"], "PORT": str(m["port"]), "DBNAME": m["dbname"], + "DEPENDS": " ".join(read_text(NEEDS_DIR, n, "depends").strip() for n in m["needs"]), + } + compose_extra = "".join(read_text(NEEDS_DIR, n, "compose") for n in m["needs"]) + compose = read_text(TEMPLATES, "docker-compose.yml.in").replace( + "{{COMPOSE_EXTRA}}\n", compose_extra) + env = read_text(TEMPLATES, "env.in") + "".join( + read_text(NEEDS_DIR, n, "env.in") for n in m["needs"]) + + final = os.path.join(SERVICES, m["name"]) + new = final + ".new" + shutil.rmtree(new, ignore_errors=True) + os.makedirs(new) + write(os.path.join(new, "service"), fill(read_text(TEMPLATES, "service"), values)) + write(os.path.join(new, "docker-compose.yml.in"), fill(compose, values)) + write(os.path.join(new, "env.in"), fill(env, values)) + write(os.path.join(new, "install"), fill(read_text(TEMPLATES, "install"), values), 0o755) + write(os.path.join(new, "uninstall"), fill(read_text(TEMPLATES, "uninstall"), values), 0o755) + for need in m["needs"]: + os.makedirs(os.path.join(new, "needs", need)) + for step in ("setup", "teardown"): + write(os.path.join(new, "needs", need, step), + fill(read_text(NEEDS_DIR, need, step), values)) + shutil.copyfile(icon_from(source), os.path.join(new, "icon.png")) + 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") + shutil.rmtree(final, ignore_errors=True) + os.rename(new, final) + + +# --- install, update, remove ---------------------------------------------------- + +def log_path(name, what): + os.makedirs(LOGS, mode=0o700, exist_ok=True) + path = os.path.join(LOGS, f"{name}-{what}.log") + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + os.close(fd) + return path + + +def run_logged(cmd, log, failure): + """Run cmd with its output in log (the Core's scripts trace secrets).""" + with open(log, "a") as f: + result = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT, cwd=FEDERATED) + if result.returncode != 0: + with open(log) as f: + tail = f.readlines()[-20:] + sys.stderr.write("".join(tail)) + raise Refused(f"{failure} (whole log on the Core: {log}).") + + +def ensure_image(m): + ref = f"{m['image']}:{m['version']}" + if 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]) + if out.returncode != 0: + raise Refused(f"Couldn't pull {ref}: {out.stderr.strip()}") + + +def compose_up(name, log): + run_logged(["docker", "compose", "-f", f"{APPS}/{name}/docker-compose.yml", + "-p", name, "up", "-d", "--remove-orphans"], log, + f"Starting {name} failed") + + +# Run on update: the same values the generated install provides, then the +# compose file again (it may have changed), settings the new version adds, +# and the setup of needs that are new. Arguments: name, version, needs. +# (service sets NAME to the app's title, so the name is also in NAME_ID.) +UPDATE_SCRIPT = r''' +cd /federated +. /etc/federated +. lib/functions.sh +. lib/helpers.sh +set -e +. services/$1/service +TRAEFIK_IP="$(sed -n 's/^INTERNAL_IP=//p' services/traefik/service)" +templatize services/$1/docker-compose.yml.in > apps/$1/docker-compose.yml +fresh="$(mktemp)" +templatize services/$1/env.in > "$fresh" +while IFS= read -r line; do + case "$line" in [A-Za-z_]*=*) ;; *) continue ;; esac + grep -q "^${line%%=*}=" apps/$1/.env || echo "$line" >> apps/$1/.env +done < "$fresh" +rm -f "$fresh" +sed -i "s/^IMAGE_VERSION=.*/IMAGE_VERSION=$2/" apps/$1/.env +chmod 600 apps/$1/.env +shift 2 +for need in "$@"; do . services/$NAME_ID/needs/$need/setup; done +''' + + +def install(folder, addon_ok): + m = read_manifest(folder) + p = plan(m) + 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 p["state"] == "new": + say(f"Installing {name} at {p['address']} (the Core's installapp)...") + log = log_path(name, "install") + run_logged([FEDERATED + "/bin/installapp", "-n", name], log, "installapp failed") + # installapp's start step only knows Federated's own apps + compose_up(name, log) + else: + say(f"Updating {name} to {m['version']}...") + log = log_path(name, "update") + env = dict(os.environ, NAME_ID=name) + with open(log, "a") as f: + result = subprocess.run(["bash", "-c", UPDATE_SCRIPT, "update", name, + m["version"], *p["new_needs"]], + stdout=f, stderr=subprocess.STDOUT, env=env) + if result.returncode != 0: + raise Refused(f"Updating failed (whole log on the Core: {log}).") + compose_up(name, log) + + wait_until_answering(m, p) + if p["state"] == "update": + remove_old_images(m) + say(f"{'Installed' if p['state'] == 'new' else 'Updated'}: {p['url']}") + return 0 + + +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]) + + +def wait_until_answering(m, p): + name = m["name"] + url = f"http://{p['address']}:{m['port']}{m['health']}" + say(f"Waiting for it to answer at {url}...") + for _ in range(30): + state = run(["docker", "inspect", "-f", "{{.State.Status}}", name]).stdout.strip() + if state not in ("running", "created", "restarting"): + break + try: + with urllib.request.urlopen(url, timeout=2) as r: + if 200 <= r.status < 400: + return + except urllib.error.HTTPError as e: + if e.code < 500: + return + except (urllib.error.URLError, OSError): + pass + time.sleep(2) + logs = run(["docker", "logs", "--tail", "20", name]) + sys.stderr.write(logs.stdout + logs.stderr) + raise Refused(f"{name} doesn't answer at {url} (state: {state or 'missing'}; " + "its log is above).") + + +def remove(name): + if not re.fullmatch(FIELDS["name"], name): + raise Refused(f"'{name}' isn't an app name.") + folder = os.path.join(SERVICES, name) + if not os.path.isdir(folder): + raise Refused(f"No app called '{name}' on this Core.") + if not is_ours(name): + raise Refused(f"'{name}' wasn't installed by coreapps; it's not removed here.") + image = service_value(os.path.join(folder, "service"), "CONTAINER") + log = log_path(name, "remove") + if os.path.isdir(os.path.join(APPS, name)): + say(f"Uninstalling {name} (the Core's uninstallapp)...") + 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]) + # uninstallapp made superpanel's catalog while the folder was still + # there, so it would still offer the app: make it again, as installapp + # does + if os.path.exists(APPS + "/superpanel/.env"): + run_logged([FEDERATED + "/bin/superpanel-generate-catalog"], log, + "Updating superpanel's app catalog failed") + run(["docker", "exec", "superpanel", "pkill", "-HUP", "superpanel"]) + say(f"Removed {name}.") + return 0 + + +def list_apps(): + rows = [] + for name in sorted(os.listdir(SERVICES)): + if not is_ours(name): + continue + service = os.path.join(SERVICES, name, "service") + state = run(["docker", "inspect", "-f", "{{.State.Status}}", name]).stdout.strip() + rows.append((name, service_value(service, "VERSION"), + service_value(service, "INTERNAL_IP"), state or "not running")) + if not rows: + say("No apps installed by coreapps.") + for row in rows: + say("%-24s %-12s %-16s %s" % row) + return 0 + + +# --- Command line ----------------------------------------------------------------- + +def main(args): + if not args or args[0] in ("-h", "--help", "help"): + print(__doc__.split("\n\n", 2)[2].strip()) + return 0 + cmd, rest = args[0], args[1:] + if cmd == "manifest" and len(rest) == 1: + m = read_manifest(rest[0]) + for key in ("name", "title", "description", "version", "image", "port", + "health", "docs", "dbname"): + print(f"{key}={m[key]}") + print(f"needs={' '.join(m['needs'])}") + return 0 + 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])) + for key, value in p.items(): + print(f"{key}={' '.join(value) if isinstance(value, list) else value}") + return 0 + if cmd == "install" and rest: + addon_ok = "--addon-ok" in rest + folders = [a for a in rest if a != "--addon-ok"] + if len(folders) == 1: + return install(folders[0], addon_ok) + if cmd == "remove" and len(rest) == 1: + return remove(rest[0]) + if cmd == "list" and not rest: + return list_apps() + sys.stderr.write(__doc__.split("\n\n", 2)[2].strip() + "\n") + return 2 + + +if __name__ == "__main__": + try: + sys.exit(main(sys.argv[1:])) + except Refused as e: + sys.stderr.write(f"{e}\n") + sys.exit(1) diff --git a/templates/postgres/.depends b/core/needs/postgres/depends similarity index 100% rename from templates/postgres/.depends rename to core/needs/postgres/depends diff --git a/templates/postgres/env.in.append b/core/needs/postgres/env.in similarity index 67% rename from templates/postgres/env.in.append rename to core/needs/postgres/env.in index a41055c..1305d4b 100644 --- a/templates/postgres/env.in.append +++ b/core/needs/postgres/env.in @@ -1,4 +1,4 @@ -# Its database on the Core's PostgreSQL, made by install +# Its database on the Core's PostgreSQL, made by needs/postgres/setup DB_HOST=postgresql.@DOMAIN@ DB_PORT=5432 DB_NAME={{DBNAME}} diff --git a/templates/postgres/install.append b/core/needs/postgres/setup similarity index 90% rename from templates/postgres/install.append rename to core/needs/postgres/setup index 460fc23..200c3aa 100644 --- a/templates/postgres/install.append +++ b/core/needs/postgres/setup @@ -1,5 +1,4 @@ - -# Its own database and user on the Core's PostgreSQL (DEPENDS=postgresql), +# Its own database and user on the Core's PostgreSQL, # with the password from .env. Safe to run again: an existing user gets the # password, an existing database is kept. DB_PASSWORD="$(sed -n 's/^DB_PASSWORD=//p' /federated/apps/{{NAME}}/.env)" diff --git a/templates/postgres/uninstall.append b/core/needs/postgres/teardown similarity index 73% rename from templates/postgres/uninstall.append rename to core/needs/postgres/teardown index c985e98..9f40b09 100644 --- a/templates/postgres/uninstall.append +++ b/core/needs/postgres/teardown @@ -1,3 +1,3 @@ -# ...and its database +# Drop its database and user from the Core's PostgreSQL docker exec postgresql psql -U postgres -qc "DROP DATABASE IF EXISTS {{DBNAME}}" docker exec postgresql psql -U postgres -qc "DROP USER IF EXISTS {{DBNAME}}" diff --git a/core/needs/sso/compose b/core/needs/sso/compose new file mode 100644 index 0000000..25ba2e0 --- /dev/null +++ b/core/needs/sso/compose @@ -0,0 +1,4 @@ + # Reach Authelia's https address through traefik on the core network + # (inside it, authelia.@DOMAIN@ is Authelia's own plain-http container) + extra_hosts: + - "authelia.@DOMAIN@:@TRAEFIK_IP@" diff --git a/templates/sso/.depends b/core/needs/sso/depends similarity index 100% rename from templates/sso/.depends rename to core/needs/sso/depends diff --git a/templates/sso/env.in.append b/core/needs/sso/env.in similarity index 63% rename from templates/sso/env.in.append rename to core/needs/sso/env.in index 874c69a..0742bbc 100644 --- a/templates/sso/env.in.append +++ b/core/needs/sso/env.in @@ -1,5 +1,5 @@ -# Sign-in through the Core's Authelia (OpenID Connect); install registers -# the client +# Sign-in through the Core's Authelia (OpenID Connect); needs/sso/setup +# registers the client OIDC_ISSUER=https://authelia.@DOMAIN@ OIDC_CLIENT_ID=coreapp-{{NAME}} OIDC_CLIENT_SECRET=@OIDC_CLIENT_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ diff --git a/templates/sso/install.append b/core/needs/sso/setup similarity index 99% rename from templates/sso/install.append rename to core/needs/sso/setup index b7863d3..80118a9 100644 --- a/templates/sso/install.append +++ b/core/needs/sso/setup @@ -1,4 +1,3 @@ - # Register it with the Core's Authelia as an OpenID Connect client, with the # secret from .env (hashed), between markers so uninstall can remove it. # Safe to run again. Authelia is checked with the new client before it diff --git a/templates/sso/uninstall.append b/core/needs/sso/teardown similarity index 73% rename from templates/sso/uninstall.append rename to core/needs/sso/teardown index d8c41a8..52853c9 100644 --- a/templates/sso/uninstall.append +++ b/core/needs/sso/teardown @@ -1,4 +1,4 @@ -# ...and its Authelia client +# Remove its OpenID Connect client from the Core's Authelia sed -i '/^ ### coreapp-{{NAME}} begin$/,/^ ### coreapp-{{NAME}} end$/d' \ /federated/apps/authelia/data/config/idproviders.yml restart_service authelia diff --git a/templates/app/docker-compose.yml.in b/core/templates/docker-compose.yml.in similarity index 89% rename from templates/app/docker-compose.yml.in rename to core/templates/docker-compose.yml.in index aa76e3d..8f36a47 100644 --- a/templates/app/docker-compose.yml.in +++ b/core/templates/docker-compose.yml.in @@ -1,12 +1,13 @@ services: {{NAME}}: - image: coreapp/{{NAME}}:${IMAGE_VERSION} + image: @CONTAINER@:${IMAGE_VERSION} container_name: {{NAME}} hostname: {{NAME}}.@DOMAIN@ restart: always networks: core: ipv4_address: {{IP}} +{{COMPOSE_EXTRA}} env_file: - ./.env volumes: @@ -16,7 +17,7 @@ services: - "traefik.http.routers.{{NAME}}.rule=Host(`{{NAME}}.@DOMAIN@`)" - "traefik.http.routers.{{NAME}}.entrypoints=websecure" - "traefik.http.routers.{{NAME}}.tls.certresolver=letsencrypt" - - "traefik.http.services.{{NAME}}.loadbalancer.server.port=8080" + - "traefik.http.services.{{NAME}}.loadbalancer.server.port={{PORT}}" networks: core: diff --git a/core/templates/env.in b/core/templates/env.in new file mode 100644 index 0000000..d7d700b --- /dev/null +++ b/core/templates/env.in @@ -0,0 +1,5 @@ +# The app's settings, filled in when it's installed. Updates keep the values +# (secrets don't change) and add settings a new version needs. +IMAGE_VERSION=@VERSION@ +APP_URL=https://{{NAME}}.@DOMAIN@ +APP_SECRET=@APP_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ diff --git a/core/templates/icon.png b/core/templates/icon.png new file mode 100644 index 0000000..9e76f46 Binary files /dev/null and b/core/templates/icon.png differ diff --git a/core/templates/install b/core/templates/install new file mode 100644 index 0000000..0b68802 --- /dev/null +++ b/core/templates/install @@ -0,0 +1,14 @@ +# Made by coreapps from the app's coreapp.toml. Sourced by the Core's +# installapp. +. /federated/lib/helpers.sh +# Besides /etc/federated's and service's values, the templates use +# @TRAEFIK_IP@, traefik's address on the core network +TRAEFIK_IP="$(sed -n 's/^INTERNAL_IP=//p' /federated/services/traefik/service)" +installGeneric {{NAME}} +# .env holds secrets +chmod 600 /federated/apps/{{NAME}}/.env +# What the app needs from the Core (its database, its sign-in client) +for setup in /federated/services/{{NAME}}/needs/*/setup; do + [ -e "$setup" ] && . "$setup" +done +unset setup diff --git a/core/templates/service b/core/templates/service new file mode 100644 index 0000000..e9d81b6 --- /dev/null +++ b/core/templates/service @@ -0,0 +1,8 @@ +NAME="{{TITLE}}" +DESCRIPTION="{{DESCRIPTION}}" +DOCS={{DOCS}} +CONTAINER={{IMAGE}} +VERSION={{VERSION}} +INTERNAL_IP={{IP}} +DEPENDS="{{DEPENDS}}" +PORTS={{PORT}} diff --git a/core/templates/uninstall b/core/templates/uninstall new file mode 100644 index 0000000..c212f9c --- /dev/null +++ b/core/templates/uninstall @@ -0,0 +1,9 @@ +# Made by coreapps from the app's coreapp.toml. Sourced by the Core's +# uninstallapp (so no `exit` here): stop the app, undo what it needed from +# the Core, delete its settings and data. +docker compose -f /federated/apps/{{NAME}}/docker-compose.yml -p {{NAME}} down +for teardown in /federated/services/{{NAME}}/needs/*/teardown; do + [ -e "$teardown" ] && . "$teardown" +done +unset teardown +rm -rf /federated/apps/{{NAME}} diff --git a/templates/app/.dockerignore b/templates/app/.dockerignore index f82df0a..9e32a7a 100644 --- a/templates/app/.dockerignore +++ b/templates/app/.dockerignore @@ -1,7 +1,5 @@ .git -service -*.in -install -uninstall +.gitea +coreapp.toml icon.png README.md diff --git a/templates/app/Dockerfile b/templates/app/Dockerfile index f6b34ea..1d02f7b 100644 --- a/templates/app/Dockerfile +++ b/templates/app/Dockerfile @@ -1,6 +1,6 @@ -# The app's image. coreapp deploy builds it as coreapp/{{NAME}}: -# and copies it to the Core. Replace this with your own app; keep it -# listening on the port in docker-compose.yml.in (8080). +# The app's image. coreapp deploy builds it as image:version (from +# coreapp.toml) and copies it to the Core. Replace this with your own app; +# keep it listening on the port in coreapp.toml (8080). FROM busybox:stable COPY www /www EXPOSE 8080 diff --git a/templates/app/README.md b/templates/app/README.md index 1cbc74b..4f81f49 100644 --- a/templates/app/README.md +++ b/templates/app/README.md @@ -18,28 +18,36 @@ coreapp remove # uninstall it from the Core ## Files -The app is in the format Federated Core installs apps from -(`/federated/services/{{NAME}}/` on the Core): - | File | What it is | |---|---| -| `service` | Name, description, image (`CONTAINER`), `VERSION`, `INTERNAL_IP`, apps it needs (`DEPENDS`, e.g. `postgresql`), and how to check it's up (`MONITOR`) | -| `docker-compose.yml.in` | The container(s), on the Core's `core` network at `INTERNAL_IP`, with the traefik labels that give it `https://{{NAME}}.` | -| `env.in` | Its settings, as the `.env` file next to the compose file | -| `install` | Run by the Core's `installapp`; fills in the templates | -| `icon.png` | Its icon in the Core's dashboard | -| `Dockerfile`, `www/` | The app itself (not copied to the Core) | +| `coreapp.toml` | What the Core needs to know: name, title, image and version, port, health path, and what it needs from the Core (`needs`) | +| `Dockerfile`, `www/` | The app itself | +| `icon.png` | Its icon in the Core's dashboard (a PNG, up to 1 MB) | -In `docker-compose.yml.in` and `env.in`, the Core replaces, once at install: +That's all an app has. The Core's side (the container on the Core's `core` +network, the traefik route to `https://{{NAME}}.`, its settings and +secrets, its database or sign-in client) is made by coreapp-dev's installer, +`coreapps`, from `coreapp.toml`. The app can't run scripts on the Core. -- `@DOMAIN@`: the Core's domain, and any other variable in `/etc/federated` -- `@VERSION@`, `@CONTAINER@`, `@INTERNAL_IP@`: from `service` -- `@SECRET:RANDOM:LLLLLLLL@`: a random value (`L` a letter or digit, `a` - lowercase, `A` uppercase, `0` a digit, `x` hex), also available as - `@SECRET@` further down +## What the app gets -`${...}` is left for Docker Compose, which reads it from `.env`. +Its environment (the `.env` file on the Core, made once at install; updates +keep its values and add new ones): -Raise `VERSION` in `service` for each release. The Core's nightly upgrade -only redeploys an app when `VERSION` differs from `IMAGE_VERSION` in its -`.env`. +| Variable | Value | +|---|---| +| `APP_URL` | `https://{{NAME}}.` | +| `APP_SECRET` | A random secret, for signing cookies and such | +| `IMAGE_VERSION` | The version that's installed | + +`needs = ["postgres"]` adds `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER` and +`DB_PASSWORD`; `needs = ["sso"]` adds `OIDC_ISSUER`, `OIDC_CLIENT_ID` and +`OIDC_CLIENT_SECRET`. + +Its files: `/data` in the container is kept on the Core +(`/federated/apps/{{NAME}}/data`) across updates and restarts. + +The app serves plain HTTP on its `port`; traefik on the Core handles HTTPS +and the certificate. + +Raise `version` in `coreapp.toml` for each release. diff --git a/templates/app/coreapp.toml b/templates/app/coreapp.toml new file mode 100644 index 0000000..a63c246 --- /dev/null +++ b/templates/app/coreapp.toml @@ -0,0 +1,23 @@ +# What a Federated Core needs to know to install {{TITLE}}. coreapp-dev's +# installer (coreapps) makes the rest from it: the container on the Core's +# network, https://{{NAME}}., its settings and secrets. + +# Its id and hostname: https://{{NAME}}. +name = "{{NAME}}" +title = "{{TITLE}}" +description = "{{TITLE}}, made with coreapp-dev" +# docs = "https://..." + +# The image, as image:version. localhost/... images only exist where +# coreapp deploy copies them; a published app names its registry, e.g. +# gitea.example.com/owner/{{NAME}}. Raise the version for each release. +image = "localhost/coreapp/{{NAME}}" +version = "0.1.0" + +# The port the app serves HTTP on, and a path that answers when it's up +port = 8080 +health = "/" + +# What it needs from the Core: "postgres" (its own database), "sso" +# (sign-in with Core accounts through Authelia) +needs = [] diff --git a/templates/app/env.in b/templates/app/env.in deleted file mode 100644 index 947b93b..0000000 --- a/templates/app/env.in +++ /dev/null @@ -1,5 +0,0 @@ -# Filled in once, when the app is installed (see README.md). Redeploying -# keeps the result, so secrets don't change. -IMAGE_VERSION=@VERSION@ -APP_URL=https://{{NAME}}.@DOMAIN@ -APP_SECRET=@APP_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ diff --git a/templates/app/install b/templates/app/install deleted file mode 100755 index a9ef095..0000000 --- a/templates/app/install +++ /dev/null @@ -1,7 +0,0 @@ -. /federated/lib/helpers.sh -# Values the templates can use besides /etc/federated's and service's: -# @TRAEFIK_IP@, traefik's address on the core network -TRAEFIK_IP="$(sed -n 's/^INTERNAL_IP=//p' /federated/services/traefik/service)" -installGeneric {{NAME}} -# .env holds secrets -chmod 600 /federated/apps/{{NAME}}/.env diff --git a/templates/app/service b/templates/app/service deleted file mode 100644 index 021c2b0..0000000 --- a/templates/app/service +++ /dev/null @@ -1,9 +0,0 @@ -NAME="{{TITLE}}" -DESCRIPTION="{{TITLE}}, made with coreapp-dev" -DOCS= -CONTAINER=coreapp/{{NAME}} -VERSION=0.1.0 -INTERNAL_IP={{IP}} -DEPENDS="" -PORTS=8080 -MONITOR="https://{{NAME}}.@DOMAIN@|http_2xx" diff --git a/templates/app/uninstall b/templates/app/uninstall deleted file mode 100755 index e34d3ce..0000000 --- a/templates/app/uninstall +++ /dev/null @@ -1,4 +0,0 @@ -# Sourced by the Core's uninstallapp (so no `exit` here): stop the app and -# delete its settings and data -docker compose -f /federated/apps/{{NAME}}/docker-compose.yml -p {{NAME}} down -rm -rf /federated/apps/{{NAME}} diff --git a/templates/postgres-sso/Dockerfile b/templates/postgres-sso/Dockerfile index 499ec0d..00b415e 100644 --- a/templates/postgres-sso/Dockerfile +++ b/templates/postgres-sso/Dockerfile @@ -1,6 +1,6 @@ -# The app's image. coreapp deploy builds it as coreapp/{{NAME}}: -# and copies it to the Core. Replace this with your own app; keep it -# listening on the port in docker-compose.yml.in (8080). +# The app's image. coreapp deploy builds it as image:version (from +# coreapp.toml) and copies it to the Core. Replace this with your own app; +# keep it listening on the port in coreapp.toml (8080). FROM python:3.13-slim RUN pip install --no-cache-dir "psycopg[binary]==3.2.*" COPY app.py oidc.py /app/ diff --git a/templates/postgres/.needs b/templates/postgres/.needs new file mode 100644 index 0000000..f134994 --- /dev/null +++ b/templates/postgres/.needs @@ -0,0 +1 @@ +postgres diff --git a/templates/postgres/Dockerfile b/templates/postgres/Dockerfile index 26b0e69..9e6a925 100644 --- a/templates/postgres/Dockerfile +++ b/templates/postgres/Dockerfile @@ -1,6 +1,6 @@ -# The app's image. coreapp deploy builds it as coreapp/{{NAME}}: -# and copies it to the Core. Replace this with your own app; keep it -# listening on the port in docker-compose.yml.in (8080). +# The app's image. coreapp deploy builds it as image:version (from +# coreapp.toml) and copies it to the Core. Replace this with your own app; +# keep it listening on the port in coreapp.toml (8080). FROM python:3.13-slim RUN pip install --no-cache-dir "psycopg[binary]==3.2.*" COPY app.py /app/app.py diff --git a/templates/postgres/README.md.append b/templates/postgres/README.md.append index c8276e6..1f711b7 100644 --- a/templates/postgres/README.md.append +++ b/templates/postgres/README.md.append @@ -1,12 +1,12 @@ ## Database -The app has its own database on the Core's shared PostgreSQL -(`DEPENDS="postgresql"` in `service`): +`needs = ["postgres"]`: the app has its own database on the Core's shared +PostgreSQL. -- `install` creates the user and database `{{DBNAME}}`, with the random - `DB_PASSWORD` from `.env`; `uninstall` drops both (`coreapp remove` - deletes the data). +- At install, the user and database `{{DBNAME}}` are created, with the + random `DB_PASSWORD` from `.env`. `coreapp remove` drops both, with the + data. - The app reads `DB_HOST` (`postgresql.`, which only resolves on the Core's `core` network), `DB_PORT`, `DB_NAME`, `DB_USER` and `DB_PASSWORD` from its environment. `app.py` shows how, with `psycopg`. diff --git a/templates/sso/.needs b/templates/sso/.needs new file mode 100644 index 0000000..496502b --- /dev/null +++ b/templates/sso/.needs @@ -0,0 +1 @@ +sso diff --git a/templates/sso/Dockerfile b/templates/sso/Dockerfile index 9eb030b..5b7dda1 100644 --- a/templates/sso/Dockerfile +++ b/templates/sso/Dockerfile @@ -1,6 +1,6 @@ -# The app's image. coreapp deploy builds it as coreapp/{{NAME}}: -# and copies it to the Core. Replace this with your own app; keep it -# listening on the port in docker-compose.yml.in (8080). +# The app's image. coreapp deploy builds it as image:version (from +# coreapp.toml) and copies it to the Core. Replace this with your own app; +# keep it listening on the port in coreapp.toml (8080). FROM python:3.13-slim COPY app.py oidc.py /app/ USER nobody diff --git a/templates/sso/README.md.append b/templates/sso/README.md.append index b479d94..e879bd1 100644 --- a/templates/sso/README.md.append +++ b/templates/sso/README.md.append @@ -1,20 +1,15 @@ ## Sign-in -People sign in with their Core account, through the Core's Authelia -(OpenID Connect, authorization code flow with PKCE): +`needs = ["sso"]`: people sign in with their Core account, through the +Core's Authelia (OpenID Connect, authorization code flow with PKCE). -- `install` registers the client `coreapp-{{NAME}}` in Authelia's - `idproviders.yml` (between `### coreapp-{{NAME}} begin/end` markers), with - the random `OIDC_CLIENT_SECRET` from `.env`, hashed. It checks Authelia's - configuration before restarting it and puts the old one back if the check - fails. `uninstall` removes the client. -- Its redirect URI is `https://{{NAME}}./auth/callback`. Change it in - `install` if your app uses another path. -- Authelia decides whether a second factor is needed (the Core's 2FA policy - is applied to every client after each install). -- The app reaches `https://authelia.` through traefik - (`extra_hosts` in `docker-compose.yml.in`). +- At install, the client `coreapp-{{NAME}}` is registered in Authelia, with + the random `OIDC_CLIENT_SECRET` from `.env`. `coreapp remove` removes it. +- Its redirect URI is `https://{{NAME}}./auth/callback`, so the app + has to handle that path. +- Authelia decides whether a second factor is needed (the Core's 2FA + policy). - `oidc.py` does the whole flow with Python's standard library, and `app.py` uses it for `/login`, `/auth/callback` and `/logout`. For a real app, use your framework's OpenID Connect library with `OIDC_ISSUER`, diff --git a/templates/sso/docker-compose.yml.in b/templates/sso/docker-compose.yml.in deleted file mode 100644 index 6982e4f..0000000 --- a/templates/sso/docker-compose.yml.in +++ /dev/null @@ -1,27 +0,0 @@ -services: - {{NAME}}: - image: coreapp/{{NAME}}:${IMAGE_VERSION} - container_name: {{NAME}} - hostname: {{NAME}}.@DOMAIN@ - restart: always - networks: - core: - ipv4_address: {{IP}} - # Reach Authelia's https address through traefik on the core network - # (inside it, authelia.@DOMAIN@ is Authelia's own plain-http container) - extra_hosts: - - "authelia.@DOMAIN@:@TRAEFIK_IP@" - env_file: - - ./.env - volumes: - - ./data:/data - labels: - - "traefik.enable=true" - - "traefik.http.routers.{{NAME}}.rule=Host(`{{NAME}}.@DOMAIN@`)" - - "traefik.http.routers.{{NAME}}.entrypoints=websecure" - - "traefik.http.routers.{{NAME}}.tls.certresolver=letsencrypt" - - "traefik.http.services.{{NAME}}.loadbalancer.server.port=8080" - -networks: - core: - external: true