From 284f52fc298ee36f619e2ffe7b2e476b30e2b188 Mon Sep 17 00:00:00 2001 From: David Young Date: Thu, 3 Dec 2026 12:34:27 -0700 Subject: [PATCH] coreapp new --sso: sign-in through the Core's Authelia A template overlay (templates/sso) registers the app as an OpenID Connect client in Authelia's idproviders.yml (between markers, secret hashed by the running Authelia), checks the configuration before restarting Authelia and restores it if the check fails; uninstall removes the client. The app reaches Authelia's https address through traefik (@TRAEFIK_IP@, provided by the template's install and by redeploys). The example is a standard-library Python OIDC client (code flow with PKCE). Tested by install, redeploy, remove and reinstall, and a real sign-in in a browser. Also: the postgres overlay appends to the base install, uninstall and env.in; database names get a coreapp_ prefix (PostgreSQL reserves pg_*); deploy waits until the app answers on its own address. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 24 +- README.md | 3 +- TEST.md | 27 ++- bin/coreapp | 46 +++- templates/app/install | 3 + templates/postgres/env.in | 11 - templates/postgres/env.in.append | 6 + .../postgres/{install => install.append} | 4 - templates/postgres/uninstall | 6 - templates/postgres/uninstall.append | 3 + templates/sso/.remove | 1 + templates/sso/Dockerfile | 8 + templates/sso/README.md.append | 21 ++ templates/sso/app.py | 205 ++++++++++++++++++ templates/sso/docker-compose.yml.in | 27 +++ templates/sso/env.in.append | 5 + templates/sso/install.append | 43 ++++ templates/sso/service | 9 + templates/sso/uninstall.append | 4 + 19 files changed, 419 insertions(+), 37 deletions(-) delete mode 100644 templates/postgres/env.in create mode 100644 templates/postgres/env.in.append rename templates/postgres/{install => install.append} (88%) mode change 100755 => 100644 delete mode 100755 templates/postgres/uninstall create mode 100644 templates/postgres/uninstall.append create mode 100644 templates/sso/.remove create mode 100644 templates/sso/Dockerfile create mode 100644 templates/sso/README.md.append create mode 100644 templates/sso/app.py create mode 100644 templates/sso/docker-compose.yml.in create mode 100644 templates/sso/env.in.append create mode 100644 templates/sso/install.append create mode 100644 templates/sso/service create mode 100644 templates/sso/uninstall.append diff --git a/PLAN.md b/PLAN.md index 03066c6..47985d3 100644 --- a/PLAN.md +++ b/PLAN.md @@ -165,8 +165,28 @@ 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. -- [ ] Next: sign-in through the Core's Authelia (OIDC), as Federated's apps - do with `configsso_` +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. + +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 +- [ ] `--postgres` and `--sso` together (each has its own example app) - [ ] Later: apps published for other Cores (registry, submitting to Federated) diff --git a/README.md b/README.md index 9ed8bde..69d9e71 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ the app's own `Dockerfile`. The README in each new app explains the files. |---|---| | `coreapp new ` | Make an app in `./`; it gets an address in 192.168.200.x on the Core | | `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 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 status` / `logs [-f]` / `shell` | Its container, its log, a shell in it | @@ -109,6 +110,6 @@ stay installed. | `bin/coreapp-vm` | Creates and manages CoreServer VMs (`coreapp-vm help`) | | `bin/coreapp` | Makes, deploys and tests apps (`coreapp help`) | | `templates/app/` | What `coreapp new` starts from | -| `templates/postgres/` | Laid over it by `--postgres` (`*.append` files are added to the base file; `.remove` lists base files to drop) | +| `templates/postgres/`, `templates/sso/` | Laid over it by `--postgres` / `--sso` (`*.append` files are added to the base file; `.remove` lists base files to drop) | | `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 2436314..a199e83 100644 --- a/TEST.md +++ b/TEST.md @@ -173,14 +173,33 @@ no `blackboxregistrar` request. ### With a database 1. `coreapp new --postgres guest-book`: has `app.py`, no `www/`; - `service` has `DEPENDS="postgresql"`; `env.in` has `DB_NAME=guest_book` + `service` has `DEPENDS="postgresql"`; `env.in` has `DB_NAME=coreapp_guest_book` and a random `DB_PASSWORD`; 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 `guest_book`, - owned by `guest_book`. + Core, `docker exec postgresql psql -U postgres -l` lists `coreapp_guest_book`, + owned by `coreapp_guest_book`. 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 `guest_book` database and user are gone too. +5. `coreapp remove`: the `coreapp_guest_book` database and user are gone too. + +### 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_*`; the README has a Sign-in section. + `coreapp new --sso --postgres x` refuses. +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. +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. diff --git a/bin/coreapp b/bin/coreapp index 0143ad3..b89b95e 100755 --- a/bin/coreapp +++ b/bin/coreapp @@ -3,8 +3,9 @@ # Purpose : Make, deploy and test apps for Federated Core, against the Core # in coreapp-dev's VM (coreapp-vm). # -# coreapp new [--postgres] -# make a new app in ./ (with its own database) +# coreapp new [--postgres|--sso] +# make a new app in ./ (with its own database, +# or with sign-in through the Core's Authelia) # coreapp deploy build, copy to the Core, install or update # coreapp check the app answers at https://./ # coreapp status its container, address and URL @@ -77,7 +78,7 @@ 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="" +NAME="" TITLE="" CONTAINER="" VERSION="" INTERNAL_IP="" MONITOR="" HIDDEN="" PORTS="" 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 ." @@ -113,14 +114,18 @@ cmd_new() { local name="" overlay="" title ip dbname f while [[ $# -gt 0 ]]; do case "$1" in - --postgres) overlay="$TEMPLATES/postgres" ;; - -*) die "Unknown option $1. Usage: coreapp new [--postgres] " ;; + --postgres | --sso) + # Each brings its own example app, so one at a time for now + [[ -z "$overlay" ]] || die "Use --postgres or --sso, not both (yet)." + overlay="$TEMPLATES/${1#--}" + ;; + -*) die "Unknown option $1. Usage: coreapp new [--postgres|--sso] " ;; *) name="$1" ;; esac shift done [[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE" - [[ -n "$name" ]] || die "Usage: coreapp new [--postgres] (lowercase letters, digits and -)" + [[ -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.." [[ ! -e "$name" ]] || die "./$name already exists." @@ -131,9 +136,11 @@ cmd_new() { mkdir -p "$DATA" echo "$name $ip" >> "$ADDRESSES" fi - # "my-app" -> "My App"; database names can't have "-" + # "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, ...) title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')" - dbname="${name//-/_}" + dbname="coreapp_${name//-/_}" mkdir "$name" tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf - @@ -154,7 +161,12 @@ cmd_new() { -e "s/{{DBNAME}}/$dbname/g" "$f" done < <(find "$name" -type f ! -name '*.png' -print0) - echo "Made $title in ./$name (address on the Core: $ip${overlay:+, database $dbname})." + case "$overlay" in + */postgres) f=", database $dbname" ;; + */sso) f=", sign-in through Authelia" ;; + *) f="" ;; + esac + echo "Made $title in ./$name (address on the Core: $ip$f)." echo "Next: cd $name && coreapp deploy" } @@ -240,6 +252,8 @@ cmd_deploy() { . /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" @@ -249,6 +263,20 @@ cmd_deploy() { 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)" } diff --git a/templates/app/install b/templates/app/install index bfce6e3..a9ef095 100755 --- a/templates/app/install +++ b/templates/app/install @@ -1,4 +1,7 @@ . /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/postgres/env.in b/templates/postgres/env.in deleted file mode 100644 index c780834..0000000 --- a/templates/postgres/env.in +++ /dev/null @@ -1,11 +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@ -# Its database on the Core's PostgreSQL, made by install -DB_HOST=postgresql.@DOMAIN@ -DB_PORT=5432 -DB_NAME={{DBNAME}} -DB_USER={{DBNAME}} -DB_PASSWORD=@DB_PASSWORD:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ diff --git a/templates/postgres/env.in.append b/templates/postgres/env.in.append new file mode 100644 index 0000000..a41055c --- /dev/null +++ b/templates/postgres/env.in.append @@ -0,0 +1,6 @@ +# Its database on the Core's PostgreSQL, made by install +DB_HOST=postgresql.@DOMAIN@ +DB_PORT=5432 +DB_NAME={{DBNAME}} +DB_USER={{DBNAME}} +DB_PASSWORD=@DB_PASSWORD:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@ diff --git a/templates/postgres/install b/templates/postgres/install.append old mode 100755 new mode 100644 similarity index 88% rename from templates/postgres/install rename to templates/postgres/install.append index 3ec2594..460fc23 --- a/templates/postgres/install +++ b/templates/postgres/install.append @@ -1,7 +1,3 @@ -. /federated/lib/helpers.sh -installGeneric {{NAME}} -# .env holds secrets -chmod 600 /federated/apps/{{NAME}}/.env # Its own database and user on the Core's PostgreSQL (DEPENDS=postgresql), # with the password from .env. Safe to run again: an existing user gets the diff --git a/templates/postgres/uninstall b/templates/postgres/uninstall deleted file mode 100755 index 09e2d46..0000000 --- a/templates/postgres/uninstall +++ /dev/null @@ -1,6 +0,0 @@ -# Sourced by the Core's uninstallapp (so no `exit` here): stop the app and -# delete its settings, data and database -docker compose -f /federated/apps/{{NAME}}/docker-compose.yml -p {{NAME}} down -rm -rf /federated/apps/{{NAME}} -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/templates/postgres/uninstall.append b/templates/postgres/uninstall.append new file mode 100644 index 0000000..c985e98 --- /dev/null +++ b/templates/postgres/uninstall.append @@ -0,0 +1,3 @@ +# ...and its database +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/templates/sso/.remove b/templates/sso/.remove new file mode 100644 index 0000000..f8d728c --- /dev/null +++ b/templates/sso/.remove @@ -0,0 +1 @@ +www diff --git a/templates/sso/Dockerfile b/templates/sso/Dockerfile new file mode 100644 index 0000000..f135e92 --- /dev/null +++ b/templates/sso/Dockerfile @@ -0,0 +1,8 @@ +# 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). +FROM python:3.13-slim +COPY app.py /app/app.py +USER nobody +EXPOSE 8080 +CMD ["python", "-u", "/app/app.py"] diff --git a/templates/sso/README.md.append b/templates/sso/README.md.append new file mode 100644 index 0000000..39cab87 --- /dev/null +++ b/templates/sso/README.md.append @@ -0,0 +1,21 @@ + +## Sign-in + +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`). +- `app.py` shows the whole flow with Python's standard library: `/login`, + `/auth/callback`, `/logout`. For a real app, use your framework's OpenID + Connect library with `OIDC_ISSUER`, `OIDC_CLIENT_ID` and + `OIDC_CLIENT_SECRET`. diff --git a/templates/sso/app.py b/templates/sso/app.py new file mode 100644 index 0000000..1ca637f --- /dev/null +++ b/templates/sso/app.py @@ -0,0 +1,205 @@ +"""{{TITLE}}: signs people in with the Core's Authelia (OpenID Connect). + +Python's standard library only. Settings come from the environment (.env on +the Core): APP_URL, APP_SECRET, OIDC_ISSUER, OIDC_CLIENT_ID, +OIDC_CLIENT_SECRET. + +/login sends the browser to Authelia; Authelia sends it back to +/auth/callback with a code, which the app exchanges for an access token +(authorization code flow with PKCE) and uses to ask who signed in. +""" + +import base64 +import hashlib +import hmac +import html +import json +import os +import secrets +import time +import urllib.error +import urllib.parse +import urllib.request +from http.cookies import SimpleCookie +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +APP_URL = os.environ["APP_URL"].rstrip("/") +APP_SECRET = os.environ["APP_SECRET"].encode() +ISSUER = os.environ["OIDC_ISSUER"].rstrip("/") +CLIENT_ID = os.environ["OIDC_CLIENT_ID"] +CLIENT_SECRET = os.environ["OIDC_CLIENT_SECRET"] +REDIRECT_URI = APP_URL + "/auth/callback" +SESSION_SECONDS = 3600 + +_discovery = {} + + +def discovery(): + """Authelia's endpoints, from its OpenID Connect discovery document.""" + if not _discovery: + url = ISSUER + "/.well-known/openid-configuration" + with urllib.request.urlopen(url, timeout=10) as response: + _discovery.update(json.load(response)) + return _discovery + + +def b64(data): + return base64.urlsafe_b64encode(data).rstrip(b"=").decode() + + +def unb64(text): + return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) + + +def sign(value): + """A cookie value only this app can make: data.signature.""" + data = b64(json.dumps(value).encode()) + mac = hmac.new(APP_SECRET, data.encode(), hashlib.sha256).digest() + return data + "." + b64(mac) + + +def unsign(cookie): + try: + data, mac = cookie.rsplit(".", 1) + good = hmac.new(APP_SECRET, data.encode(), hashlib.sha256).digest() + if not hmac.compare_digest(unb64(mac), good): + return None + value = json.loads(unb64(data)) + except (ValueError, json.JSONDecodeError): + return None + if value.get("expires", 0) < time.time(): + return None + return value + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + url = urllib.parse.urlsplit(self.path) + query = dict(urllib.parse.parse_qsl(url.query)) + routes = { + "/": self.home, + "/login": self.login, + "/auth/callback": self.callback, + "/logout": self.logout, + "/health": lambda q: self.reply(200, "ok\n", "text/plain"), + } + route = routes.get(url.path) + if route is None: + self.reply(404, "Not found\n", "text/plain") + return + try: + route(query) + except (urllib.error.URLError, KeyError, ValueError) as error: + self.reply(502, f"Sign-in failed: {error}\n", "text/plain") + + def cookie(self, name): + cookies = SimpleCookie(self.headers.get("Cookie", "")) + return cookies[name].value if name in cookies else None + + def home(self, query): + user = unsign(self.cookie("session") or "") + if user: + groups = ", ".join(user.get("groups") or []) or "none" + body = ( + f"

