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

{Lab} Migrate lab command module to Microsoft Graph #29889

Merged
merged 1 commit into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -2339,11 +2339,10 @@ interactions:
accept-language:
- en-US
method: GET
uri: https://graph.windows.net/00000000-0000-0000-0000-000000000000/me?api-version=1.6
uri: https://graph.microsoft.com/v1.0/me
Copy link
Member Author

@jiasli jiasli Sep 11, 2024

Choose a reason for hiding this comment

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

I don't know why #29878 marked test_lab_vm as record_only:

@record_only()
def test_lab_vm(self):

so I manually edited the recording file.

response:
body:
string: '{"odata.metadata":"https://graph.windows.net/00000000-0000-0000-0000-000000000000/$metadata#directoryObjects/@Element","odata.type":"Microsoft.DirectoryServices.User","objectType":"User","objectId":"d44a2991-98c6-47c3-b59b-2b30d72cfcc2","deletionTimestamp":null,"accountEnabled":true,"ageGroup":null,"assignedLicenses":[],"assignedPlans":[],"city":null,"companyName":null,"consentProvidedForMinor":null,"country":null,"createdDateTime":"2021-04-07T05:58:20Z","creationType":"Invitation","department":null,"dirSyncEnabled":null,"displayName":"Jingsong
Zhang (WICRESOFT NORTH AMERICA LTD)","employeeId":null,"facsimileTelephoneNumber":null,"givenName":null,"immutableId":null,"isCompromised":null,"jobTitle":null,"lastDirSyncTime":null,"legalAgeGroupClassification":null,"mail":"[email protected]","mailNickname":"v-jingszhang_microsoft.com#EXT#","mobile":null,"onPremisesDistinguishedName":null,"onPremisesSecurityIdentifier":null,"otherMails":["[email protected]"],"passwordPolicies":null,"passwordProfile":null,"physicalDeliveryOfficeName":null,"postalCode":null,"preferredLanguage":null,"provisionedPlans":[],"provisioningErrors":[],"proxyAddresses":["SMTP:[email protected]"],"refreshTokensValidFromDateTime":"2021-04-07T05:58:20Z","showInAddressList":false,"signInNames":[],"sipProxyAddress":null,"state":null,"streetAddress":null,"surname":null,"telephoneNumber":null,"[email protected]":"directoryObjects/d44a2991-98c6-47c3-b59b-2b30d72cfcc2/Microsoft.DirectoryServices.User/thumbnailPhoto","usageLocation":null,"userIdentities":[],"userPrincipalName":"v-jingszhang_microsoft.com#EXT#@AzureSDKTeam.onmicrosoft.com","userState":"Accepted","userStateChangedOn":"2021-04-07T05:59:39Z","userType":"Guest"}'
string: '{"id":"d44a2991-98c6-47c3-b59b-2b30d72cfcc2"}'
headers:
access-control-allow-origin:
- '*'
Expand Down Expand Up @@ -2739,11 +2738,10 @@ interactions:
accept-language:
- en-US
method: GET
uri: https://graph.windows.net/00000000-0000-0000-0000-000000000000/me?api-version=1.6
uri: https://graph.microsoft.com/v1.0/me
response:
body:
string: '{"odata.metadata":"https://graph.windows.net/00000000-0000-0000-0000-000000000000/$metadata#directoryObjects/@Element","odata.type":"Microsoft.DirectoryServices.User","objectType":"User","objectId":"d44a2991-98c6-47c3-b59b-2b30d72cfcc2","deletionTimestamp":null,"accountEnabled":true,"ageGroup":null,"assignedLicenses":[],"assignedPlans":[],"city":null,"companyName":null,"consentProvidedForMinor":null,"country":null,"createdDateTime":"2021-04-07T05:58:20Z","creationType":"Invitation","department":null,"dirSyncEnabled":null,"displayName":"Jingsong
Zhang (WICRESOFT NORTH AMERICA LTD)","employeeId":null,"facsimileTelephoneNumber":null,"givenName":null,"immutableId":null,"isCompromised":null,"jobTitle":null,"lastDirSyncTime":null,"legalAgeGroupClassification":null,"mail":"[email protected]","mailNickname":"v-jingszhang_microsoft.com#EXT#","mobile":null,"onPremisesDistinguishedName":null,"onPremisesSecurityIdentifier":null,"otherMails":["[email protected]"],"passwordPolicies":null,"passwordProfile":null,"physicalDeliveryOfficeName":null,"postalCode":null,"preferredLanguage":null,"provisionedPlans":[],"provisioningErrors":[],"proxyAddresses":["SMTP:[email protected]"],"refreshTokensValidFromDateTime":"2021-04-07T05:58:20Z","showInAddressList":false,"signInNames":[],"sipProxyAddress":null,"state":null,"streetAddress":null,"surname":null,"telephoneNumber":null,"[email protected]":"directoryObjects/d44a2991-98c6-47c3-b59b-2b30d72cfcc2/Microsoft.DirectoryServices.User/thumbnailPhoto","usageLocation":null,"userIdentities":[],"userPrincipalName":"v-jingszhang_microsoft.com#EXT#@AzureSDKTeam.onmicrosoft.com","userState":"Accepted","userStateChangedOn":"2021-04-07T05:59:39Z","userType":"Guest"}'
string: '{"id":"d44a2991-98c6-47c3-b59b-2b30d72cfcc2"}'
headers:
access-control-allow-origin:
- '*'
Expand Down
72 changes: 2 additions & 70 deletions src/azure-cli/azure/cli/command_modules/lab/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,20 +91,8 @@ def validate_claim_vm(namespace):


