coreapp new --postgres --sso: database and sign-in together
Overlays no longer replace service: each names the Core apps it needs in .depends, merged into DEPENDS. The sign-in code is a module (oidc.py) that examples import; templates/postgres-sso is the combined example (sign-in, each person's visits counted in PostgreSQL). Tested with team-visits, including sign-in in a browser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -186,7 +186,15 @@ A real sign-in to sso-demo with a Core account in a browser worked
|
||||
- `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)
|
||||
Both together (2026-12-03): overlays no longer replace `service`; each
|
||||
names the Core apps it needs in `.depends`, merged into `DEPENDS`. The
|
||||
sign-in code is a module (`oidc.py`) any example imports;
|
||||
`templates/postgres-sso` is the combined example (sign-in, each person's
|
||||
visits in PostgreSQL). Tested with `team-visits`: database, Authelia client
|
||||
`coreapp-team-visits`, `DEPENDS="postgresql authelia"`, `/login` to Authelia.
|
||||
|
||||
Signing in to team-visits and sso-demo (with the oidc.py code) in a browser
|
||||
worked (2026-12-03, tested by David).
|
||||
- [ ] Later: apps published for other Cores (registry, submitting to
|
||||
Federated)
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ the app's own `Dockerfile`. The README in each new app explains the files.
|
||||
| `coreapp new <name>` | Make an app in `./<name>`; it gets an address in 192.168.200.x on the Core |
|
||||
| `coreapp new --postgres <name>` | The same, with its own database on the Core's PostgreSQL (a Python example app that uses it) |
|
||||
| `coreapp new --sso <name>` | The same, with sign-in through the Core's Authelia (OpenID Connect; a Python example app) |
|
||||
| `coreapp new --postgres --sso <name>` | Both: a database and sign-in (the example counts each person's visits) |
|
||||
| `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 |
|
||||
@@ -110,6 +111,7 @@ 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/`, `templates/sso/` | Laid over it by `--postgres` / `--sso` (`*.append` files are added to the base file; `.remove` lists base files to drop) |
|
||||
| `templates/postgres/`, `templates/sso/` | Laid over it by `--postgres` / `--sso`: their files replace the base's; `*.append` files are added to the base file, `.remove` lists base files to drop, `.depends` the Core apps it needs (merged into `DEPENDS`) |
|
||||
| `templates/postgres-sso/` | The example app when both are used |
|
||||
| `uninstall.sh` | Removes what coreapp-dev set up |
|
||||
| [PLAN.md](PLAN.md), [TEST.md](TEST.md) | What's next, and how to test it |
|
||||
|
||||
@@ -189,8 +189,8 @@ no `blackboxregistrar` request.
|
||||
|
||||
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.
|
||||
`@TRAEFIK_IP@`; `env.in` has `OIDC_*`; `app.py` and `oidc.py`; the README
|
||||
has a Sign-in section.
|
||||
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
|
||||
@@ -203,3 +203,14 @@ no `blackboxregistrar` request.
|
||||
sign-in link.
|
||||
5. Redeploy: still one client block. `coreapp remove`: none, Authelia
|
||||
healthy, other clients (Nextcloud) still work. Deploy again: one block.
|
||||
|
||||
### With both
|
||||
|
||||
1. `coreapp new --postgres --sso team-visits`: `service` has
|
||||
`DEPENDS="postgresql authelia"`; `env.in` has `DB_*` and `OIDC_*`;
|
||||
`install` creates the database and registers the client; `uninstall`
|
||||
undoes both; `app.py` imports `oidc` and `psycopg`.
|
||||
2. `coreapp deploy`, `coreapp check`. In a browser, sign in: the page shows
|
||||
your name and "Your visits", which counts up on reload. Another account
|
||||
gets its own count; "people who have visited" counts both.
|
||||
3. `coreapp remove`: the database, user and Authelia client are gone.
|
||||
|
||||
+40
-27
@@ -3,9 +3,9 @@
|
||||
# Purpose : Make, deploy and test apps for Federated Core, against the Core
|
||||
# in coreapp-dev's VM (coreapp-vm).
|
||||
#
|
||||
# coreapp new [--postgres|--sso] <name>
|
||||
# coreapp new [--postgres] [--sso] <name>
|
||||
# make a new app in ./<name> (with its own database,
|
||||
# or with sign-in through the Core's Authelia)
|
||||
# sign-in through the Core's Authelia, or both)
|
||||
# coreapp deploy build, copy to the Core, install or update
|
||||
# coreapp check the app answers at https://<name>.<domain>/
|
||||
# coreapp status its container, address and URL
|
||||
@@ -110,26 +110,47 @@ next_address() {
|
||||
die "All addresses in $PREFIX.10-250 are taken (see $ADDRESSES)."
|
||||
}
|
||||
|
||||
# Lay an overlay over the app in $1: its files replace the app's, except
|
||||
# *.append (added to the end of the app's file), .remove (app files it
|
||||
# doesn't use) and .depends (apps it needs, for DEPENDS in service)
|
||||
apply_overlay() {
|
||||
local app="$1" overlay="$2" f
|
||||
tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude=.depends \
|
||||
--exclude='*.append' -cf - . | tar -C "$app" -xf -
|
||||
for f in "$overlay"/*.append; do
|
||||
[[ -e "$f" ]] && cat "$f" >> "$app/$(basename "$f" .append)"
|
||||
done
|
||||
if [[ -f "$overlay/.remove" ]]; then
|
||||
while read -r f; do [[ -n "$f" ]] && rm -rf "${app:?}/$f"; done < "$overlay/.remove"
|
||||
fi
|
||||
}
|
||||
|
||||
cmd_new() {
|
||||
local name="" overlay="" title ip dbname f
|
||||
local name="" postgres="" sso="" title ip dbname f depends="" what=""
|
||||
local overlays=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--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>" ;;
|
||||
--postgres) postgres=1 ;;
|
||||
--sso) sso=1 ;;
|
||||
-*) die "Unknown option $1. Usage: coreapp new [--postgres] [--sso] <name>" ;;
|
||||
*) name="$1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE"
|
||||
[[ -n "$name" ]] || die "Usage: coreapp new [--postgres|--sso] <name> (lowercase letters, digits and -)"
|
||||
[[ -n "$name" ]] || die "Usage: coreapp new [--postgres] [--sso] <name> (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.<domain>."
|
||||
[[ ! -e "$name" ]] || die "./$name already exists."
|
||||
|
||||
# In this order; with both, the combined example app goes on top
|
||||
[[ -n "$postgres" ]] && overlays+=("$TEMPLATES/postgres")
|
||||
[[ -n "$sso" ]] && overlays+=("$TEMPLATES/sso")
|
||||
[[ -n "$postgres" && -n "$sso" ]] && overlays+=("$TEMPLATES/postgres-sso")
|
||||
for f in "${overlays[@]}"; do
|
||||
[[ -d "$f" ]] || die "The template $f is missing."
|
||||
done
|
||||
|
||||
ip="$(grep -s "^$name " "$ADDRESSES" | cut -d' ' -f2 || true)"
|
||||
if [[ -z "$ip" ]]; then
|
||||
ip="$(next_address)"
|
||||
@@ -144,29 +165,21 @@ cmd_new() {
|
||||
|
||||
mkdir "$name"
|
||||
tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf -
|
||||
if [[ -n "$overlay" ]]; then
|
||||
# The overlay's files replace the base's; *.append ones are added to the
|
||||
# end of the base file; .remove lists base files it doesn't use
|
||||
tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude='*.append' -cf - . \
|
||||
| tar -C "$name" -xf -
|
||||
for f in "$overlay"/*.append; do
|
||||
[[ -e "$f" ]] && cat "$f" >> "$name/$(basename "$f" .append)"
|
||||
for f in "${overlays[@]}"; do
|
||||
apply_overlay "$name" "$f"
|
||||
[[ -f "$f/.depends" ]] && depends="$depends $(cat "$f/.depends")"
|
||||
done
|
||||
if [[ -f "$overlay/.remove" ]]; then
|
||||
while read -r f; do [[ -n "$f" ]] && rm -rf "${name:?}/$f"; done < "$overlay/.remove"
|
||||
fi
|
||||
fi
|
||||
depends="${depends# }"
|
||||
sed -i "s/^DEPENDS=.*/DEPENDS=\"$depends\"/" "$name/service"
|
||||
|
||||
while IFS= read -r -d '' f; do
|
||||
sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{IP}}/$ip/g" \
|
||||
-e "s/{{DBNAME}}/$dbname/g" "$f"
|
||||
done < <(find "$name" -type f ! -name '*.png' -print0)
|
||||
|
||||
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)."
|
||||
[[ -n "$postgres" ]] && what=", database $dbname"
|
||||
[[ -n "$sso" ]] && what="$what, sign-in through Authelia"
|
||||
echo "Made $title in ./$name (address on the Core: $ip$what)."
|
||||
echo "Next: cd $name && coreapp deploy"
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# The app's image. coreapp deploy builds it as coreapp/{{NAME}}:<VERSION>
|
||||
# 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
|
||||
RUN pip install --no-cache-dir "psycopg[binary]==3.2.*"
|
||||
COPY app.py oidc.py /app/
|
||||
USER nobody
|
||||
EXPOSE 8080
|
||||
CMD ["python", "-u", "/app/app.py"]
|
||||
@@ -0,0 +1,145 @@
|
||||
"""{{TITLE}}: signs people in with the Core's Authelia, and counts each
|
||||
person's visits in its PostgreSQL database.
|
||||
|
||||
The sign-in is in oidc.py. Settings come from the environment (.env on the
|
||||
Core): DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD, and oidc.py's.
|
||||
"""
|
||||
|
||||
import html
|
||||
import os
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
from http.cookies import SimpleCookie
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import psycopg
|
||||
|
||||
import oidc
|
||||
|
||||
DB = {
|
||||
"host": os.environ["DB_HOST"],
|
||||
"port": os.environ.get("DB_PORT", "5432"),
|
||||
"dbname": os.environ["DB_NAME"],
|
||||
"user": os.environ["DB_USER"],
|
||||
"password": os.environ["DB_PASSWORD"],
|
||||
"connect_timeout": 5,
|
||||
}
|
||||
|
||||
|
||||
def connect():
|
||||
return psycopg.connect(**DB, autocommit=True)
|
||||
|
||||
|
||||
def setup():
|
||||
# PostgreSQL may still be starting (after a reboot): keep trying
|
||||
for attempt in range(60):
|
||||
try:
|
||||
with connect() as db:
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS visits ("
|
||||
" id bigserial PRIMARY KEY,"
|
||||
" person text NOT NULL,"
|
||||
" at timestamptz NOT NULL DEFAULT now())"
|
||||
)
|
||||
return
|
||||
except psycopg.OperationalError as error:
|
||||
print(f"Waiting for the database ({error})", flush=True)
|
||||
time.sleep(5)
|
||||
raise SystemExit("The database didn't answer for 5 minutes")
|
||||
|
||||
|
||||
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 oidc.SignInError as error:
|
||||
self.reply(400, f"Sign-in failed: {error}\n", "text/plain")
|
||||
except (urllib.error.URLError, KeyError, ValueError) as error:
|
||||
self.reply(502, f"Sign-in failed: {error}\n", "text/plain")
|
||||
except psycopg.Error as error:
|
||||
self.reply(503, f"Database error: {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 = oidc.read_session(self.cookie("session"))
|
||||
if not user:
|
||||
self.page('<p><a href="/login">Sign in with your Core account</a></p>')
|
||||
return
|
||||
with connect() as db:
|
||||
db.execute("INSERT INTO visits (person) VALUES (%s)", (user["sub"],))
|
||||
mine = db.execute(
|
||||
"SELECT count(*) FROM visits WHERE person = %s", (user["sub"],)
|
||||
).fetchone()[0]
|
||||
people = db.execute("SELECT count(DISTINCT person) FROM visits").fetchone()[0]
|
||||
self.page(
|
||||
f"<p>Signed in as <strong id=\"user\">{html.escape(user['name'])}</strong>"
|
||||
f" ({html.escape(user['email'])}).</p>"
|
||||
f"<p>Your visits: <strong id=\"visits\">{mine}</strong>"
|
||||
f" (people who have visited: {people}), counted in PostgreSQL.</p>"
|
||||
'<p><a href="/logout">Sign out</a></p>'
|
||||
)
|
||||
|
||||
def login(self, query):
|
||||
location, flow = oidc.start_login()
|
||||
self.redirect(location, [("flow", flow, oidc.FLOW_SECONDS)])
|
||||
|
||||
def callback(self, query):
|
||||
user = oidc.finish_login(query, self.cookie("flow"))
|
||||
self.redirect("/", [("session", oidc.make_session(user), oidc.SESSION_SECONDS),
|
||||
("flow", "", 0)])
|
||||
|
||||
def logout(self, query):
|
||||
self.redirect("/", [("session", "", 0)])
|
||||
|
||||
def page(self, body):
|
||||
self.reply(200, f"""<!doctype html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>{{TITLE}}</title></head>
|
||||
<body>
|
||||
<h1>{{TITLE}}</h1>
|
||||
<p>Running on Federated Core, deployed with coreapp-dev.</p>
|
||||
{body}
|
||||
</body>
|
||||
</html>
|
||||
""", "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__":
|
||||
setup()
|
||||
print("Listening on port 8080", flush=True)
|
||||
ThreadingHTTPServer(("", 8080), Handler).serve_forever()
|
||||
@@ -0,0 +1 @@
|
||||
postgresql
|
||||
@@ -1,9 +0,0 @@
|
||||
NAME="{{TITLE}}"
|
||||
DESCRIPTION="{{TITLE}}, made with coreapp-dev"
|
||||
DOCS=
|
||||
CONTAINER=coreapp/{{NAME}}
|
||||
VERSION=0.1.0
|
||||
INTERNAL_IP={{IP}}
|
||||
DEPENDS="postgresql"
|
||||
PORTS=8080
|
||||
MONITOR="https://{{NAME}}.@DOMAIN@|http_2xx"
|
||||
@@ -0,0 +1 @@
|
||||
authelia
|
||||
@@ -2,7 +2,7 @@
|
||||
# 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
|
||||
COPY app.py oidc.py /app/
|
||||
USER nobody
|
||||
EXPOSE 8080
|
||||
CMD ["python", "-u", "/app/app.py"]
|
||||
|
||||
@@ -15,7 +15,7 @@ People sign in with their Core account, through the Core's Authelia
|
||||
is applied to every client after each install).
|
||||
- The app reaches `https://authelia.<domain>` 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`.
|
||||
- `oidc.py` does the whole flow with Python's standard library, and `app.py`
|
||||
uses it for `/login`, `/auth/callback` and `/logout`. For a real app, use
|
||||
your framework's OpenID Connect library with `OIDC_ISSUER`,
|
||||
`OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET`.
|
||||
|
||||
+11
-117
@@ -1,75 +1,15 @@
|
||||
"""{{TITLE}}: signs people in with the Core's Authelia (OpenID Connect).
|
||||
"""{{TITLE}}: signs people in with the Core's Authelia.
|
||||
|
||||
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.
|
||||
The sign-in itself is in oidc.py. Python's standard library only.
|
||||
"""
|
||||
|
||||
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
|
||||
import oidc
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
@@ -89,6 +29,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return
|
||||
try:
|
||||
route(query)
|
||||
except oidc.SignInError as error:
|
||||
self.reply(400, f"Sign-in failed: {error}\n", "text/plain")
|
||||
except (urllib.error.URLError, KeyError, ValueError) as error:
|
||||
self.reply(502, f"Sign-in failed: {error}\n", "text/plain")
|
||||
|
||||
@@ -97,7 +39,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return cookies[name].value if name in cookies else None
|
||||
|
||||
def home(self, query):
|
||||
user = unsign(self.cookie("session") or "")
|
||||
user = oidc.read_session(self.cookie("session"))
|
||||
if user:
|
||||
groups = ", ".join(user.get("groups") or []) or "none"
|
||||
body = (
|
||||
@@ -110,61 +52,13 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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)])
|
||||
location, flow = oidc.start_login()
|
||||
self.redirect(location, [("flow", flow, oidc.FLOW_SECONDS)])
|
||||
|
||||
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)])
|
||||
user = oidc.finish_login(query, self.cookie("flow"))
|
||||
self.redirect("/", [("session", oidc.make_session(user), oidc.SESSION_SECONDS),
|
||||
("flow", "", 0)])
|
||||
|
||||
def logout(self, query):
|
||||
self.redirect("/", [("session", "", 0)])
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Sign-in with the Core's Authelia (OpenID Connect), standard library only.
|
||||
|
||||
Authorization code flow with PKCE, and a signed session cookie. Settings
|
||||
come from the environment (.env on the Core): APP_URL, APP_SECRET,
|
||||
OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET.
|
||||
|
||||
location, flow = start_login() # /login: redirect to Authelia
|
||||
user = finish_login(query, flow) # /auth/callback: who signed in
|
||||
cookie = make_session(user) # keep them signed in
|
||||
user = read_session(cookie) # later requests (None if not)
|
||||
|
||||
For a real app, your framework's OpenID Connect library does the same with
|
||||
OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
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
|
||||
FLOW_SECONDS = 600
|
||||
|
||||
|
||||
class SignInError(Exception):
|
||||
"""The sign-in didn't complete (expired, cancelled, refused)."""
|
||||
|
||||
|
||||
_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, seconds):
|
||||
"""A cookie value only this app can make (data.signature), expiring."""
|
||||
value = dict(value, expires=time.time() + seconds)
|
||||
data = _b64(json.dumps(value).encode())
|
||||
mac = hmac.new(APP_SECRET, data.encode(), hashlib.sha256).digest()
|
||||
return data + "." + _b64(mac)
|
||||
|
||||
|
||||
def unsign(cookie):
|
||||
"""The value in a cookie from sign(), or None if forged or expired."""
|
||||
try:
|
||||
data, mac = (cookie or "").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
|
||||
return value if value.get("expires", 0) >= time.time() else None
|
||||
|
||||
|
||||
def start_login():
|
||||
"""Where to send the browser, and a cookie value to keep until it's back.
|
||||
|
||||
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)
|
||||
params = {
|
||||
"response_type": "code",
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"scope": "openid profile email groups",
|
||||
"state": state,
|
||||
"code_challenge": _b64(hashlib.sha256(verifier.encode()).digest()),
|
||||
"code_challenge_method": "S256",
|
||||
}
|
||||
location = discovery()["authorization_endpoint"] + "?" + urllib.parse.urlencode(params)
|
||||
return location, sign({"state": state, "verifier": verifier}, FLOW_SECONDS)
|
||||
|
||||
|
||||
def finish_login(query, flow_cookie):
|
||||
"""Who signed in: {sub, name, email, groups}, from Authelia's answer."""
|
||||
flow = unsign(flow_cookie)
|
||||
if not flow or not hmac.compare_digest(flow["state"], query.get("state", "")):
|
||||
raise SignInError("The sign-in expired or didn't start here. Try again.")
|
||||
if "error" in query:
|
||||
raise SignInError(query.get("error_description", query["error"]))
|
||||
# Exchange the code for tokens (client_secret_basic)
|
||||
form = urllib.parse.urlencode({
|
||||
"grant_type": "authorization_code",
|
||||
"code": query.get("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)
|
||||
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)
|
||||
return {
|
||||
"sub": info["sub"],
|
||||
"name": info.get("name") or info.get("preferred_username") or info["sub"],
|
||||
"email": info.get("email", ""),
|
||||
"groups": info.get("groups", []),
|
||||
}
|
||||
|
||||
|
||||
def make_session(user):
|
||||
return sign(user, SESSION_SECONDS)
|
||||
|
||||
|
||||
def read_session(cookie):
|
||||
return unsign(cookie)
|
||||
@@ -1,9 +0,0 @@
|
||||
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"
|
||||
Reference in New Issue
Block a user