Signed in as {html.escape(user['name'])}" + f" ({html.escape(user['email'])}), groups: {html.escape(groups)}.

" + '

Sign out

' + ) + else: + body = '

Sign in with your Core account

' + self.page(body) + + def login(self, query): + # state ties Authelia's answer to this browser; the PKCE verifier + # proves the code is redeemed by whoever asked for it + state = secrets.token_urlsafe(24) + verifier = secrets.token_urlsafe(48) + challenge = b64(hashlib.sha256(verifier.encode()).digest()) + params = { + "response_type": "code", + "client_id": CLIENT_ID, + "redirect_uri": REDIRECT_URI, + "scope": "openid profile email groups", + "state": state, + "code_challenge": challenge, + "code_challenge_method": "S256", + } + flow = sign({"state": state, "verifier": verifier, "expires": time.time() + 600}) + location = discovery()["authorization_endpoint"] + "?" + urllib.parse.urlencode(params) + self.redirect(location, [("flow", flow, 600)]) + + def callback(self, query): + flow = unsign(self.cookie("flow") or "") + if not flow or not hmac.compare_digest(flow["state"], query.get("state", "")): + self.reply(400, "Sign-in expired or didn't start here. Try again.\n", "text/plain") + return + if "error" in query: + self.reply(400, f"Authelia said: {query.get('error_description', query['error'])}\n", "text/plain") + return + # Exchange the code for tokens (client_secret_basic) + form = urllib.parse.urlencode({ + "grant_type": "authorization_code", + "code": query["code"], + "redirect_uri": REDIRECT_URI, + "code_verifier": flow["verifier"], + }).encode() + auth = base64.b64encode( + f"{urllib.parse.quote(CLIENT_ID)}:{urllib.parse.quote(CLIENT_SECRET)}".encode() + ).decode() + request = urllib.request.Request( + discovery()["token_endpoint"], data=form, + headers={"Authorization": "Basic " + auth, + "Content-Type": "application/x-www-form-urlencoded"}) + with urllib.request.urlopen(request, timeout=10) as response: + tokens = json.load(response) + # Who signed in + request = urllib.request.Request( + discovery()["userinfo_endpoint"], + headers={"Authorization": "Bearer " + tokens["access_token"]}) + with urllib.request.urlopen(request, timeout=10) as response: + info = json.load(response) + session = sign({ + "name": info.get("name") or info.get("preferred_username") or info["sub"], + "email": info.get("email", ""), + "groups": info.get("groups", []), + "expires": time.time() + SESSION_SECONDS, + }) + self.redirect("/", [("session", session, SESSION_SECONDS), ("flow", "", 0)]) + + def logout(self, query): + self.redirect("/", [("session", "", 0)]) + + def page(self, body): + self.reply(200, f""" + +{{TITLE}} + +

