diff --git a/PLAN.md b/PLAN.md index 368ed5c..fb09808 100644 --- a/PLAN.md +++ b/PLAN.md @@ -67,6 +67,14 @@ What we learned provisioning (2026-12-02/03): `uniqueMember`. `groups_filter: (uniqueMember={dn})` and `group_name: cn` would give apps `admins`/`everybody` (checked 2026-12-03 on dev.fedcom.net's LDAP; not changed there) + - Authelia 4.39 puts `email`, `name` and `preferred_username` only in + userinfo. Apps that read the person only from the ID token (Leantime) + fail every sign-in without a patch. A claims policy in + `idproviders.yml` (`identity_providers.oidc.claims_policies` with + `id_token: [email, email_verified, name, preferred_username, + groups]`), named by each client's `claims_policy`, would fix it for + all apps. coreapps doesn't add it: it would edit Federated's part of + the file, and a client naming a policy that's gone stops Authelia - On this image, disabling systemd-resolved isn't enough: networkd's `systemd-networkd-resolve-hook.socket` starts it at boot, it takes port 53 and pdns can't start after a reboot. coreapp-dev masks it @@ -523,6 +531,30 @@ Steps: - Decided 2026-12-04 (David): apps call the Core's sign-in "Core SSO" or "Authelia" (provider name, button text: "Sign in with Core SSO"). In the skill, sign-in.md, porting.md and the sso examples + - Rehearsed 2026-12-04 with Leantime (upstream PHP image; postgres, + sso, email; it chose PostgreSQL over MySQL, as the skill says, so + `mysql` is still unrehearsed): deployed at + `https://leantime.dev.fedcom.net/`, signed in (the test account + read-only), admin rule by a trigger on the admin's row, a password + reset read with `coreapp inbox`, data kept by `--recreate`. Two + patches to Leantime: claims from userinfo (it reads only the ID + token) and no sample project for read-only newcomers (its first + page was a 403). Fixed from it: deploy waited 30 s and said + "Updated" when the image's own HEALTHCHECK failed (Leantime + refused 127.0.0.1 after trusted proxies were set) and traefik + didn't route it; it now waits while Docker says "starting", stops + on "unhealthy" with the check and its last result (an update rolls + back; a first install says it stays installed), and a rollback + waits until the old version is routed again. `coreapp signin` + follows a page's one "Core SSO"/"Authelia" link like a button, + prints the app's visible error when it doesn't end signed in, and + has `--help`. Skill: 127.0.0.1 among trusted proxies, the image's + HEALTHCHECK, `COPY --chmod`, `$TMPDIR` outside the sandbox, + `coreapp shell`'s user, patching an app's OIDC code for userinfo + claims, testing a new account's first sign-in + - [ ] David: sign in to leantime as admin@dev.fedcom.net (owner; + a project, a task, an upload); remove it when done + - [ ] A MySQL-only app, to rehearse `mysql` - [ ] David: sign in to listmonk-app as admin@dev.fedcom.net (Super Admin, Settings), and send a campaign from `listmonk-app@dev.fedcom.net`; remove it when done diff --git a/TEST.md b/TEST.md index 689a906..8b9cb75 100644 --- a/TEST.md +++ b/TEST.md @@ -249,6 +249,15 @@ The Core's own scripts trace secrets, so their output goes to Comparison is numeric (`"17.10"` is newer than 17.6); `min_version = 17.4` (a TOML number with a dot) and `">=18"` are refused with a hint; `[mysql]` has no `extensions`. +5f. An image with its own failing `HEALTHCHECK` (`coreapp new x`, then + `HEALTHCHECK --interval=3s --retries=2 CMD ["false"]` in the + Dockerfile): a new install stops with "Docker says x is unhealthy, so + traefik doesn't route ... (CMD false); its last result: exit code 1" + and "x is installed but not working. Deploying again updates it ...". + With a passing check (`wget -qO /dev/null http://127.0.0.1:8080/`) it + deploys; breaking it again in an update gives the same message with + the wget error, rolls back, and right after "Rolled back" the public + address answers 200 (the rollback waits for traefik). 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 @@ -433,9 +442,21 @@ has the `DB_*` variables, `.coreapp` says `needs=postgres`. `coreapp signin /signin` shows `POST .../signin/core (the form's button "Sign in with ...") -> 303`, then signs in. `--form /signin/core /signin`: the same. `--form /nope /signin`: "has no form with action - /nope (its forms: /signin, /signin/core)". sso-demo's `/` (a link, not - a form): "didn't lead to the Core's sign-in". A page with two - hidden-only forms: "several forms ... pick one with --form". + /nope (its forms: /signin, /signin/core)". A page whose only link to + sign-in doesn't name Core SSO (sso-demo deployed before the label, + "Sign in with your Core account" at `/`): "didn't lead to the Core's + sign-in". A page with two hidden-only forms: "several forms ... pick + one with --form". +11b. A sign-in link: Leantime's `/auth/login` (a password form and a link + "Sign in with Core SSO" to `/oidc/login`): `coreapp signin + /auth/login` shows `GET .../oidc/login (the link "Sign in with Core + SSO") -> 302` and signs in. In the module, `pick_link` finds a link by + its text, title or aria-label (Core SSO or Authelia), follows two + links to the same address, and none when two name different ones. + `page_says` gives the text of elements whose class, id or role says + alert, error, notice and the like (`' The page says: "..."'`), and '' + without one; the "Not signed in" messages after the app end with it. + `coreapp signin --help` prints signin's part of `coreapp help`. 11a. A callback that fails quietly: an app whose callback sends the browser back to its sign-in page (Miniflux with group mapping on, or its sign-in page replayed through `signin.main` with `follow` replaced): "Not diff --git a/bin/coreapp b/bin/coreapp index c940dac..2ca3799 100755 --- a/bin/coreapp +++ b/bin/coreapp @@ -25,8 +25,10 @@ # coreapp signin [path] sign in to it with the Core's test account, as a # browser would, starting at path (default /login; # a page whose button starts sign-in is pressed, -# --form picks the form); --cookies -# keeps the app's cookies +# --form picks the form, or its one +# "Core SSO" link followed; if it fails, the app's +# error is shown); --cookies keeps the +# app's cookies # coreapp signin --code for sign-in started in the browser's JavaScript: # get a code for the app's callback from Authelia # coreapp signin --remove-account @@ -394,6 +396,10 @@ cmd_signin() { --form) [[ $# -ge 2 ]] || die "--form needs the form's action: coreapp signin --form /signin/core /signin" form="$2"; shift ;; + -h|--help) + sed -n '/^# coreapp signin \[path\]/,/^# coreapp signin --remove-account/{s/^# \{0,1\}//;p}' "${BASH_SOURCE[0]}" + echo " remove the test account from the Core" + return ;; --remove-account) init_core; sync_installer core "$REMOTE_INSTALLER/coreapps test-account --remove" diff --git a/core/coreapps b/core/coreapps index db2a0b6..f9fc73b 100755 --- a/core/coreapps +++ b/core/coreapps @@ -1039,8 +1039,13 @@ def install_app(m, p, folder, origin, addon_ok, recreate): run_logged([FEDERATED + "/bin/installapp", "-n", name], log, "installapp failed") # installapp's start step only knows Federated's own apps compose_up(m, log) - wait_until_answering(m, p) - wait_for_route(m, p) + try: + wait_until_answering(m, p) + wait_for_route(m, p) + except Refused as e: + # A new app has nothing to roll back to: it stays installed + raise Refused(f"{e}\n{name} is installed but not working. Deploying again " + f"updates it (its data and database stay); removing it deletes them.") else: before = service_value(f"{APPS}/{name}/.env", "IMAGE_VERSION") if before == m["version"]: @@ -1356,6 +1361,13 @@ def roll_back(m, p, backup, log): stdout=f, stderr=subprocess.STDOUT) if result.returncode != 0: problems.append("starting the old version") + else: + # Until people can reach it again (traefik waits for the image's + # HEALTHCHECK, if it has one) + try: + wait_for_route(m, p) + except Refused: + problems.append("the old version is unhealthy too") # The new version's image, unless it's the same tag as the old one if old and (old["image"], old["version"]) != (m["image"], m["version"]): run(["docker", "image", "rm", f"{m['image']}:{m['version']}"]) @@ -1457,14 +1469,50 @@ def wait_for_route(m, p): # wait for traefik to give the same, not for "not 404") direct = status("-H", f"Host: {host}", "-H", "X-Forwarded-Proto: https", f"http://{p['address']}:{m['port']}{m['health']}") - for _ in range(30): + # traefik leaves out containers whose image's own HEALTHCHECK says + # they're starting or unhealthy: wait while it's starting, and stop on + # unhealthy (the route would never come) + started = time.monotonic() + while time.monotonic() - started < 180: code = status("--resolve", f"{host}:443:{traefik}", f"https://{host}{m['health']}") if code == direct or code not in ("", "000", "404", "502", "503"): return - time.sleep(1) + health = container_health(m["name"]) + if health == "unhealthy": + raise Refused(unhealthy_message(m, host)) + if health != "starting" and time.monotonic() - started > 30: + break + time.sleep(2) say(f"Note: traefik doesn't route https://{host}/ to it yet; it may take a moment.") +def container_health(name): + """Docker's health status from the image's HEALTHCHECK: "starting", + "healthy", "unhealthy", or "" if the image has none.""" + return run(["docker", "inspect", "-f", + "{{if .State.Health}}{{.State.Health.Status}}{{end}}", name]).stdout.strip() + + +def unhealthy_message(m, host): + out = run(["docker", "inspect", "-f", "{{json .Config.Healthcheck}}|{{json .State.Health}}", + m["name"]]).stdout + try: + check, _, health = out.partition("|") + test = " ".join(json.loads(check)["Test"]) + log = json.loads(health).get("Log") or [] + last = log[-1] if log else {} + result = f"exit code {last.get('ExitCode')}" + ( + f", {' '.join(str(last.get('Output', '')).split())[-300:]}" + if str(last.get("Output", "")).strip() else "") + except (ValueError, KeyError, TypeError, AttributeError): + test, result = "?", "?" + return (f"Docker says {m['name']} is unhealthy, so traefik doesn't route https://{host}/ " + f"to it. The check is the image's own HEALTHCHECK, run inside the container " + f"({test}); its last result: {result}. If the app answers that check with an " + "error (e.g. it refuses requests from 127.0.0.1 because of a trusted-proxies " + "setting), fix that, or the HEALTHCHECK in the Dockerfile.") + + def update(name, addon_ok): """An app installed from a repository, to its newest release.""" if not re.fullmatch(FIELDS["name"], name) or not is_ours(name): diff --git a/lib/signin.py b/lib/signin.py index 98aab1a..9d1d7e9 100644 --- a/lib/signin.py +++ b/lib/signin.py @@ -9,7 +9,9 @@ signin.py [--cookies FILE] [--form ACTION] and say where it ended. If start-url is a page whose form starts sign-in (a button, with hidden fields only, e.g. a CSRF token), submit it, as a person pressing the button would: the only such form, or the one whose - action is ACTION. + action is ACTION. Without such a form, follow its one link whose text + names Core SSO or Authelia. When it doesn't end signed in, it prints + the error or notice the app's page shows. signin.py --code [--pkce] For apps whose sign-in starts in the browser's JavaScript: start at Authelia's authorization with the app's client, sign in, and stop at the @@ -120,6 +122,92 @@ class Forms(html.parser.HTMLParser): self.form["button"] = (self.form["button"] + " " + data.strip()).strip() +class Links(html.parser.HTMLParser): + """The page's links that start sign-in with the Core: their text (or + title or aria-label) names Core SSO or Authelia, as Coreapps label it.""" + NAMES = re.compile(r"core\s*sso|authelia", re.I) + + def __init__(self): + super().__init__() + self.found, self.href, self.text = [], None, "" + + def handle_starttag(self, tag, attrs): + if tag == "a": + a = dict(attrs) + self.href = a.get("href") + self.text = " ".join(filter(None, [a.get("title"), a.get("aria-label")])) + + def handle_data(self, data): + if self.href is not None: + self.text += " " + data + + def handle_endtag(self, tag): + if tag == "a" and self.href is not None: + text = " ".join(self.text.split()) + if self.NAMES.search(text) and not self.href.startswith(("#", "javascript:")): + self.found.append((self.href, text)) + self.href = None + + +def pick_link(page_url, body): + """(url, label) for the page's one Core SSO link, or None.""" + parser = Links() + parser.feed(body.decode(errors="replace")) + urls = {} + for href, text in parser.found: + urls.setdefault(urllib.parse.urljoin(page_url, href), text) + if len(urls) != 1: + return None + url, text = next(iter(urls.items())) + return url, f"the link \"{text[:60]}\"" + + +class Messages(html.parser.HTMLParser): + """Text the page shows as an error or notice: elements whose class, id + or role says alert, error, notice, flash or the like.""" + KINDS = re.compile(r"alert|error|danger|warning|notice|notification|flash|toast|invalid", re.I) + VOID = {"br", "img", "input", "meta", "link", "hr", "wbr", "source"} + + def __init__(self): + super().__init__() + self.depth, self.parts, self.found = 0, [], [] + + def handle_starttag(self, tag, attrs): + if tag in self.VOID: + return + if self.depth: + self.depth += 1 + return + a = dict(attrs) + marks = " ".join(filter(None, [a.get("class"), a.get("id"), a.get("role")])) + if tag not in ("script", "style", "template") and self.KINDS.search(marks): + self.depth, self.parts = 1, [] + + def handle_endtag(self, tag): + if tag in self.VOID or not self.depth: + return + self.depth -= 1 + if not self.depth: + text = " ".join(" ".join(self.parts).split()) + if text and text not in self.found: + self.found.append(text) + + def handle_data(self, data): + if self.depth: + self.parts.append(data) + + +def page_says(body): + """' The page says: "..."' with its visible error or notice, or ''.""" + parser = Messages() + try: + parser.feed(body.decode(errors="replace")) + except Exception: + return "" + text = "; ".join(parser.found)[:300] + return f' The page says: "{text}".' if text else "" + + def pick_form(page_url, body, wanted): """(url, data, label) for the form that starts sign-in, or None.""" parser = Forms() @@ -221,6 +309,14 @@ def follow(browser, url, username, password, stop_at=None, form=None): browser.signin_urls.append(url) submitted = True continue + if not signed_in and not submitted and status == 200 and not form: + # Or whose link does ("Sign in with Core SSO") + picked = pick_link(url, body) + if picked: + url, label = picked + browser.signin_urls.append(url) + submitted = True + continue return url, status, body, signed_in raise SystemExit(f"Not signed in: more than {MAX_STEPS} redirects.") @@ -285,14 +381,16 @@ def main(args): if not signed_in: raise SystemExit( f"Not signed in: {shown(start)} didn't lead to the Core's sign-in (it ended at " - f"{shown(last)}, HTTP {status}). Give the app's path that starts sign-in, or its sign-in " - "page with --form for a form; if the app starts it in the browser's " - "JavaScript, use --code.") + f"{shown(last)}, HTTP {status}).{page_says(body)} Give the app's path that starts " + "sign-in, or its sign-in page (a button is pressed, a \"Core SSO\" link followed; " + "--form picks a form); if the app starts it in the browser's JavaScript, " + "use --code.") if urllib.parse.urlsplit(last).netloc != app.netloc: raise SystemExit(f"Not signed in: it ended at {shown(last)} (HTTP {status}), not at the app.") if status >= 400: raise SystemExit(f"Not signed in: Authelia accepted the test account, but the app answered " - f"HTTP {status} at {shown(last)} (coreapp logs says why).") + f"HTTP {status} at {shown(last)}.{page_says(body)} (coreapp logs may say " + "more.)") text = re.sub(rb"<[^>]+>", b" ", body).decode(errors="replace") mentions = username.split("@")[0] in text # Back at the app isn't signed in if the app's page offers sign-in again @@ -306,8 +404,8 @@ def main(args): if offers and not mentions: raise SystemExit( f"Not signed in: Authelia accepted the test account, but the app ended at " - f"{shown(last)}, which offers sign-in again: its callback didn't sign the person in " - "(coreapp logs says why).") + f"{shown(last)}, which offers sign-in again: its callback didn't sign the person " + f"in.{page_says(body)} (coreapp logs may say more.)") if cookies: jar.save(ignore_discard=True, ignore_expires=True) print(f"Signed in: back at the app, {shown(last)} answered HTTP {status}.") diff --git a/skills/coreapp/SKILL.md b/skills/coreapp/SKILL.md index a2edc63..124d5c1 100644 --- a/skills/coreapp/SKILL.md +++ b/skills/coreapp/SKILL.md @@ -406,7 +406,16 @@ Common causes: each means is at the end of [references/sign-in.md](references/sign-in.md). - Permission denied under `/data`: the app switches to another user after starting (the Core gives `/data` to the image's `USER`), or it writes - somewhere else in the container (`coreapp shell 'id; ls -ld /data'`). + somewhere else in the container (`coreapp shell 'id; ls -ld /data'`; + `coreapp shell` runs as the image's user). +- "Docker says is unhealthy": the image's own `HEALTHCHECK` fails + inside the container, so traefik won't route it; the message has the + check and its result (often the app refusing 127.0.0.1, see the porting + checklist). An update rolls back; a first install stays, so deploy again + once it's fixed. +- `coreapp` runs outside the sandbox, where `$TMPDIR` is another folder: + keep a file you pass between your shell and `coreapp` (or `docker cp`) + in the app's folder, not in `$TMPDIR`. The installer's own log (the Core's install scripts) is on the Core in `/federated/logs/coreapps/`. It contains secrets, so don't print it in full; diff --git a/skills/coreapp/references/porting.md b/skills/coreapp/references/porting.md index c25468a..43221c0 100644 --- a/skills/coreapp/references/porting.md +++ b/skills/coreapp/references/porting.md @@ -12,7 +12,11 @@ SKILL.md), and make the Dockerfile fit the Core: `X-Forwarded-Proto: https` and `X-Forwarded-For`: set the app's "trusted proxies" to `CORE_PROXY` (so it logs and rate-limits by the real client address), and turn on its "behind HTTPS" or secure-cookie setting if it - has one, since it sees plain HTTP itself. + has one, since it sees plain HTTP itself. If that setting also refuses + requests from other addresses, add `127.0.0.1`: an image's own + `HEALTHCHECK` runs inside the container, and while Docker calls the + container unhealthy, traefik doesn't route to it (deploy stops and says + so). - **Keep state in `/data`**: point upload folders, SQLite files and generated keys there. If the app needs a directory structure under `/data`, create it at startup (it starts empty). @@ -71,6 +75,12 @@ SKILL.md), and make the Dockerfile fit the Core: (end it with `exec` and the upstream entrypoint; call tools as `/bin/busybox mkdir ...`). Prefer this to a program of your own. +- **Check the image's own `HEALTHCHECK`** (`docker inspect -f + '{{json .Config.Healthcheck}}' `): it decides whether traefik + routes to the app, so it has to pass with the app's Core settings. +- **`COPY --chmod`** into a folder that doesn't exist yet makes that folder + with the same mode, so a `0644` file gets an unreadable parent folder: + copy into an existing folder, or `RUN chmod` afterwards. - **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/skills/coreapp/references/sign-in.md b/skills/coreapp/references/sign-in.md index f3d608a..62b68a1 100644 --- a/skills/coreapp/references/sign-in.md +++ b/skills/coreapp/references/sign-in.md @@ -58,7 +58,14 @@ standard-library Python example of the whole flow (`oidc.py`). (the account's uid, e.g. `coreapp.test`), `preferred_username` (the email address, which is what people sign in with), `groups`. The ID token has none of them, so an app that reads the person only from the ID token - gets no email or name: turn on its "use userinfo" setting. + gets no email or name: turn on its "use userinfo" setting. Requesting + fewer scopes doesn't help (without `openid`, userinfo answers 403). If + the app has no such setting, a small patch to its OIDC code that fills + missing claims from userinfo (when its `sub` matches the ID token's) is + fine: keep it as a patch file applied in the Dockerfile, say why in a + comment, and name it in your report, since it's the app's own code. (The + Core could put these claims in the ID token; that's Federated's to + change.) - `groups` is `null` on today's Cores, not a list: they have two groups, `admins` and `everybody`, but Authelia's settings don't find them yet (for Federated to fix). Don't turn on an app's group-to-role mapping: @@ -119,6 +126,7 @@ says whether it got back to the app signed in. Run it in the app's folder coreapp signin # starts at /login coreapp signin /auth/login # the app's own page that starts sign-in coreapp signin /signin # a page whose button starts sign-in: pressed +coreapp signin /auth/login # or whose "Sign in with Core SSO" link starts it: followed jar=$(mktemp) && coreapp signin --cookies "$jar" /login && curl -b "$jar" https://./api/me ``` @@ -126,14 +134,21 @@ jar=$(mktemp) && coreapp signin --cookies "$jar" /login && curl -b "$jar" https: CSRF token) is submitted as a person pressing it would. Forms with fields to fill (a password form beside the button) are ignored, so a page with one button and a password form needs nothing more; only with several - buttons, pick one with `--form `. Don't add routes to the app just - for the test. + buttons, pick one with `--form `. Without such a form, its one + link whose text names Core SSO or Authelia is followed. Don't add routes + to the app just for the test. - With `--cookies`, check what the test account may do: it should land as a read-only member. Keep the jar's path in one command, as above (`$TMPDIR` can differ between a sandboxed shell and `coreapp`'s). - "Signed in" needs the app to have kept the person: if its page offers sign-in again (its callback failed quietly), `coreapp signin` says "Not - signed in ... offers sign-in again"; `coreapp logs` has the app's reason. + signed in ... offers sign-in again", with the error or notice the app's + page shows; `coreapp logs` may have more. +- Test a brand-new account's first sign-in too, not only the second: apps + often do extra work for a new person (a sample project, onboarding) that + a read-only role isn't allowed. The test account stays in the app after + its first sign-in, so to repeat it, delete its user in the app (as the + app's admin, or in its database with `coreapp shell`) and sign in again. - Apps whose sign-in starts in the browser's JavaScript (single-page apps: the page builds the authorize URL itself): `coreapp signin --code` starts at Authelia with the app's client and stops at the app's callback,