Files
coreapp-dev/lib/signin.py
T
davidandClaude Opus 5.5 da767e2139 Add coreapp signin: test an app's sign-in on the Core, as a browser would
The Vikunja rehearsal's agent could only test sign-in against a stand-in
Authelia. coreapp signin follows the app's sign-in through the Core's real
Authelia as a test person (coreapp.test, made by coreapps test-account
with a new random password each run, kept nowhere), prints each step with
Authelia's errors, and says whether it got back to the app signed in.
--code covers apps that start sign-in in the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 17:57:48 -07:00

206 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""Sign in to an app on the Core as a browser would, with the test account.
Used by `coreapp signin`; the password comes on stdin.
signin.py [--cookies FILE] <start-url> <username>
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.
signin.py --code [--pkce] <issuer> <client-id> <callback-url> <username>
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
app's callback: print it, with the code (and the PKCE verifier).
Each step is printed; values of codes, states and such are left out.
Exits 0 when signed in, 1 when not.
"""
import base64
import hashlib
import http.cookiejar
import json
import re
import secrets
import sys
import urllib.error
import urllib.parse
import urllib.request
MAX_STEPS = 25
# Query values worth showing (the rest are secrets or noise)
SHOWN = {"client_id", "redirect_uri", "scope", "response_type", "response_mode",
"code_challenge_method", "error", "error_description", "error_hint", "flow"}
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
def shown(url):
"""url without the values that aren't for printing."""
parts = urllib.parse.urlsplit(url)
query = [f"{k}={v}" if k in SHOWN else f"{k}=…"
for k, v in urllib.parse.parse_qsl(parts.query, keep_blank_values=True)]
return urllib.parse.urlunsplit(parts._replace(query="&".join(query)))
def errors(url):
q = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query))
return {k: q[k] for k in ("error", "error_description", "error_hint") if k in q}
class Browser:
def __init__(self, jar):
self.jar = jar
self.opener = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(jar), NoRedirect)
def request(self, url, data=None, headers=None):
"""(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 {})})
try:
with self.opener.open(req, timeout=30) as r:
return r.status, "", r.read(200_000)
except urllib.error.HTTPError as e:
location = e.headers.get("Location", "")
return e.code, urllib.parse.urljoin(url, location) if location else "", e.read(200_000)
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."""
parts = urllib.parse.urlsplit(portal_url)
q = dict(urllib.parse.parse_qsl(parts.query))
body = {"username": username, "password": password, "keepMeLoggedIn": False}
if q.get("flow"):
body.update(flow=q["flow"], flowID=q.get("flow_id", ""))
if q.get("subflow"):
body["subflow"] = q["subflow"]
elif q.get("rd"):
body.update(targetURL=q["rd"], requestMethod=q.get("rm", "GET"))
origin = f"{parts.scheme}://{parts.netloc}"
status, _, raw = browser.request(origin + "/api/firstfactor", json.dumps(body).encode(), {
"Content-Type": "application/json", "Origin": origin})
try:
reply = json.loads(raw)
except ValueError:
reply = {}
print(f" POST {origin}/api/firstfactor (as {username}) -> {status} {reply.get('status', '')}")
if status != 200 or reply.get("status") != "OK":
message = reply.get("message") or raw[:200].decode(errors="replace")
raise SystemExit(f"Not signed in: Authelia refused the test account: {message}")
return urllib.parse.urljoin(origin, (reply.get("data") or {}).get("redirect", "") or "/")
def follow(browser, url, username, password, stop_at=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
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}")
err = errors(location or url)
if err:
raise SystemExit("Not signed in: " + ", ".join(f"{k}: {v}" for k, v in err.items()))
host = urllib.parse.urlsplit(url).netloc
if "/api/oidc/authorization" in url:
auth_host = host
if location:
url = location
continue
if host == auth_host and status == 200 and b"<html" in body[:500].lower():
# Authelia's own page: the login form (or a consent page, which
# the Core's clients don't ask for)
if signed_in:
raise SystemExit(f"Not signed in: Authelia showed its page again after signing in ({shown(url)}).")
url = sign_in(browser, url, username, password)
signed_in = True
continue
return url, status, body, signed_in
raise SystemExit(f"Not signed in: more than {MAX_STEPS} redirects.")
def pkce_pair():
verifier = secrets.token_urlsafe(48)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=")
return verifier, challenge.decode()
def main(args):
# Steps and verdicts in order, when both go to one pipe
sys.stdout.reconfigure(line_buffering=True)
code_mode = "--code" in args
pkce = "--pkce" in args
cookies = None
if "--cookies" in args:
i = args.index("--cookies")
cookies = args[i + 1]
del args[i:i + 2]
args = [a for a in args if a not in ("--code", "--pkce")]
if len(args) != (4 if code_mode else 2):
sys.stderr.write(__doc__)
return 2
start, username = args[0], args[-1]
password = sys.stdin.read()
jar = http.cookiejar.MozillaCookieJar(cookies) if cookies else http.cookiejar.CookieJar()
browser = Browser(jar)
app = urllib.parse.urlsplit(start)
if code_mode:
issuer, client_id, callback = args[0], args[1], args[2]
state = secrets.token_urlsafe(16)
query = {"response_type": "code", "client_id": client_id, "redirect_uri": callback,
"scope": "openid profile email groups", "state": state,
"nonce": secrets.token_urlsafe(16)}
verifier = None
if pkce:
verifier, challenge = pkce_pair()
query.update(code_challenge=challenge, code_challenge_method="S256")
url = issuer.rstrip("/") + "/api/oidc/authorization?" + urllib.parse.urlencode(query)
last, _, _, _ = follow(browser, url, username, password, stop_at=callback)
q = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(last).query))
if not last.startswith(callback) or "code" not in q:
raise SystemExit(f"Not signed in: Authelia didn't send a code to {callback}.")
if q.get("state") != state:
raise SystemExit("Not signed in: the state came back changed.")
print("Signed in: Authelia sent the browser to the app's callback with a code.")
print(f"callback={last}")
print(f"code={q['code']}")
print(f"state={state}")
if verifier:
print(f"code_verifier={verifier}")
print("The code works once, for a few minutes, with the app's own client secret.")
return 0
last, status, body, signed_in = follow(browser, start, username, password)
if not signed_in:
raise SystemExit(
f"Not signed in: {shown(start)} didn't lead to the Core's sign-in (it ended at "
f"{shown(last)}, HTTP {status}). Give the app's path that starts sign-in; if the app "
"starts it in the browser's JavaScript, use --code.")
if urllib.parse.urlsplit(last).netloc != app.netloc:
raise SystemExit(f"Not signed in: it ended at {shown(last)} (HTTP {status}), not at the app.")
if status >= 400:
raise SystemExit(f"Not signed in: Authelia accepted the test account, but the app answered "
f"HTTP {status} at {shown(last)} (coreapp logs says why).")
if cookies:
jar.save(ignore_discard=True, ignore_expires=True)
text = re.sub(rb"<[^>]+>", b" ", body).decode(errors="replace")
mentions = username.split("@")[0] in text
print(f"Signed in: back at the app, {shown(last)} answered HTTP {status}.")
print("Its page " + ("shows" if mentions else "doesn't show") + f" {username.split('@')[0]}.")
if cookies:
print(f"Cookies saved in {cookies} (curl -b {cookies} https://{app.netloc}/...).")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))