diff --git a/PLAN.md b/PLAN.md index f47335d..4996775 100644 --- a/PLAN.md +++ b/PLAN.md @@ -489,8 +489,14 @@ Steps: in one command - [ ] David: Miniflux runs without an admin until the Core's groups work (then map `admins`) - - [ ] `[postgres] extensions = ["vector"]`: the installer enables - extensions an app can't (when an app needs one) + - Done 2026-12-03: `[postgres] extensions = ["vector"]` in + coreapp.toml: the installer checks the Core has each one and + makes it in the app's database as the superuser (`CASCADE`, so + dependencies come too), on install and every update; ones taken + off the list are kept. Tested on dev.fedcom.net with vector, + pg_trgm and earthdistance, a refused postgis, and a rollback that + kept them. Also fixed: `needs` with both postgres and mysql was + meant to be refused, but the check never ran - [ ] PostgreSQL 18 on the Core (Federated's), or a minimum version in coreapp.toml that the installer checks, so an app refuses to install on an older Core instead of failing later diff --git a/README.md b/README.md index 29b5ba4..51573bb 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,9 @@ needs = ["postgres", "sso"] # its own database ("mysql" for MariaDB); s callback = "/auth/openid/core" # default "/auth/callback" pkce = false # default true token_auth = "client_secret_post" # default "client_secret_basic" + +[postgres] # optional: extensions only a superuser can make +extensions = ["vector"] ``` The app has no scripts or compose file: the Core side is made by diff --git a/TEST.md b/TEST.md index fbf03dd..f8d962a 100644 --- a/TEST.md +++ b/TEST.md @@ -222,6 +222,17 @@ The Core's own scripts trace secrets, so their output goes to disk (btrfs) and what's not offered. As an app's database user, `CREATE EXTENSION pg_trgm` works and `CREATE EXTENSION vector` is refused ("Must be superuser"). +5c. `[postgres] extensions`: a `coreapp new --postgres` app with + `[postgres]` `extensions = ["vector"]` deploys with "Enabling PostgreSQL + extension(s) vector"; on the Core, its database has vector (owned by + postgres), and as the app's user a `vector(3)` table, a distance query + and an HNSW index work. Adding `"postgis"` is refused before anything + changes ("this Core's PostgreSQL doesn't have postgis"); adding + `"pg_trgm"` enables only that; `"earthdistance"` brings cube with it. + An update that fails (a wrong `port`) rolls back with the extensions, + the table and its index. `[postgres]` without `"postgres"` in needs, an + unknown setting or a bad name is refused; so is `needs` with both + postgres and mysql. 6. `coreapp status` (address and port), `coreapp logs`, `coreapp shell` (exit with `exit`), `coreapp shell 'id; echo $APP_URL'` (prints both, no terminal needed, also when piped), `coreapp list` (all apps installed diff --git a/core/coreapps b/core/coreapps index a3af564..bb494bd 100755 --- a/core/coreapps +++ b/core/coreapps @@ -98,6 +98,7 @@ FIELDS = { "docs": r"(?:https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~/%+-]*)?)?", "needs": None, "sso": None, + "postgres": None, } REQUIRED = ["name", "title", "version", "image", "port"] @@ -108,6 +109,11 @@ SSO_DEFAULTS = {"callback": "/auth/callback", "pkce": True, SSO_CALLBACK = r"/[A-Za-z0-9._~/-]{0,200}" SSO_TOKEN_AUTH = ["client_secret_basic", "client_secret_post"] +# [postgres]: extensions the Core's superuser enables in the app's database +# (ones the app's own user can't, like vector) +POSTGRES_SETTINGS = ["extensions"] +EXTENSION = r"[a-z0-9][a-z0-9_-]{0,62}" + # Repositories apps are installed from: https only, no user or password in # the URL. Tags: v + a version; releases (picked by default) are numeric. REPO_URL = r"https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._-]+){2,}?(?:\.git)?/?" @@ -156,6 +162,22 @@ def read_sso(value): return sso +def read_postgres(value): + """coreapp.toml's [postgres] table, checked.""" + if not isinstance(value, dict): + raise Refused('coreapp.toml: postgres must be a table: [postgres] with extensions = ["vector"].') + unknown = sorted(set(value) - set(POSTGRES_SETTINGS)) + if unknown: + raise Refused(f"coreapp.toml: [postgres]: unknown setting(s) {', '.join(unknown)} " + f"(it knows {', '.join(POSTGRES_SETTINGS)}).") + extensions = value.get("extensions", []) + if not isinstance(extensions, list) or not all( + isinstance(e, str) and re.fullmatch(EXTENSION, e) for e in extensions): + raise Refused('coreapp.toml: [postgres] extensions must be a list of extension names, ' + 'like extensions = ["vector"].') + return {"extensions": sorted(set(extensions))} + + def read_manifest(folder): """coreapp.toml in folder, checked, with defaults filled in.""" path = os.path.join(folder, "coreapp.toml") @@ -177,7 +199,8 @@ def read_manifest(folder): if missing: raise Refused(f"coreapp.toml needs {', '.join(missing)}.") - m = {"description": "", "health": "/", "docs": "", "needs": [], "sso": dict(SSO_DEFAULTS)} + m = {"description": "", "health": "/", "docs": "", "needs": [], "sso": dict(SSO_DEFAULTS), + "postgres": {"extensions": []}} for key, value in data.items(): if key == "port": if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= 65535: @@ -190,11 +213,13 @@ def read_manifest(folder): raise Refused(f"coreapp.toml: needs: unknown {', '.join(bad)} " f"(it knows {', '.join(NEEDS)}).") value = [n for n in NEEDS if n in value] - elif key == "sso": - value = read_sso(value) if "postgres" in value and "mysql" in value: raise Refused("coreapp.toml: needs: postgres or mysql, not both " "(both give the app DB_* settings).") + elif key == "sso": + value = read_sso(value) + elif key == "postgres": + value = read_postgres(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. " @@ -202,6 +227,8 @@ def read_manifest(folder): m[key] = value if "sso" in data and "sso" not in m["needs"]: raise Refused('coreapp.toml: [sso] is for apps with "sso" in needs.') + if "postgres" in data and "postgres" not in m["needs"]: + raise Refused('coreapp.toml: [postgres] is for apps with "postgres" in needs.') 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("-", "_") @@ -596,12 +623,31 @@ def plan(m, origin=None, downgrade=False, drop_database=False): else: p["new_needs"] = list(m["needs"]) p["dropped_needs"] = [] + p["new_extensions"] = extensions_to_enable(m, p) for key in ("source", "tag", "commit"): if origin: p[key] = origin[key] return p +def extensions_to_enable(m, p): + """[postgres] extensions the app's database doesn't have yet, or Refused + if this Core's PostgreSQL doesn't have one.""" + wanted = m["postgres"]["extensions"] + if not wanted: + return [] + psql = ["docker", "exec", "postgresql", "psql", "-U", "postgres", "-Atc"] + available = run(psql + ["SELECT name FROM pg_available_extensions"]).stdout.split() + missing = [e for e in wanted if e not in available] + if missing: + raise Refused(f"coreapp.toml: [postgres] extensions: this Core's PostgreSQL doesn't have " + f"{', '.join(missing)} (coreapp core lists the ones it has).") + have = [] + if p["state"] == "update" and "postgres" not in p["new_needs"]: + have = run(psql + ["SELECT extname FROM pg_extension", "-d", m["dbname"]]).stdout.split() + return [e for e in wanted if e not in have] + + # --- Making the app's files --------------------------------------------------- def read_text(*parts): @@ -671,6 +717,7 @@ def make_service_folder(m, p, source, origin): "SSO_PKCE": ("require_pkce: true\n pkce_challenge_method: 'S256'" if m["sso"]["pkce"] else "require_pkce: false"), "DEPENDS": " ".join(read_text(NEEDS_DIR, n, "depends").strip() for n in m["needs"]), + "EXTENSIONS": " ".join(m["postgres"]["extensions"]), } compose_extra = "".join(read_text(NEEDS_DIR, n, "compose") for n in m["needs"]) compose = read_text(TEMPLATES, "docker-compose.yml.in").replace( @@ -877,6 +924,9 @@ def install_app(m, p, folder, origin, addon_ok, recreate): if state != "ok": say(f"Note: {note}") + if p["new_extensions"]: + say(f"Enabling PostgreSQL extension(s) {', '.join(p['new_extensions'])} in " + f"{name}'s database (as the Core's superuser).") if p["state"] == "new": make_service_folder(m, p, folder, origin) say(f"Installing {name} at {p['address']} (the Core's installapp)...") diff --git a/core/needs/postgres/setup b/core/needs/postgres/setup index 200c3aa..a04e418 100644 --- a/core/needs/postgres/setup +++ b/core/needs/postgres/setup @@ -11,3 +11,8 @@ if ! docker exec postgresql psql -U postgres -tAc "SELECT 1 FROM pg_database WHE docker exec postgresql psql -U postgres -qc "CREATE DATABASE {{DBNAME}} OWNER {{DBNAME}}" fi unset DB_PASSWORD +# The extensions coreapp.toml asks for (also kept current by update) +for extension in {{EXTENSIONS}}; do + docker exec postgresql psql -U postgres -d {{DBNAME}} -v ON_ERROR_STOP=1 -qc "CREATE EXTENSION IF NOT EXISTS \"$extension\" CASCADE" +done +unset extension diff --git a/core/needs/postgres/update b/core/needs/postgres/update new file mode 100644 index 0000000..a063fb5 --- /dev/null +++ b/core/needs/postgres/update @@ -0,0 +1,8 @@ +# The extensions coreapp.toml asks for ([postgres] extensions), made by the +# Core's superuser in the app's database (the app's user can't make +# untrusted ones, like vector). Ones already there are kept, also when the +# list drops them: the app's data may use them. +for extension in {{EXTENSIONS}}; do + docker exec postgresql psql -U postgres -d {{DBNAME}} -v ON_ERROR_STOP=1 -qc "CREATE EXTENSION IF NOT EXISTS \"$extension\" CASCADE" +done +unset extension diff --git a/skills/coreapp/SKILL.md b/skills/coreapp/SKILL.md index 19cf9fa..b146c8f 100644 --- a/skills/coreapp/SKILL.md +++ b/skills/coreapp/SKILL.md @@ -118,7 +118,7 @@ using it runs, so deploy, `coreapp check` and a sign-in can all pass. |---|---|---| | PostgreSQL | 17.6 | `needs = ["postgres"]` | | PostgreSQL extensions the app can enable (`CREATE EXTENSION` in its migrations) | btree_gin, btree_gist, citext, cube, fuzzystrmatch, hstore, intarray, isn, lo, ltree, pg_trgm, pgcrypto, seg, tablefunc, unaccent, uuid-ossp, ... | | -| Extensions only the Core can enable | vector (pgvector 0.8.1), pg_stat_statements, dblink, postgres_fdw, ... | not available to apps yet: report it | +| Extensions only the Core can enable | vector (pgvector 0.8.1), pg_stat_statements, dblink, postgres_fdw, ... | `[postgres] extensions = ["vector"]` in coreapp.toml | | MariaDB | 12.1.2 | `needs = ["mysql"]` | | Authelia | 4.39 | `needs = ["sso"]`: OpenID Connect sign-in with Core accounts | | Mail server | docker-mailserver 16 | `needs = ["email"]`: sending, SMTP with STARTTLS | @@ -160,7 +160,22 @@ The server is the Core's PostgreSQL (its version and extensions: "What the Core offers"; check the app's needs against them first), shared with the Core's other apps; the app owns its database and nothing else. There's no superuser access, so the app creates its own tables (migrations at startup -are the usual way). At boot the +are the usual way). Extensions the app's user can't make (vector and the +others "only the Core can enable") go in `coreapp.toml`; the installer +makes them, as the superuser, before the app starts: + +```toml +[postgres] +extensions = ["vector"] # pgvector, for the app's embeddings +``` + +List only those the app's migrations need (trusted ones may be listed +too, which is harmless; dependencies, like cube for earthdistance, come +with them). A migration's own `CREATE EXTENSION IF NOT EXISTS vector` then +passes; one without `IF NOT EXISTS` fails, so change it. An extension the +Core doesn't have (postgis today) is refused at deploy: report it. Taking +one off the list keeps it in the database, since the data may use it. At +boot the database may come up after the app: retry the connection instead of exiting. Many apps want a URL; build it from these variables in the entrypoint or the app's config (e.g. diff --git a/templates/app/README.md b/templates/app/README.md index d0978ff..92ba437 100644 --- a/templates/app/README.md +++ b/templates/app/README.md @@ -45,7 +45,9 @@ keep its values and add new ones): | `CORE_ADMIN_EMAIL` | `admin@`, the Core's admin account: always an admin of the app, when it signs in with the Core | `needs = ["postgres"]` adds `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER` and -`DB_PASSWORD` (`needs = ["mysql"]` the same, for MariaDB); `needs = ["sso"]` adds `OIDC_ISSUER`, `OIDC_CLIENT_ID` and +`DB_PASSWORD` (`needs = ["mysql"]` the same, for MariaDB; PostgreSQL +extensions only a superuser can make, like vector, go in `coreapp.toml`'s +`[postgres] extensions`); `needs = ["sso"]` adds `OIDC_ISSUER`, `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET` (the client's callback, PKCE and secret method are in `coreapp.toml`'s `[sso]`); `needs = ["email"]` adds `SMTP_HOST`, `SMTP_PORT` (587), `SMTP_SECURITY` (`starttls`), `SMTP_USER`, `SMTP_PASSWORD` and diff --git a/templates/app/coreapp.toml b/templates/app/coreapp.toml index 6f6e730..eeca218 100644 --- a/templates/app/coreapp.toml +++ b/templates/app/coreapp.toml @@ -29,3 +29,8 @@ needs = [] # callback = "/auth/callback" # the path it sends people back to # pkce = true # whether it sends PKCE (S256) # token_auth = "client_secret_basic" # or "client_secret_post" + +# With "postgres": extensions the app's database user can't make itself, +# made by the Core (coreapp core lists what it has) +# [postgres] +# extensions = ["vector"]