Files
linux-cloud-router/tests/remote/oidc_login.py
T

64 lines
2.5 KiB
Python

"""Sign a user in at the server's OpenID Provider as a browser would, in the client of the oidc scenario.
It reads the authorization URL a relying party made from /run/lm-dev/oidc-url, the user's name, password and TOTP code
from /run/lm-dev/oidc-name, /run/lm-dev/oidc-password and /run/lm-dev/oidc-code, and removes the password and the code,
trusts the server's root CA in /root/oidc-root.pem, opens the URL, which answers the sign-in page, and posts the page's
form to /oidc/login without following the redirect. It prints {"page", "status", "location"} as JSON: whether the
sign-in page came, the status of the sign-in, and the Location of its redirect, null without one.
python3 oidc_login.py
"""
import json
import os
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request
HANDOVER = '/run/lm-dev'
ROOT_PEM = '/root/oidc-root.pem'
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""A redirect is answered as it is, not followed."""
def redirect_request(self, request, fp, code, message, headers, new_url):
return None
def read(name, remove=False):
path = os.path.join(HANDOVER, name)
with open(path, encoding='utf-8') as handle:
value = handle.read().strip()
if remove:
os.remove(path)
return value
def main():
url = read('oidc-url')
name = read('oidc-name')
password = read('oidc-password', remove=True)
code = read('oidc-code', remove=True)
context = ssl.create_default_context(cafile=ROOT_PEM)
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context), NoRedirect())
with opener.open(url, timeout=30) as response:
page = response.status == 200 and 'name="password"' in response.read().decode(errors='replace')
parts = urllib.parse.urlsplit(url)
form = urllib.parse.urlencode({'request': parts.query, 'name': name, 'password': password, 'code': code}).encode()
request = urllib.request.Request(f'{parts.scheme}://{parts.netloc}/oidc/login', data=form, method='POST',
headers={'Content-Type': 'application/x-www-form-urlencoded'})
try:
with opener.open(request, timeout=30) as response:
status, location = response.status, response.headers.get('Location')
except urllib.error.HTTPError as error:
status, location = error.code, error.headers.get('Location')
print(json.dumps({'page': page, 'status': status, 'location': location}))
return 0
if __name__ == '__main__':
sys.exit(main())