Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

identity_vscode_credential #10840

Merged
merged 82 commits into from
Apr 30, 2020
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
82 commits
Select commit Hold shift + click to select a range
0002805
identity_win_vscode_credential
xiangyan99 Apr 14, 2020
b1e79de
remove used import
xiangyan99 Apr 14, 2020
13fd676
update
xiangyan99 Apr 15, 2020
d356ba6
update
xiangyan99 Apr 15, 2020
41b0394
update
xiangyan99 Apr 15, 2020
526470d
update
xiangyan99 Apr 15, 2020
dc671f2
update
xiangyan99 Apr 15, 2020
5a47894
update shared requirements
xiangyan99 Apr 15, 2020
c797482
add async credential and tests
xiangyan99 Apr 15, 2020
25de404
update dev_requirements
xiangyan99 Apr 15, 2020
f48fdd4
add try in import
xiangyan99 Apr 15, 2020
a77e336
not raise
xiangyan99 Apr 15, 2020
9f5ad5d
update
xiangyan99 Apr 15, 2020
d155f80
mac os support
xiangyan99 Apr 15, 2020
015f1f7
update
xiangyan99 Apr 15, 2020
bfa2ea1
update msal version
xiangyan99 Apr 15, 2020
16873bd
roll back msal change
xiangyan99 Apr 15, 2020
58844b9
remove dependency on pywin32
xiangyan99 Apr 16, 2020
05694a9
update
xiangyan99 Apr 16, 2020
671d5ea
update
xiangyan99 Apr 16, 2020
921b7a2
update
xiangyan99 Apr 16, 2020
3911b88
add tests
xiangyan99 Apr 16, 2020
f313ba4
add pygobject dependency
xiangyan99 Apr 16, 2020
283a055
linux support
xiangyan99 Apr 16, 2020
9974361
update
xiangyan99 Apr 16, 2020
4e7b9c4
updates
xiangyan99 Apr 16, 2020
bbe7a20
updates
xiangyan99 Apr 16, 2020
94b152b
pylint fix
xiangyan99 Apr 16, 2020
657617c
updates
xiangyan99 Apr 17, 2020
426dea7
updates
xiangyan99 Apr 17, 2020
f9a2abf
updates
xiangyan99 Apr 17, 2020
593a62f
update tests
xiangyan99 Apr 17, 2020
0805e74
format
xiangyan99 Apr 17, 2020
eaf10cb
add type checking
xiangyan99 Apr 17, 2020
e1dab12
refactor code
xiangyan99 Apr 17, 2020
9c33cfd
remove unused import
xiangyan99 Apr 17, 2020
d072e20
updates
xiangyan99 Apr 17, 2020
6024a9a
remove pygobject dependency
xiangyan99 Apr 17, 2020
a63e157
updates
xiangyan99 Apr 18, 2020
a8d45c0
typo
xiangyan99 Apr 18, 2020
2fca38a
update tests
xiangyan99 Apr 18, 2020
3866a93
update mac tests
xiangyan99 Apr 18, 2020
ebb5df2
add linux tests
xiangyan99 Apr 18, 2020
595cdea
updates
xiangyan99 Apr 18, 2020
246ab2d
updates
xiangyan99 Apr 18, 2020
af482e6
clean up
xiangyan99 Apr 18, 2020
57953ba
mock patch not work well on async 3.8+
xiangyan99 Apr 18, 2020
022f376
refactor code
xiangyan99 Apr 21, 2020
7e15ddd
pylint
xiangyan99 Apr 21, 2020
975f6ed
pylint
xiangyan99 Apr 21, 2020
767906f
add tests for win apis
xiangyan99 Apr 22, 2020
1e10649
use __module__
xiangyan99 Apr 22, 2020
cf54345
update
xiangyan99 Apr 22, 2020
e43a74f
update
xiangyan99 Apr 22, 2020
4fe1be3
add tests
xiangyan99 Apr 22, 2020
0fd89e6
typo
xiangyan99 Apr 22, 2020
5524ea9
update
xiangyan99 Apr 22, 2020
ff9d532
update
xiangyan99 Apr 22, 2020
e6b83ca
update
xiangyan99 Apr 22, 2020
9232a3b
Update sdk/identity/azure-identity/tests/test_vscode_credential.py
xiangyan99 Apr 23, 2020
9ea845e
updates
xiangyan99 Apr 23, 2020
77f8838
update
xiangyan99 Apr 23, 2020
0f69230
update
xiangyan99 Apr 23, 2020
ec1f0a3
update
xiangyan99 Apr 27, 2020
4fadaf3
update
xiangyan99 Apr 27, 2020
435fdce
update
xiangyan99 Apr 27, 2020
cb74ce2
updates
xiangyan99 Apr 28, 2020
a402f3b
update
xiangyan99 Apr 28, 2020
853dd3e
update
xiangyan99 Apr 28, 2020
54d1b48
update
xiangyan99 Apr 29, 2020
75624b8
disable on 2.7
xiangyan99 Apr 29, 2020
ed1db0c
raise on Python 2.7 Linux
xiangyan99 Apr 29, 2020
6fc8708
fix typo
xiangyan99 Apr 29, 2020
7d36ad5
update
xiangyan99 Apr 29, 2020
6f8ae61
update
xiangyan99 Apr 30, 2020
42270b8
check error
xiangyan99 Apr 30, 2020
5c8bcec
update
xiangyan99 Apr 30, 2020
77cc4d8
add vs code credential to default
xiangyan99 Apr 30, 2020
10a9e43
Merge branch 'master' into identity_vcode_credential
xiangyan99 Apr 30, 2020
ff8e1c7
update
xiangyan99 Apr 30, 2020
8efee5c
update
xiangyan99 Apr 30, 2020
a5dc253
updates
xiangyan99 Apr 30, 2020
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
3 changes: 2 additions & 1 deletion sdk/identity/azure-identity/azure/identity/_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@


