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:
2026-12-03 12:43:22 -07:00
co-authored by Claude Opus 5.5
parent 284f52fc29
commit d8c6d1011f
14 changed files with 381 additions and 172 deletions
+9
View File
@@ -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"]
+145
View File
@@ -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()
+1
View File
@@ -0,0 +1 @@
postgresql
-9
View File
@@ -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"
+1
View File
@@ -0,0 +1 @@
authelia
+1 -1
View File
@@ -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"]
+4 -4
View File
@@ -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
View File
@@ -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)])
+143
View File
@@ -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)
-9
View File
@@ -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"