From dcc72fe5daf30e1bf03d94ca3aeddb066b19171d Mon Sep 17 00:00:00 2001 From: David Young Date: Thu, 3 Dec 2026 18:22:42 -0700 Subject: [PATCH] Fixes from porting Supermarket: sign-in buttons, CORE_DOMAIN, skill gaps An agent ported Supermarket with only the skill. coreapp signin now presses a sign-in page's button (a form with only hidden fields; --form picks one), every app gets CORE_DOMAIN, and the skill covers apps that also run elsewhere, IMAGE_VERSION instead of build args, deriving keys from APP_SECRET, the first admin, apps with their own client setup, and that the groups claim is empty on today's Cores. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 29 +++++++++- TEST.md | 12 +++- bin/coreapp | 15 +++-- core/templates/env.in | 2 + lib/signin.py | 120 ++++++++++++++++++++++++++++++++++++---- skills/coreapp/SKILL.md | 41 ++++++++++++-- templates/app/README.md | 1 + 7 files changed, 196 insertions(+), 24 deletions(-) diff --git a/PLAN.md b/PLAN.md index c04cf64..adefa18 100644 --- a/PLAN.md +++ b/PLAN.md @@ -58,6 +58,12 @@ What we learned provisioning (2026-12-02/03): mail server also has no `SPOOF_PROTECTION`, so any account can send as any address. coreapps gives each app its own sending-only account instead (see Coreapps, step 4) + - Authelia's `groups` claim is always empty: its LDAP settings look + for `(member={dn})` with names from `gidNumber`, but the Core's + groups (`admins`, `everybody`) are `groupOfUniqueNames` with + `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) - 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 @@ -381,8 +387,27 @@ Steps: a wrong callback shows Authelia's hint - [ ] Hide the test account from Superpanel's users (HIDDEN_USERS, as `fcore`), if it bothers anyone; it only exists on dev Cores - - [ ] Test it with David's candidate app: an agent in that repository - uses the skill; what it struggles with becomes fixes + - Tested 2026-12-03 with David's candidate app, Supermarket (Go; its + server edition already had Postgres, mail, users and Core sign-in), by + an agent given only the skill, in a clone (commit 24338c7 there, not + in David's repository). Deployed at `https://supermarket.dev.fedcom.net/` + with postgres, sso (`[sso] callback = "/auth/core/callback"`, + `token_auth = "client_secret_post"`) and email; `coreapp check`, + `coreapp signin`, data kept by `--recreate`. Fixed from its findings: + `coreapp signin` presses a sign-in page's button (a POST form with only + hidden fields, such as a CSRF token; `--form ` picks one), so + the agent's extra GET route isn't needed; `CORE_DOMAIN` in every app's + `.env` (the Core's domain, set only on a Core; updates add it); the + skill now says: apps that also run elsewhere choose Core behaviour on + `CORE_DOMAIN` without changing the Dockerfile for everyone; no build + args (read `IMAGE_VERSION`); `APP_SECRET` isn't key bytes (hash it) and + lives only in `.env`; `groups` is empty today (see "Tell Federated"); + the first admin comes from a setup link in the log, not whoever signs + in first; apps with their own client-setup step take `OIDC_*` + instead; icons under 80 pixels get a note + - [ ] David: the agent's changes, for Supermarket's own repository + (and a login CSRF it noticed in the app's sign-in: its OIDC state + isn't tied to a browser cookie) 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 diff --git a/TEST.md b/TEST.md index b15c751..8c2b9ae 100644 --- a/TEST.md +++ b/TEST.md @@ -192,7 +192,9 @@ The Core's own scripts trace secrets, so their output goes to `docker-compose.yml.in`, `env.in`, `install`, `uninstall`, `icon.png`, `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 + random `APP_SECRET`, and `CORE_DOMAIN` the Core's domain (an app + installed before `CORE_DOMAIN` existed gets it on its next update). + 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). @@ -344,6 +346,14 @@ has the `DB_*` variables, `.coreapp` says `needs=postgres`. bans after three). `coreapp signin --remove-account`: "Removed", then "There's no test account"; `coreapp signin` makes it again. `coreapps test-account` with less than 16 characters on stdin: refused. +11. A sign-in page with a button (Supermarket's `/signin`: a password + form, and a POST form to `/signin/core` with only hidden fields): + `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". ### With mysql diff --git a/bin/coreapp b/bin/coreapp index c065cf4..c72dfe1 100755 --- a/bin/coreapp +++ b/bin/coreapp @@ -14,8 +14,10 @@ # coreapp logs [-f] its log # coreapp shell [command] a shell in its container, or run one command there # coreapp signin [path] sign in to it with the Core's test account, as a -# browser would, starting at path (default /login); -# --cookies keeps the app's cookies +# 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 # 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 @@ -346,19 +348,22 @@ cmd_shell() { # test-account) gets a new random password each time, given to the Core and # to signin.py on stdin, and kept nowhere cmd_signin() { - local path="" cookies="" code=0 domain password account issuer client pkce + local path="" cookies="" form="" code=0 domain password account issuer client pkce while [[ $# -gt 0 ]]; do case "$1" in --code) code=1 ;; --cookies) [[ $# -ge 2 ]] || die "--cookies needs a file: coreapp signin --cookies [path]" cookies="$2"; shift ;; + --form) + [[ $# -ge 2 ]] || die "--form needs the form's action: coreapp signin --form /signin/core /signin" + form="$2"; shift ;; --remove-account) init_core; sync_installer core "$REMOTE_INSTALLER/coreapps test-account --remove" return ;; /*) [[ -z "$path" ]] || die "One path: coreapp signin [path]"; path="$1" ;; - *) die "coreapp signin [--cookies ] [path], coreapp signin --code, or coreapp signin --remove-account (a path starts with /)" ;; + *) die "coreapp signin [--cookies ] [--form ] [path], coreapp signin --code, or coreapp signin --remove-account (a path starts with /)" ;; esac shift done @@ -380,7 +385,7 @@ cmd_signin() { printf '%s' "$password" | python3 "$SIGNIN" --code "${pkce[@]}" \ "$issuer" "$client" "https://$NAME.$domain$SSO_CALLBACK" "$account" else - printf '%s' "$password" | python3 "$SIGNIN" ${cookies:+--cookies "$cookies"} \ + printf '%s' "$password" | python3 "$SIGNIN" ${cookies:+--cookies "$cookies"} ${form:+--form "$form"} \ "https://$NAME.$domain${path:-/login}" "$account" fi } diff --git a/core/templates/env.in b/core/templates/env.in index d7d700b..d53c301 100644 --- a/core/templates/env.in +++ b/core/templates/env.in @@ -2,4 +2,6 @@ # (secrets don't change) and add settings a new version needs. IMAGE_VERSION=@VERSION@ APP_URL=https://{{NAME}}.@DOMAIN@ +# The Core's domain; set only on a Core, so an app can tell it runs on one +CORE_DOMAIN=@DOMAIN@ APP_SECRET=@APP_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ diff --git a/lib/signin.py b/lib/signin.py index 587f782..fa1bcae 100644 --- a/lib/signin.py +++ b/lib/signin.py @@ -3,10 +3,13 @@ Used by `coreapp signin`; the password comes on stdin. -signin.py [--cookies FILE] +signin.py [--cookies FILE] [--form ACTION] Open start-url (the app's page that starts sign-in), follow the redirects to the Core's Authelia, sign in, follow them back to the app, - and say where it ended. + 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. 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 @@ -18,6 +21,7 @@ Exits 0 when signed in, 1 when not. import base64 import hashlib +import html.parser import http.cookiejar import json import re @@ -61,7 +65,7 @@ class Browser: """(status, Location or "", body) for one request, no redirects.""" req = urllib.request.Request(url, data=data, headers={ "User-Agent": "coreapp-signin", "Accept": "text/html,application/json,*/*", - **(headers or {})}) + **{k: v for k, v in (headers or {}).items() if v}}) try: with self.opener.open(req, timeout=30) as r: return r.status, "", r.read(200_000) @@ -70,6 +74,78 @@ class Browser: return e.code, urllib.parse.urljoin(url, location) if location else "", e.read(200_000) +class Forms(html.parser.HTMLParser): + """The forms on a page: method, action, hidden values, whether a person + has to fill something in, and the button's text.""" + FILLED = {"hidden", "submit", "button", "image", "reset"} + + def __init__(self): + super().__init__() + self.forms = [] + self.form = None + self.in_button = False + + def handle_starttag(self, tag, attrs): + a = dict(attrs) + if tag == "form": + self.form = {"method": (a.get("method") or "get").lower(), + "action": a.get("action") or "", "fields": [], + "to_fill": False, "button": ""} + self.forms.append(self.form) + elif self.form is None: + return + elif tag == "input": + kind = (a.get("type") or "text").lower() + if kind == "hidden" and a.get("name"): + self.form["fields"].append((a["name"], a.get("value") or "")) + elif kind not in self.FILLED: + self.form["to_fill"] = True + elif kind == "submit" and not self.form["button"]: + self.form["button"] = a.get("value") or "" + elif tag in ("textarea", "select"): + self.form["to_fill"] = True + elif tag == "button": + self.in_button = True + + def handle_endtag(self, tag): + if tag == "form": + self.form = None + elif tag == "button": + self.in_button = False + + def handle_data(self, data): + if self.form is not None and self.in_button and data.strip(): + self.form["button"] = (self.form["button"] + " " + data.strip()).strip() + + +def pick_form(page_url, body, wanted): + """(url, data, label) for the form that starts sign-in, or None.""" + parser = Forms() + parser.feed(body.decode(errors="replace")) + for f in parser.forms: + f["url"] = urllib.parse.urljoin(page_url, f["action"]) + if wanted: + target = urllib.parse.urljoin(page_url, wanted) + forms = [f for f in parser.forms if f["url"].split("?")[0] == target.split("?")[0]] + if not forms: + actions = ", ".join(sorted({urllib.parse.urlsplit(f["url"]).path for f in parser.forms})) + raise SystemExit(f"Not signed in: {shown(page_url)} has no form with action {wanted}" + f" (its forms: {actions or 'none'}).") + else: + forms = [f for f in parser.forms if not f["to_fill"]] + if len(forms) > 1: + actions = ", ".join(urllib.parse.urlsplit(f["url"]).path for f in forms) + raise SystemExit(f"Not signed in: {shown(page_url)} has several forms that could start " + f"sign-in ({actions}): pick one with --form .") + if not forms: + return None + f = forms[0] + data = urllib.parse.urlencode(f["fields"]) + if f["method"] == "post": + return f["url"], data.encode(), f"the form's button \"{f['button']}\"" + return f["url"].split("?")[0] + ("?" + data if data else ""), None, f"the form's button \"{f['button']}\"" + + def sign_in(browser, portal_url, username, password): """Authelia's login page reached: sign in with its API, as its page does. Returns where Authelia sends the browser next.""" @@ -96,16 +172,27 @@ def sign_in(browser, portal_url, username, password): return urllib.parse.urljoin(origin, (reply.get("data") or {}).get("redirect", "") or "/") -def follow(browser, url, username, password, stop_at=None): +def follow(browser, url, username, password, stop_at=None, form=None): """Follow a browser's way from url. Returns (last url, status, body, whether it signed in at Authelia).""" auth_host = None signed_in = False + submitted = False + data, label, referer = None, "", None for _ in range(MAX_STEPS): if stop_at and url.startswith(stop_at): return url, None, b"", signed_in - status, location, body = browser.request(url) - print(f" GET {shown(url)} -> {status}") + if data is not None: + parts = urllib.parse.urlsplit(url) + status, location, body = browser.request(url, data, { + "Content-Type": "application/x-www-form-urlencoded", + "Origin": f"{parts.scheme}://{parts.netloc}", "Referer": referer}) + print(f" POST {shown(url)} ({label}) -> {status}") + data = None + else: + status, location, body = browser.request(url) + print(f" GET {shown(url)}{f' ({label})' if label else ''} -> {status}") + label = "" err = errors(location or url) if err: raise SystemExit("Not signed in: " + ", ".join(f"{k}: {v}" for k, v in err.items())) @@ -123,6 +210,14 @@ def follow(browser, url, username, password, stop_at=None): url = sign_in(browser, url, username, password) signed_in = True continue + if not signed_in and not submitted and status == 200 and b" for 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: diff --git a/skills/coreapp/SKILL.md b/skills/coreapp/SKILL.md index 31533f7..3d8e213 100644 --- a/skills/coreapp/SKILL.md +++ b/skills/coreapp/SKILL.md @@ -52,7 +52,14 @@ What the Core gives every app: |---|---| | `APP_URL` | `https://.`, the app's public address | | `APP_SECRET` | 32 random letters and digits, for signing cookies, sessions | - | `IMAGE_VERSION` | The installed version | + | `IMAGE_VERSION` | The installed version (`coreapp deploy` builds with plain `docker build .`, no build args, so read the version from here, not a build-time `VERSION`) | + | `CORE_DOMAIN` | The Core's domain (``). Set only on a Core: an app that also runs elsewhere can use it to tell | + + `APP_SECRET` isn't hex or base64: an app that wants key bytes (e.g. 32 + bytes for encryption) derives them, e.g. SHA-256 of `APP_SECRET`. It + never changes, and it lives only in the app's `.env` on the Core + (`/federated/apps//.env`, beside `/data`): anything encrypted with + it is unreadable without that file. plus the ones each need adds (below). @@ -176,8 +183,14 @@ authorize URL can't show those are right: `coreapp signin` can (see (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). + `preferred_username`, `name`, `email`, and `groups`, which is empty on + today's Cores: they have two groups, `admins` and `everybody`, but + Authelia's settings don't find them yet (for Federated to fix). Read `groups` + if the app can use it, but don't depend on it for roles. +- The app's first admin: not "whoever signs in first" (any employee could + be first). Prefer a one-time setup link or code the app prints in its log + (`coreapp logs`, or `coreapp shell ''`), then admins it + names in its own settings. Later, the Core's `admins` group. - Discovery: `$OIDC_ISSUER/.well-known/openid-configuration`. The Core routes `authelia.` from inside the app's container to the real HTTPS endpoint, with a valid certificate, so normal TLS verification works. @@ -186,7 +199,11 @@ may log; it should retry). Use the app's own OpenID Connect support or its framework's library where it has one: most self-hosted apps have "generic OIDC" settings that map onto -these variables. For a standard-library Python example of the whole flow, +these variables. If the app has its own step for setting up its client (an +admin makes a secret in its settings, or pastes a client block into the +identity provider), skip it on the Core: fill its settings from `OIDC_*`, +so sign-in works with no admin step, and don't show those instructions when +the Core gave the client. For a standard-library Python example of the whole flow, `coreapp new --sso example` makes one (`oidc.py`). ### `email`: sending mail @@ -260,6 +277,12 @@ and make the Dockerfile fit the Core: create it at startup (it starts empty). - **Send mail with `needs = ["email"]`**, if the app sends any (password resets, notifications): map `SMTP_*` onto its mail settings. +- **If the app also runs elsewhere** (a desktop or another server edition + sharing the Dockerfile), keep those working: choose the Core's behaviour + in the app when `CORE_DOMAIN` is set (the Core's variables become + defaults; the app's own explicit settings still win), not by changing + the Dockerfile's `ENV` or `ENTRYPOINT` for everyone. The Core builds the + `Dockerfile` at the repository's root. - **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=...`). Set the app's own @@ -292,7 +315,7 @@ and make the Dockerfile fit the Core: - **Give it its own `icon.png`**: the project's logo, square, as a PNG (convert an SVG or ICO; 256x256 is good). The template's is a placeholder. `coreapp deploy` and `publish` say if it's unusable, not - square or too small; `publish` refuses one the Core can't use. + square or under 80 pixels; `publish` refuses one the Core can't use. - **Answer on `health`** once ready (a dedicated health endpoint, or `/` if it returns 2xx-4xx without signing in). - **One container.** If the upstream project ships a compose file with @@ -335,9 +358,15 @@ whether it got back to the app signed in: ```bash 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 --cookies jar /login && curl -b jar https://./api/me ``` +A page with a sign-in button (a form with only hidden fields, such as a +CSRF token) is submitted as a person pressing it would; with several such +forms, pick one with `--form `. Don't add routes to the app just for +the test. + For 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, @@ -350,7 +379,7 @@ so don't loop on it. Still ask the user to sign in once in a browser with their own account before a release: it checks what a script can't (the app's pages, and a -person in the Core's groups). +real person's account). ### 4. When something fails diff --git a/templates/app/README.md b/templates/app/README.md index 1ae7ea4..b9a6fda 100644 --- a/templates/app/README.md +++ b/templates/app/README.md @@ -40,6 +40,7 @@ keep its values and add new ones): | `APP_URL` | `https://{{NAME}}.` | | `APP_SECRET` | A random secret, for signing cookies and such | | `IMAGE_VERSION` | The version that's installed | +| `CORE_DOMAIN` | The Core's domain (set only on a 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