Fixes from porting Supermarket: sign-in buttons, CORE_DOMAIN, skill gaps
An agent ported Supermarket with only the skill. coreapp signin now presses a sign-in page's button (a form with only hidden fields; --form picks one), every app gets CORE_DOMAIN, and the skill covers apps that also run elsewhere, IMAGE_VERSION instead of build args, deriving keys from APP_SECRET, the first admin, apps with their own client setup, and that the groups claim is empty on today's Cores. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+110
-10
@@ -3,10 +3,13 @@
|
||||
|
||||
Used by `coreapp signin`; the password comes on stdin.
|
||||
|
||||
signin.py [--cookies FILE] <start-url> <username>
|
||||
signin.py [--cookies FILE] [--form ACTION] <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.
|
||||
and say where it ended. If start-url is a page whose form starts sign-in
|
||||
(a button, with hidden fields only, e.g. a CSRF token), submit it, as a
|
||||
person pressing the button would: the only such form, or the one whose
|
||||
action is ACTION.
|
||||
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
|
||||
@@ -18,6 +21,7 @@ Exits 0 when signed in, 1 when not.
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import html.parser
|
||||
import http.cookiejar
|
||||
import json
|
||||
import re
|
||||
@@ -61,7 +65,7 @@ class Browser:
|
||||
"""(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 {})})
|
||||
**{k: v for k, v in (headers or {}).items() if v}})
|
||||
try:
|
||||
with self.opener.open(req, timeout=30) as r:
|
||||
return r.status, "", r.read(200_000)
|
||||
@@ -70,6 +74,78 @@ class Browser:
|
||||
return e.code, urllib.parse.urljoin(url, location) if location else "", e.read(200_000)
|
||||
|
||||
|
||||
class Forms(html.parser.HTMLParser):
|
||||
"""The forms on a page: method, action, hidden values, whether a person
|
||||
has to fill something in, and the button's text."""
|
||||
FILLED = {"hidden", "submit", "button", "image", "reset"}
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.forms = []
|
||||
self.form = None
|
||||
self.in_button = False
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
a = dict(attrs)
|
||||
if tag == "form":
|
||||
self.form = {"method": (a.get("method") or "get").lower(),
|
||||
"action": a.get("action") or "", "fields": [],
|
||||
"to_fill": False, "button": ""}
|
||||
self.forms.append(self.form)
|
||||
elif self.form is None:
|
||||
return
|
||||
elif tag == "input":
|
||||
kind = (a.get("type") or "text").lower()
|
||||
if kind == "hidden" and a.get("name"):
|
||||
self.form["fields"].append((a["name"], a.get("value") or ""))
|
||||
elif kind not in self.FILLED:
|
||||
self.form["to_fill"] = True
|
||||
elif kind == "submit" and not self.form["button"]:
|
||||
self.form["button"] = a.get("value") or ""
|
||||
elif tag in ("textarea", "select"):
|
||||
self.form["to_fill"] = True
|
||||
elif tag == "button":
|
||||
self.in_button = True
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag == "form":
|
||||
self.form = None
|
||||
elif tag == "button":
|
||||
self.in_button = False
|
||||
|
||||
def handle_data(self, data):
|
||||
if self.form is not None and self.in_button and data.strip():
|
||||
self.form["button"] = (self.form["button"] + " " + data.strip()).strip()
|
||||
|
||||
|
||||
def pick_form(page_url, body, wanted):
|
||||
"""(url, data, label) for the form that starts sign-in, or None."""
|
||||
parser = Forms()
|
||||
parser.feed(body.decode(errors="replace"))
|
||||
for f in parser.forms:
|
||||
f["url"] = urllib.parse.urljoin(page_url, f["action"])
|
||||
if wanted:
|
||||
target = urllib.parse.urljoin(page_url, wanted)
|
||||
forms = [f for f in parser.forms if f["url"].split("?")[0] == target.split("?")[0]]
|
||||
if not forms:
|
||||
actions = ", ".join(sorted({urllib.parse.urlsplit(f["url"]).path for f in parser.forms}))
|
||||
raise SystemExit(f"Not signed in: {shown(page_url)} has no form with action {wanted}"
|
||||
f" (its forms: {actions or 'none'}).")
|
||||
else:
|
||||
forms = [f for f in parser.forms if not f["to_fill"]]
|
||||
if len(forms) > 1:
|
||||
actions = ", ".join(urllib.parse.urlsplit(f["url"]).path for f in forms)
|
||||
raise SystemExit(f"Not signed in: {shown(page_url)} has several forms that could start "
|
||||
f"sign-in ({actions}): pick one with --form <action>.")
|
||||
if not forms:
|
||||
return None
|
||||
f = forms[0]
|
||||
data = urllib.parse.urlencode(f["fields"])
|
||||
if f["method"] == "post":
|
||||
return f["url"], data.encode(), f"the form's button \"{f['button']}\""
|
||||
return f["url"].split("?")[0] + ("?" + data if data else ""), None, f"the form's button \"{f['button']}\""
|
||||
|
||||
|
||||
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."""
|
||||
@@ -96,16 +172,27 @@ def sign_in(browser, portal_url, username, password):
|
||||
return urllib.parse.urljoin(origin, (reply.get("data") or {}).get("redirect", "") or "/")
|
||||
|
||||
|
||||
def follow(browser, url, username, password, stop_at=None):
|
||||
def follow(browser, url, username, password, stop_at=None, form=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
|
||||
submitted = False
|
||||
data, label, referer = None, "", None
|
||||
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}")
|
||||
if data is not None:
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
status, location, body = browser.request(url, data, {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Origin": f"{parts.scheme}://{parts.netloc}", "Referer": referer})
|
||||
print(f" POST {shown(url)} ({label}) -> {status}")
|
||||
data = None
|
||||
else:
|
||||
status, location, body = browser.request(url)
|
||||
print(f" GET {shown(url)}{f' ({label})' if label else ''} -> {status}")
|
||||
label = ""
|
||||
err = errors(location or url)
|
||||
if err:
|
||||
raise SystemExit("Not signed in: " + ", ".join(f"{k}: {v}" for k, v in err.items()))
|
||||
@@ -123,6 +210,14 @@ def follow(browser, url, username, password, stop_at=None):
|
||||
url = sign_in(browser, url, username, password)
|
||||
signed_in = True
|
||||
continue
|
||||
if not signed_in and not submitted and status == 200 and b"<form" in body.lower():
|
||||
# The app's sign-in page, whose button starts sign-in
|
||||
picked = pick_form(url, body, form)
|
||||
if picked:
|
||||
referer = url
|
||||
url, data, label = picked
|
||||
submitted = True
|
||||
continue
|
||||
return url, status, body, signed_in
|
||||
raise SystemExit(f"Not signed in: more than {MAX_STEPS} redirects.")
|
||||
|
||||
@@ -138,11 +233,15 @@ def main(args):
|
||||
sys.stdout.reconfigure(line_buffering=True)
|
||||
code_mode = "--code" in args
|
||||
pkce = "--pkce" in args
|
||||
cookies = None
|
||||
cookies = form = None
|
||||
if "--cookies" in args:
|
||||
i = args.index("--cookies")
|
||||
cookies = args[i + 1]
|
||||
del args[i:i + 2]
|
||||
if "--form" in args:
|
||||
i = args.index("--form")
|
||||
form = 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__)
|
||||
@@ -179,12 +278,13 @@ def main(args):
|
||||
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)
|
||||
last, status, body, signed_in = follow(browser, start, username, password, form=form)
|
||||
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.")
|
||||
f"{shown(last)}, HTTP {status}). Give the app's path that starts sign-in, or its sign-in "
|
||||
"page with --form <action> for a form; 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:
|
||||
|
||||
Reference in New Issue
Block a user