"""Federation interop test: a real GoToSocial account follows a Scrobbler user. Runs inside the interop compose network (see deploy/interop/). Standard library only. Exits non-zero, with a description, on the first thing that doesn't work. """ import html import http.cookiejar import json import os import re import sys import time import urllib.error import urllib.parse import urllib.request GTS = "http://gts.test" SCROBBLER_API = "http://api:8000/api/v1" GTS_EMAIL = os.environ.get("GTS_EMAIL", "gtsuser@gts.test") GTS_PASSWORD = os.environ.get("GTS_PASSWORD", "Interop-Test-Password-1") OOB = "urn:ietf:wg:oauth:2.0:oob" def step(message: str) -> None: print(f"==> {message}", flush=True) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None class Browser: """Just enough of a browser to sign in and authorize an OAuth app.""" def __init__(self): self.jar = http.cookiejar.CookieJar() self.opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(self.jar), NoRedirect() ) def request(self, method, url, form=None): data = urllib.parse.urlencode(form).encode() if form is not None else None req = urllib.request.Request(url, data=data, method=method) if data is not None: req.add_header("Content-Type", "application/x-www-form-urlencoded") try: with self.opener.open(req, timeout=20) as response: return response.status, dict(response.headers), response.read().decode() except urllib.error.HTTPError as err: # includes 3xx, since we don't follow them return err.code, dict(err.headers), err.read().decode() def api(method, url, token=None, body=None, form=None): headers = {"Accept": "application/json"} data = None if body is not None: data, headers["Content-Type"] = json.dumps(body).encode(), "application/json" elif form is not None: data, headers["Content-Type"] = ( urllib.parse.urlencode(form).encode(), "application/x-www-form-urlencoded", ) if token: headers["Authorization"] = f"Bearer {token}" req = urllib.request.Request(url, data=data, method=method, headers=headers) try: with urllib.request.urlopen(req, timeout=20) as response: raw = response.read() return response.status, json.loads(raw) if raw else None except urllib.error.HTTPError as err: raw = err.read() try: return err.code, json.loads(raw) except json.JSONDecodeError: return err.code, raw.decode(errors="replace")[:500] def fail(message: str): print(f"FAILED: {message}", flush=True) sys.exit(1) def gotosocial_token() -> str: """Sign in to GoToSocial's web UI and authorize an app (it has no password grant).""" status, app = api( "POST", f"{GTS}/api/v1/apps", form={ "client_name": "scrobbler-interop", "redirect_uris": OOB, "scopes": "read write follow", }, ) if status != 200: fail(f"creating a GoToSocial app: {status} {app}") browser = Browser() authorize = f"{GTS}/oauth/authorize?" + urllib.parse.urlencode( { "response_type": "code", "client_id": app["client_id"], "redirect_uri": OOB, "scope": "read write follow", } ) status, headers, body = browser.request("GET", authorize) print(f" authorize -> {status} {headers.get('Location', '')}") status, headers, body = browser.request( "POST", f"{GTS}/auth/sign_in", {"username": GTS_EMAIL, "password": GTS_PASSWORD} ) print(f" sign in -> {status} {headers.get('Location', '')}") if status not in (302, 303): fail(f"sign-in didn't redirect: {status} {body[:300]}") location = urllib.parse.urljoin(GTS, headers.get("Location", "/oauth/authorize")) status, headers, body = browser.request("GET", location) print(f" authorize page -> {status} {headers.get('Location', '')}") if status == 200: # The consent page: submit its form (with any hidden fields it has) fields = dict(re.findall(r']*name="([^"]+)"[^>]*value="([^"]*)"', body)) action = re.search(r'