AZURE_CLI_CLIENT_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"

AZURE_VSCODE_CLIENT_ID = "aebc6443-996d-45c2-90f0-388ff96faa56"
VSCODE_CREDENTIALS_SECTION = "VS Code Azure"

class KnownAuthorities:
AZURE_CHINA = "login.chinacloudapi.cn"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import json
from msal_extensions.osx import Keychain
from .._exceptions import CredentialUnavailableError
from .._constants import (
VSCODE_CREDENTIALS_SECTION,
AZURE_VSCODE_CLIENT_ID,
)
from .._internal.aad_client import AadClient


def _get_user_settings_path():
app_data_folder = os.environ['USERPROFILE']
return os.path.join(app_data_folder, "Library", "Application Support", "Code", "User", "settings.json")


def _get_user_settings():
path = _get_user_settings_path()
try:
with open(path) as file:
data = json.load(file)
environment_name = data.get("azure.cloud", "Azure")
return environment_name
except IOError:
return "Azure"


class MacOSVSCodeCredential(object):
"""Authenticates by redeeming a refresh token previously saved by VS Code

"""
def __init__(self, **kwargs):
self._client = kwargs.pop("client", None) or AadClient("organizations", AZURE_VSCODE_CLIENT_ID, **kwargs)
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved

def get_token(self, *scopes, **kwargs):
# type: (*str, **Any) -> AccessToken
"""Request an access token for `scopes`.

.. note:: This method is called by Azure SDK clients. It isn't intended for use in application code.

The first time this method is called, the credential will redeem its authorization code. On subsequent calls
the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon
redeeming the authorization code.

xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved
:param str scopes: desired scopes for the access token. This method requires at least one scope.
:rtype: :class:`azure.core.credentials.AccessToken`
:raises ~azure.identity.CredentialUnavailableError: fail to get refresh token.
"""
if not scopes:
raise ValueError("'get_token' requires at least one scope")

environment_name = _get_user_settings()
key_chain = Keychain()
refresh_token = key_chain.get_generic_password(VSCODE_CREDENTIALS_SECTION, environment_name)
if not refresh_token:
raise CredentialUnavailableError(
message="No token available."
)
token = self._client.obtain_token_by_refresh_token(refresh_token, scopes, **kwargs)
return token
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import json
import ctypes as ct
from .._exceptions import CredentialUnavailableError
from .._constants import (
VSCODE_CREDENTIALS_SECTION,
AZURE_VSCODE_CLIENT_ID,
)
from .._internal.aad_client import AadClient
try:
import ctypes.wintypes as wt
except (IOError, ValueError):
pass

SUPPORTED_CREDKEYS = set((
'Type', 'TargetName', 'Persist',
'UserName', 'Comment', 'CredentialBlob'))


class _CREDENTIAL(ct.Structure):
_fields_ = [
("Flags", wt.DWORD),
("Type", wt.DWORD),
("TargetName", ct.c_wchar_p),
("Comment", ct.c_wchar_p),
("LastWritten", wt.FILETIME),
("CredentialBlobSize", wt.DWORD),
("CredentialBlob", wt.LPBYTE),
("Persist", wt.DWORD),
("AttributeCount", wt.DWORD),
("Attributes", ct.c_void_p),
("TargetAlias", ct.c_wchar_p),
("UserName", ct.c_wchar_p)]

@classmethod
def from_dict(cls, credential):
# pylint:disable=attribute-defined-outside-init
creds = cls()
pcreds = _PCREDENTIAL(creds)

