|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Simulates the login.databricks.com discovery flow for acceptance tests. |
| 4 | +
|
| 5 | +When the CLI opens this "browser" with the login.databricks.com URL, |
| 6 | +the script extracts the OAuth parameters from the destination_url, |
| 7 | +constructs a callback to localhost with an iss parameter pointing |
| 8 | +at the testserver, and fetches it. |
| 9 | +
|
| 10 | +Usage: discovery_browser.py <url> |
| 11 | +""" |
| 12 | + |
| 13 | +import os |
| 14 | +import sys |
| 15 | +import urllib.parse |
| 16 | +import urllib.request |
| 17 | + |
| 18 | +if len(sys.argv) < 2: |
| 19 | + sys.stderr.write("Usage: discovery_browser.py <url>\n") |
| 20 | + sys.exit(1) |
| 21 | + |
| 22 | +url = sys.argv[1] |
| 23 | +parsed = urllib.parse.urlparse(url) |
| 24 | +top_params = urllib.parse.parse_qs(parsed.query) |
| 25 | + |
| 26 | +destination_url = top_params.get("destination_url", [None])[0] |
| 27 | +if not destination_url: |
| 28 | + sys.stderr.write(f"No destination_url found in: {url}\n") |
| 29 | + sys.exit(1) |
| 30 | + |
| 31 | +dest_parsed = urllib.parse.urlparse(destination_url) |
| 32 | +dest_params = urllib.parse.parse_qs(dest_parsed.query) |
| 33 | + |
| 34 | +redirect_uri = dest_params.get("redirect_uri", [None])[0] |
| 35 | +state = dest_params.get("state", [None])[0] |
| 36 | + |
| 37 | +if not redirect_uri or not state: |
| 38 | + sys.stderr.write(f"Missing redirect_uri or state in destination_url: {destination_url}\n") |
| 39 | + sys.exit(1) |
| 40 | + |
| 41 | +# The testserver's host acts as the workspace issuer. |
| 42 | +testserver_host = os.environ.get("DATABRICKS_HOST", "") |
| 43 | +if not testserver_host: |
| 44 | + sys.stderr.write("DATABRICKS_HOST not set\n") |
| 45 | + sys.exit(1) |
| 46 | + |
| 47 | +issuer = testserver_host.rstrip("/") + "/oidc" |
| 48 | + |
| 49 | +# Build the callback URL with code, state, and iss (the workspace issuer). |
| 50 | +callback_params = urllib.parse.urlencode( |
| 51 | + { |
| 52 | + "code": "oauth-code", |
| 53 | + "state": state, |
| 54 | + "iss": issuer, |
| 55 | + } |
| 56 | +) |
| 57 | +callback_url = f"{redirect_uri}?{callback_params}" |
| 58 | + |
| 59 | +try: |
| 60 | + response = urllib.request.urlopen(callback_url) |
| 61 | + if response.status != 200: |
| 62 | + sys.stderr.write(f"Callback failed: {callback_url} (status {response.status})\n") |
| 63 | + sys.exit(1) |
| 64 | +except Exception as e: |
| 65 | + sys.stderr.write(f"Callback failed: {callback_url} ({e})\n") |
| 66 | + sys.exit(1) |
| 67 | + |
| 68 | +sys.exit(0) |
0 commit comments