Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions msal/oauth2cli/authcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,34 @@ def obtain_auth_code(listen_port, auth_uri=None): # Historically only used in t
).get("code")


def is_wsl():
# "Official" way of detecting WSL: https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364
# Run `uname -a` to get 'release' without python
# - WSL 1: '4.4.0-19041-Microsoft'
# - WSL 2: '4.19.128-microsoft-standard'
import platform
uname = platform.uname()
platform_name = getattr(uname, 'system', None).lower()
release = getattr(uname, 'release', None).lower()
return platform_name == 'linux' and 'microsoft' in release


def _browse(auth_uri): # throws ImportError, possibly webbrowser.Error in future
import webbrowser # Lazy import. Some distro may not have this.
return webbrowser.open(auth_uri) # Use default browser. Customizable by $BROWSER
browser_opened = webbrowser.open(auth_uri) # Use default browser. Customizable by $BROWSER

# In WSL which doesn't have www-browser, try launching browser with PowerShell
if not browser_opened and is_wsl():
try:
import subprocess
# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe
# Ampersand (&) should be quoted
exit_code = subprocess.call(
['powershell.exe', '-NoProfile', '-Command', 'Start-Process "{}"'.format(auth_uri)])
browser_opened = exit_code == 0
except FileNotFoundError: # WSL might be too old
pass
return browser_opened


def _qs2kv(qs):
Expand Down Expand Up @@ -245,4 +270,3 @@ def __exit__(self, exc_type, exc_val, exc_tb):
timeout=60,
state=flow["state"], # Optional
), indent=4))

26 changes: 26 additions & 0 deletions tests/test_authcode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from msal.oauth2cli.authcode import _browse

from tests import unittest
from unittest.mock import patch


class TestUtil(unittest.TestCase):

def test_browse(self):
auth_uri = "https://example.com/"

with patch("webbrowser.open", return_value=True):
self.assertTrue(_browse(auth_uri))

with patch("webbrowser.open", return_value=False):
with patch("msal.oauth2cli.authcode.is_wsl", return_value=False):
self.assertFalse(_browse(auth_uri))

with patch("msal.oauth2cli.authcode.is_wsl", return_value=True):
with patch("subprocess.call", return_value=0) as call_mock:
self.assertTrue(_browse(auth_uri))
call_mock.assert_called_with(
['powershell.exe', '-NoProfile', '-Command', 'Start-Process "https://example.com/"'])

with patch("subprocess.call", return_value=1):
self.assertFalse(_browse(auth_uri))