ct.memset(pcreds, 0, ct.sizeof(creds))

for key in SUPPORTED_CREDKEYS:
if key in credential:
if key != 'CredentialBlob':
setattr(creds, key, credential[key])
else:
blob = credential['CredentialBlob']
blob_data = ct.create_unicode_buffer(blob)
creds.CredentialBlobSize = \
ct.sizeof(blob_data) - \
ct.sizeof(ct.c_wchar)
creds.CredentialBlob = ct.cast(blob_data, wt.LPBYTE)
return creds


_PCREDENTIAL = ct.POINTER(_CREDENTIAL)


_advapi = ct.WinDLL('advapi32')
_advapi.CredWriteW.argtypes = [_PCREDENTIAL, wt.DWORD]
_advapi.CredWriteW.restype = wt.BOOL
_advapi.CredReadW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.POINTER(_PCREDENTIAL)]
_advapi.CredReadW.restype = wt.BOOL
_advapi.CredFree.argtypes = [_PCREDENTIAL]
_advapi.CredDeleteW.restype = wt.BOOL
_advapi.CredDeleteW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD]


def _cred_write(credential):
creds = _CREDENTIAL.from_dict(credential)
cred_ptr = _PCREDENTIAL(creds)
_advapi.CredWriteW(cred_ptr, 0)


def _cred_delete(service_name, account_name):
target = u"{}/{}".format(service_name, account_name)
_advapi.CredDeleteW(target, 1, 0)


def _read_credential(service_name, account_name):
target = u"{}/{}".format(service_name, account_name)
cred_ptr = _PCREDENTIAL()
if _advapi.CredReadW(target, 1, 0, ct.byref(cred_ptr)):
cred_blob = cred_ptr.contents.CredentialBlob
cred_blob_size = cred_ptr.contents.CredentialBlobSize
password_as_list = [int.from_bytes(cred_blob[pos:pos + 2], 'little')
for pos in range(0, cred_blob_size, 2)]
cred = ''.join(map(chr, password_as_list))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think these three lines could just be cred = cred_blob.decode("utf-16-le"), right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried both cred = str(cred_blob, "utf-16") & cred = str(cred_blob, "utf-16-le"), neither of them worked correctly.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at the value on my machine for this, they're storing it as ASCII, not UTF-16. (Specifically, it looks like URL-safe base64 encoding without padding, but that probably doesn't matter as I think you just use this directly, right?)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. In our case, we use it directly.

_advapi.CredFree(cred_ptr)
return cred
return None


def _get_user_settings_path():
app_data_folder = os.environ['APPDATA']
return os.path.join(app_data_folder, "Code", "User", "settings.json")


def _get_user_settings():
path = _get_user_settings_path()
try:
with open(path) as file:
data = json.load(file)
environment_name = data.get("azure.cloud", "Azure")
return environment_name
except IOError:
return "Azure"


class WinVSCodeCredential(object):
"""Authenticates by redeeming a refresh token previously saved by VS Code

"""
def __init__(self, **kwargs):
self._client = kwargs.pop("client", None) or AadClient("organizations", AZURE_VSCODE_CLIENT_ID, **kwargs)

def get_token(self, *scopes, **kwargs):
# type: (*str, **Any) -> AccessToken
"""Request an access token for `scopes`.

.. note:: This method is called by Azure SDK clients. It isn't intended for use in application code.

When this method is called, the credential will try to get the refresh token saved by VS Code. If a refresh
token can be found, it will redeem the refresh token for an access token and return the access token.

:param str scopes: desired scopes for the access token. This method requires at least one scope.
:rtype: :class:`azure.core.credentials.AccessToken`
:raises ~azure.identity.CredentialUnavailableError: fail to get refresh token.
"""
if not scopes:
raise ValueError("'get_token' requires at least one scope")

environment_name = _get_user_settings()
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved
refresh_token = _read_credential(VSCODE_CREDENTIALS_SECTION, environment_name)
if not refresh_token:
raise CredentialUnavailableError(
message="No token available."
)
token = self._client.obtain_token_by_refresh_token(refresh_token, scopes, **kwargs)
return token
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import asyncio
from msal_extensions.osx import Keychain
from ..._exceptions import CredentialUnavailableError
from .._credentials.base import AsyncCredentialBase
from ..._constants import (
VSCODE_CREDENTIALS_SECTION,
AZURE_VSCODE_CLIENT_ID,
)
from .._internal.aad_client import AadClient
from ..._credentials.macos_vscode_credential import _get_user_settings


class MacOSVSCodeCredential(AsyncCredentialBase):
"""Authenticates by redeeming a refresh token previously saved by VS Code

"""
def __init__(self, **kwargs):
self._client = kwargs.pop("client", None) or AadClient("organizations", AZURE_VSCODE_CLIENT_ID, **kwargs)
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved

