diff --git a/PLAN.md b/PLAN.md index be8da31..45c2dc8 100644 --- a/PLAN.md +++ b/PLAN.md @@ -345,6 +345,26 @@ Steps: linked into `~/.claude/skills/coreapp` by `update.sh`, so any Claude Code agent on this computer can use it. Rehearsed with a small app (`memo-board`) + - Rehearsed again 2026-12-03 with Vikunja (postgres, sso, email), by an + agent given only the skill. It worked, but Vikunja's sign-in couldn't + use the fixed Authelia client (its browser code sends people back to + `/auth/openid/`, and its server doesn't send PKCE: checked in + its v2.8.0 source), so the agent wrote a 450-line OpenID bridge into the + container. Fixed in coreapps instead: `[sso]` in `coreapp.toml` + (`callback`, `pkce`, `token_auth`) shapes the app's client; changing it + registers the client again on deploy (Authelia restarts only then), and + a rollback puts the old one back (needs' update steps run after the + old files are restored). Stock Vikunja with `[sso] callback = + "/auth/openid/core"`, `pkce = false` and a busybox entrypoint replaced + the bridge. Also from it: the skill covers images without a shell + (copy in a static busybox), upstream `ENV` defaults, when Authelia + checks PKCE, and says not to build bridges; `coreapp shell` explains a + missing `sh`; `coreapp status` hides the empty address before install; + the example apps' README no longer mentions `www/` + - [ ] David: sign in to `https://vikunja.dev.fedcom.net/` with a Core + account (the agent tested the flow only against a stand-in Authelia) + - [ ] A "test locally" recipe in the skill: running the image with + made-up Core settings, for sign-in code - [ ] Test it with David's candidate app: an agent in that repository uses the skill; what it struggles with becomes fixes 6. [ ] The Coreapps screen in Superpanel (Federated's code: needs their diff --git a/README.md b/README.md index f94afd5..ec0b86c 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,11 @@ 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 ("mysql" for MariaDB); sign-in with Core accounts; "email": sending mail + +[sso] # optional: for apps whose sign-in can't match the default client +callback = "/auth/openid/core" # default "/auth/callback" +pkce = false # default true +token_auth = "client_secret_post" # default "client_secret_basic" ``` The app has no scripts or compose file: the Core side is made by diff --git a/TEST.md b/TEST.md index 1adb6f9..bf2aa42 100644 --- a/TEST.md +++ b/TEST.md @@ -305,6 +305,24 @@ has the `DB_*` variables, `.coreapp` says `needs=postgres`. `coreapp remove`: no block and no copy, and running `/federated/bin/reconcile-authelia-sso` doesn't bring it back; Authelia healthy, other clients (Nextcloud) still work. Deploy again: one block. +7. `[sso]`: `coreapps manifest` prints `sso_callback`, `sso_pkce`, + `sso_token_auth` (defaults `/auth/callback`, `true`, + `client_secret_basic`). Refused: `[sso]` without "sso" in needs, a + callback that isn't a path (`auth`, `/a'b`), `pkce = "no"`, `token_auth = + "none"`, an unknown key, `sso = "x"`. With the defaults, the client + block is the same as before `[sso]` existed. +8. Add `[sso] token_auth = "client_secret_post"` to an installed app and + deploy: its block says `client_secret_post` and Authelia restarted and is + healthy; remove it, deploy: `client_secret_basic` again. `callback = + "/auth/openid/core"`, `pkce = false`: the block has that redirect URI, + `require_pkce: false` and no `pkce_challenge_method`; Authelia's + authorize URL with that `redirect_uri` goes to its login page, with + `/auth/callback` to an `invalid_request` error. The copy + (`..oidc-client.yml`) matches. +9. Stock Vikunja (`vikunja/vikunja:2.8.0` with a busybox entrypoint, + `[sso] callback = "/auth/openid/core"`, `pkce = false`): `/api/v1/info` + lists the "Federated Core" provider; a browser sign-in with a Core + account works. ### With mysql diff --git a/bin/coreapp b/bin/coreapp index 44c0554..743f153 100755 --- a/bin/coreapp +++ b/bin/coreapp @@ -198,6 +198,9 @@ cmd_new() { [[ -n "$mysql" ]] && needs="\"mysql\"$needs" [[ -n "$email" ]] && needs="$needs, \"email\"" sed -i "s/^needs = .*/needs = [${needs#, }]/" "$name/coreapp.toml" + # The example apps with a database or sign-in are Python, not www/ + # shellcheck disable=SC2016 # backquotes are Markdown + [[ -d "$name/www" ]] || sed -i 's|`www/`|the `.py` files|g' "$name/README.md" # 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" @@ -294,10 +297,12 @@ cmd_status() { local domain load_app domain="$(core_domain)" + local address 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 $(image)" - echo "Address on the Core: $(core "sed -n 's/^INTERNAL_IP=//p' /federated/services/$NAME/service 2> /dev/null"), port $PORT" + address="$(core "sed -n 's/^INTERNAL_IP=//p' /federated/services/$NAME/service 2> /dev/null || true")" + [[ -z "$address" ]] || echo "Address on the Core: $address, port $PORT" echo "Needs: ${NEEDS:-nothing}" echo "URL: https://$NAME.$domain/" } @@ -313,6 +318,8 @@ cmd_logs() { cmd_shell() { load_app + core "docker exec $NAME sh -c : > /dev/null 2>&1" \ + || die "Can't run a shell in $NAME: it isn't running (coreapp status, coreapp logs), or its image has no sh (images built FROM scratch or distroless). coreapp logs shows its output." if [[ $# -gt 0 ]]; then # One command, without a terminal, so scripts and agents can use it: # coreapp shell 'ls -l /data' diff --git a/core/coreapps b/core/coreapps index 4806e8b..0e1d604 100755 --- a/core/coreapps +++ b/core/coreapps @@ -86,9 +86,17 @@ FIELDS = { "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, + "sso": None, } REQUIRED = ["name", "title", "version", "image", "port"] +# [sso]: how the app's OpenID Connect client in Authelia differs from the +# default, for apps whose sign-in can't be configured to match it +SSO_DEFAULTS = {"callback": "/auth/callback", "pkce": True, + "token_auth": "client_secret_basic"} +SSO_CALLBACK = r"/[A-Za-z0-9._~/-]{0,200}" +SSO_TOKEN_AUTH = ["client_secret_basic", "client_secret_post"] + # 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)?/?" @@ -118,6 +126,25 @@ def say(*args): # --- coreapp.toml ------------------------------------------------------------- +def read_sso(value): + """coreapp.toml's [sso] table, checked, with defaults filled in.""" + if not isinstance(value, dict): + raise Refused("coreapp.toml: sso must be a table: [sso] with callback, pkce, token_auth.") + unknown = sorted(set(value) - set(SSO_DEFAULTS)) + if unknown: + raise Refused(f"coreapp.toml: [sso]: unknown setting(s) {', '.join(unknown)} " + f"(it knows {', '.join(SSO_DEFAULTS)}).") + sso = dict(SSO_DEFAULTS, **value) + if not isinstance(sso["callback"], str) or not re.fullmatch(SSO_CALLBACK, sso["callback"]): + raise Refused(f"coreapp.toml: [sso] callback = {sso['callback']!r} isn't allowed: " + "a path on the app's own address, like \"/auth/callback\".") + if not isinstance(sso["pkce"], bool): + raise Refused("coreapp.toml: [sso] pkce must be true or false.") + if sso["token_auth"] not in SSO_TOKEN_AUTH: + raise Refused(f"coreapp.toml: [sso] token_auth must be {' or '.join(SSO_TOKEN_AUTH)}.") + return sso + + def read_manifest(folder): """coreapp.toml in folder, checked, with defaults filled in.""" path = os.path.join(folder, "coreapp.toml") @@ -139,7 +166,7 @@ def read_manifest(folder): if missing: raise Refused(f"coreapp.toml needs {', '.join(missing)}.") - m = {"description": "", "health": "/", "docs": "", "needs": []} + m = {"description": "", "health": "/", "docs": "", "needs": [], "sso": dict(SSO_DEFAULTS)} for key, value in data.items(): if key == "port": if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= 65535: @@ -152,6 +179,8 @@ 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).") @@ -160,6 +189,8 @@ def read_manifest(folder): raise Refused(f"coreapp.toml: {key} = {value!r} isn't allowed. " + HINTS.get(key, "")) 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 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("-", "_") @@ -604,6 +635,9 @@ def make_service_folder(m, p, source, origin): # Without docs, Superpanel links a search of Federated's documentation "DOCS": m["docs"] or (origin["source"] if origin else ""), "IMAGE": m["image"], "VERSION": m["version"], "IP": p["address"], "PORT": str(m["port"]), "DBNAME": m["dbname"], + "SSO_CALLBACK": m["sso"]["callback"], "SSO_TOKEN_AUTH": m["sso"]["token_auth"], + "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"]), } compose_extra = "".join(read_text(NEEDS_DIR, n, "compose") for n in m["needs"]) @@ -920,6 +954,18 @@ for need in "$@"; do done ''' +# After the old service folder is back: its needs' update steps, so what +# they set up matches it again (e.g. an Authelia client the update changed) +RESYNC_SCRIPT = r''' +cd /federated +. /etc/federated +. lib/functions.sh +. lib/helpers.sh +for step in services/$1/needs/*/update; do + if [ -e "$step" ]; then . "$step"; fi +done +''' + def roll_back(m, p, backup, log): """Put back the version that ran before a failed update, with its @@ -952,6 +998,11 @@ def roll_back(m, p, backup, log): for f in ROLLBACK_FILES: if os.path.exists(os.path.join(backup, f)): shutil.copy2(os.path.join(backup, f), os.path.join(APPS, name, f)) + with open(log, "a") as f: + result = subprocess.run(["bash", "-c", RESYNC_SCRIPT, "resync", name], + stdout=f, stderr=subprocess.STDOUT) + if result.returncode != 0: + problems.append("putting back what its needs set up") try: old = read_manifest(final) except Refused: @@ -1126,6 +1177,9 @@ def main(args): "health", "docs", "dbname"): print(f"{key}={m[key]}") print(f"needs={' '.join(m['needs'])}") + if "sso" in m["needs"]: + for key, value in m["sso"].items(): + print(f"sso_{key}={str(value).lower() if isinstance(value, bool) else value}") state, note = icon_check(rest[0]) print(f"icon={state}") print(f"icon_note={note}") diff --git a/core/needs/sso/setup b/core/needs/sso/setup index 8ba5cbe..b548ffe 100644 --- a/core/needs/sso/setup +++ b/core/needs/sso/setup @@ -15,10 +15,9 @@ cat >> "$IDP" <> "$IDP" <` | | `OIDC_CLIENT_SECRET` | random | -The client is fixed, so the app has to fit it: +The client, by default: - Redirect URI: exactly `https://./auth/callback` - (`$APP_URL/auth/callback`). If the app's library uses another callback - path, configure the library, or route `/auth/callback` to it. + (`$APP_URL/auth/callback`). - Authorization code flow, PKCE with S256 required, client authentication `client_secret_basic` (secret in the Authorization header). + +If the app's sign-in can't be configured to match (many have a fixed +callback path, and many don't send PKCE), change the client in +`coreapp.toml` instead of working around it in the app: + +```toml +[sso] +callback = "/auth/openid/core" # the app's callback path (default "/auth/callback") +pkce = false # the app doesn't send PKCE (default true) +token_auth = "client_secret_post" # it sends the secret in the form (default client_secret_basic) +``` + +Set only what the app needs, and say in a comment why. Find out from the +app's documentation or source: the callback path it puts in `redirect_uri` +(sometimes built in the browser, e.g. `/auth/openid/`; then +pick the key so the path is known), whether it sends `code_challenge`, +and how it sends the secret. Authelia checks the redirect URI when the +sign-in starts (an error page instead of its login page if it's wrong), but +PKCE and the secret only after the person has signed in, so a curl of the +authorize URL can't show those are right: a real sign-in can. Changing +`[sso]` and deploying registers the client again; Authelia restarts for it +(a few seconds of 404s from it, which an app checking discovery at startup +may log; it should retry). - Scopes: `openid profile email groups`. Userinfo gives `sub`, `preferred_username`, `name`, `email`, `groups` (the person's Core groups: use them for roles, e.g. admins). @@ -192,7 +214,10 @@ The Core's AI features (offering tools to its AI agent, or using its model), extra services such as Redis or a second container, extra hostnames, and public ports other than HTTPS. If the app can't work without one of these, say so plainly in your report -rather than working around it; the gap is useful to know. If it's optional +rather than working around it; the gap is useful to know. The same goes for +a need that doesn't fit the app (e.g. a sign-in `[sso]` can't describe): +report it rather than writing a proxy, bridge or second service into the +app's container. If it's optional (e.g. email notifications), leave it off and note it. ## Workflow @@ -236,7 +261,23 @@ and make the Dockerfile fit the Core: resets, notifications): map `SMTP_*` onto its mail settings. - **Read settings from the environment**, mapping the Core's names to the app's in an entrypoint script or config file if they differ - (`SECRET_KEY="$APP_SECRET"`, `DATABASE_URL=...`). + (`SECRET_KEY="$APP_SECRET"`, `DATABASE_URL=...`). Set the app's own + variables outright rather than "only if unset": upstream images often set + defaults in `ENV` (a SQLite path, a port) that would win otherwise. +- **Images without a shell** (built `FROM scratch` or distroless) can't run + an entrypoint script, and `coreapp shell` can't open one. Copy a static + busybox in and run the script with it: + + ```dockerfile + FROM busybox:1.37-musl AS busybox + FROM upstream/image:1.2.3 + COPY --from=busybox /bin/busybox /bin/busybox + COPY entrypoint.sh /entrypoint.sh + ENTRYPOINT ["/bin/busybox", "sh", "/entrypoint.sh"] + ``` + + (end it with `exec` and the upstream entrypoint; call tools as + `/bin/busybox mkdir ...`). Prefer this to a program of your own. - **Run as a non-root user** if the image allows. `/data` is given to whatever user the image runs as, so this is enough: diff --git a/templates/app/README.md b/templates/app/README.md index e508f91..4e8e5c3 100644 --- a/templates/app/README.md +++ b/templates/app/README.md @@ -42,7 +42,8 @@ keep its values and add new ones): `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 -`OIDC_CLIENT_SECRET`; `needs = ["email"]` adds `SMTP_HOST`, `SMTP_PORT` +`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 `SMTP_FROM` (`{{NAME}}@`): the app's own account on the Core's mail server, for sending. diff --git a/templates/app/coreapp.toml b/templates/app/coreapp.toml index 4f5e282..6f6e730 100644 --- a/templates/app/coreapp.toml +++ b/templates/app/coreapp.toml @@ -23,3 +23,9 @@ health = "/" # What it needs from the Core: "postgres" or "mysql" (its own database), "sso" # (sign-in with Core accounts through Authelia), "email" (sending mail) needs = [] + +# With "sso": only if the app's sign-in can't use the defaults +# [sso] +# 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"