#!/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] 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] 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"= 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:]))