async def __aenter__(self):
if self._client:
await self._client.__aenter__()
return self

async def close(self):
"""Close the credential's transport session."""

if self._client:
await self._client.__aexit__()

async def get_token(self, *scopes, **kwargs):
# type: (*str, **Any) -> AccessToken
"""Request an access token for `scopes`.

.. note:: This method is called by Azure SDK clients. It isn't intended for use in application code.

The first time this method is called, the credential will redeem its authorization code. On subsequent calls
the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon
redeeming the authorization code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
The first time this method is called, the credential will redeem its authorization code. On subsequent calls
the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon
redeeming the authorization code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leftover copy pasta here.

:param str scopes: desired scopes for the access token. This method requires at least one scope.
:rtype: :class:`azure.core.credentials.AccessToken`
:raises ~azure.identity.CredentialUnavailableError: fail to get refresh token.
"""
if not scopes:
raise ValueError("'get_token' requires at least one scope")

environment_name = _get_user_settings()
key_chain = Keychain()
refresh_token = key_chain.get_generic_password(VSCODE_CREDENTIALS_SECTION, environment_name)
if not refresh_token:
raise CredentialUnavailableError(
message="No token available."
)
loop = kwargs.pop("loop", None) or asyncio.get_event_loop()
token = await self._client.obtain_token_by_refresh_token(
refresh_token, scopes, loop=loop, **kwargs)
return token
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import asyncio
from ..._exceptions import CredentialUnavailableError
from .._credentials.base import AsyncCredentialBase
from ..._constants import (
VSCODE_CREDENTIALS_SECTION,
AZURE_VSCODE_CLIENT_ID,
)
from .._internal.aad_client import AadClient
try:
from ..._credentials.win_vscode_credential import _read_credential, _get_user_settings
except ImportError:
pass


class WinVSCodeCredential(AsyncCredentialBase):
"""Authenticates by redeeming a refresh token previously saved by VS Code

"""
def __init__(self, **kwargs):
self._client = kwargs.pop("client", None) or AadClient("organizations", AZURE_VSCODE_CLIENT_ID, **kwargs)

async def __aenter__(self):
if self._client:
await self._client.__aenter__()
return self

async def close(self):
"""Close the credential's transport session."""

if self._client:
await self._client.__aexit__()

async def get_token(self, *scopes, **kwargs):
# type: (*str, **Any) -> AccessToken
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved
"""Request an access token for `scopes`.

.. note:: This method is called by Azure SDK clients. It isn't intended for use in application code.

When this method is called, the credential will try to get the refresh token saved by VS Code. If a refresh
token can be found, it will redeem the refresh token for an access token and return the access token.

:param str scopes: desired scopes for the access token. This method requires at least one scope.
:rtype: :class:`azure.core.credentials.AccessToken`
:raises ~azure.identity.CredentialUnavailableError: fail to get refresh token.
"""
if not scopes:
raise ValueError("'get_token' requires at least one scope")

environment_name = _get_user_settings()
refresh_token = _read_credential(VSCODE_CREDENTIALS_SECTION, environment_name)
if not refresh_token:
raise CredentialUnavailableError(
message="No token available."
)
loop = kwargs.pop("loop", None) or asyncio.get_event_loop()
token = await self._client.obtain_token_by_refresh_token(
refresh_token, scopes, loop=loop, **kwargs)
return token
1 change: 1 addition & 0 deletions sdk/identity/azure-identity/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
"msal<2.0.0,>=1.0.0",
"msal-extensions~=0.1.3",
"six>=1.6",
"pygobject>=3,<4;platform_system=='Linux'",
],
extras_require={
":python_version<'3.0'": ["azure-nspkg"],
Expand Down
31 changes: 31 additions & 0 deletions sdk/identity/azure-identity/tests/test_macos_vscode_credential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import sys
import pytest
from azure.core.credentials import AccessToken
try:
from azure.identity._credentials.macos_vscode_credential import MacOSVSCodeCredential
except (ImportError, OSError):
pass
try:
from unittest.mock import Mock
except ImportError: # python < 3.3
from mock import Mock # type: ignore


@pytest.mark.skipif(not sys.platform.startswith('darwin'), reason="This test only runs on Windows")
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved
def test_get_token():
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved
expected_token = AccessToken("token", 42)

mock_client = Mock(spec=object)
mock_client.obtain_token_by_refresh_token = Mock(return_value=expected_token)

credential = MacOSVSCodeCredential(
client=mock_client,
)

token = credential.get_token("scope")
assert token is expected_token
assert mock_client.obtain_token_by_refresh_token.call_count == 1
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved
Loading