def _get_owner_object_id(cli_ctx):
from azure.cli.core._profile import Profile
from azure.graphrbac.models import GraphErrorException
from azure.graphrbac import GraphRbacManagementClient
profile = Profile(cli_ctx=cli_ctx)
cred, _, tenant_id = profile.get_login_credentials(
resource=cli_ctx.cloud.endpoints.active_directory_graph_resource_id)
graph_client = GraphRbacManagementClient(cred,
tenant_id,
base_url=cli_ctx.cloud.endpoints.active_directory_graph_resource_id)
subscription = profile.get_subscription()
try:
return _get_current_user_object_id(graph_client)
except GraphErrorException:
return _get_object_id(graph_client, subscription=subscription)
from azure.cli.command_modules.role.util import get_current_identity_object_id
return get_current_identity_object_id(cli_ctx)


# pylint: disable=no-member
Expand Down Expand Up @@ -534,59 +522,3 @@ def _single(collection):

def _any(collection):
return len([x for x in collection if x]) > 0


def _get_current_user_object_id(graph_client):
try:
current_user = graph_client.signed_in_user.get()
if current_user and current_user.object_id: # pylint:disable=no-member
return current_user.object_id # pylint:disable=no-member
except HttpResponseError:
pass
return None


def _get_object_id(graph_client, subscription=None, spn=None, upn=None):
if spn:
return _get_object_id_by_spn(graph_client, spn)
if upn:
return _get_object_id_by_upn(graph_client, upn)
return _get_object_id_from_subscription(graph_client, subscription)


def _get_object_id_from_subscription(graph_client, subscription):
if subscription['user']:
if subscription['user']['type'] == 'user':
return _get_object_id_by_upn(graph_client, subscription['user']['name'])
if subscription['user']['type'] == 'servicePrincipal':
return _get_object_id_by_spn(graph_client, subscription['user']['name'])
logger.warning("Unknown user type '%s'", subscription['user']['type'])
else:
logger.warning('Current credentials are not from a user or service principal. '
'Azure DevTest Lab does not work with certificate credentials.')
return None


def _get_object_id_by_spn(graph_client, spn):
accounts = list(graph_client.service_principals.list(
filter="servicePrincipalNames/any(c:c eq '{}')".format(spn)))
if not accounts:
logger.warning("Unable to find user with spn '%s'", spn)
return None
if len(accounts) > 1:
logger.warning("Multiple service principals found with spn '%s'. "
"You can avoid this by specifying object id.", spn)
return None
return accounts[0].object_id


def _get_object_id_by_upn(graph_client, upn):
accounts = list(graph_client.users.list(filter="userPrincipalName eq '{}'".format(upn)))
if not accounts:
logger.warning("Unable to find user with upn '%s'", upn)
return None
if len(accounts) > 1:
logger.warning("Multiple users principals found with upn '%s'. "
"You can avoid this by specifying object id.", upn)
return None
return accounts[0].object_id
Loading