{{TITLE}}

+

Running on Federated Core, deployed with coreapp-dev.

+{body} + + +""", "text/html; charset=utf-8") + + def redirect(self, location, cookies=()): + self.send_response(302) + self.send_header("Location", location) + for name, value, max_age in cookies: + self.send_header( + "Set-Cookie", + f"{name}={value}; Max-Age={max_age}; Path=/; Secure; HttpOnly; SameSite=Lax") + self.send_header("Content-Length", "0") + self.end_headers() + + def reply(self, status, body, content_type): + data = body.encode() + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + +if __name__ == "__main__": + print("Listening on port 8080", flush=True) + ThreadingHTTPServer(("", 8080), Handler).serve_forever() diff --git a/templates/sso/docker-compose.yml.in b/templates/sso/docker-compose.yml.in new file mode 100644 index 0000000..6982e4f --- /dev/null +++ b/templates/sso/docker-compose.yml.in @@ -0,0 +1,27 @@ +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 diff --git a/templates/sso/env.in.append b/templates/sso/env.in.append new file mode 100644 index 0000000..874c69a --- /dev/null +++ b/templates/sso/env.in.append @@ -0,0 +1,5 @@ +# Sign-in through the Core's Authelia (OpenID Connect); install 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/templates/sso/install.append new file mode 100644 index 0000000..b7863d3 --- /dev/null +++ b/templates/sso/install.append @@ -0,0 +1,43 @@ + +# 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 +# restarts; if the check fails, its old configuration is put back. +IDP=/federated/apps/authelia/data/config/idproviders.yml +OIDC_CLIENT_SECRET="$(sed -n 's/^OIDC_CLIENT_SECRET=//p' /federated/apps/{{NAME}}/.env)" +OIDC_HASH="$(docker exec authelia authelia crypto hash generate pbkdf2 --password "$OIDC_CLIENT_SECRET" | awk '/Digest:/ {print $2}')" +cp -p "$IDP" "$IDP.coreapp-{{NAME}}.bak" +sed -i '/^ ### coreapp-{{NAME}} begin$/,/^ ### coreapp-{{NAME}} end$/d' "$IDP" +cat >> "$IDP" < /dev/null 2>&1; then + rm -f "$IDP.coreapp-{{NAME}}.bak" + restart_service authelia +else + echo "Authelia rejected the new client; left its configuration as it was." >&2 + mv "$IDP.coreapp-{{NAME}}.bak" "$IDP" +fi +unset IDP OIDC_CLIENT_SECRET OIDC_HASH diff --git a/templates/sso/service b/templates/sso/service new file mode 100644 index 0000000..a7c0371 --- /dev/null +++ b/templates/sso/service @@ -0,0 +1,9 @@ +NAME="{{TITLE}}" +DESCRIPTION="{{TITLE}}, made with coreapp-dev" +DOCS= +CONTAINER=coreapp/{{NAME}} +VERSION=0.1.0 +INTERNAL_IP={{IP}} +DEPENDS="authelia" +PORTS=8080 +MONITOR="https://{{NAME}}.@DOMAIN@|http_2xx" diff --git a/templates/sso/uninstall.append b/templates/sso/uninstall.append new file mode 100644 index 0000000..d8c41a8 --- /dev/null +++ b/templates/sso/uninstall.append @@ -0,0 +1,4 @@ +# ...and its Authelia client +sed -i '/^ ### coreapp-{{NAME}} begin$/,/^ ### coreapp-{{NAME}} end$/d' \ + /federated/apps/authelia/data/config/idproviders.yml +restart_service authelia