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

KeyError: 'AndroidEnterpriseDedicatedDevice #457

Closed
pouriyajamshidi opened this issue Nov 13, 2023 · 7 comments
Closed

KeyError: 'AndroidEnterpriseDedicatedDevice #457

pouriyajamshidi opened this issue Nov 13, 2023 · 7 comments
Labels
bug Something isn't working dependencies Pull requests that update a dependency file

Comments

@pouriyajamshidi
Copy link

Hi,

I am developing an application for my company that requires talking to Azure to manage devices.

While pulling down the managed devices through this SDK, the program crashes with a KeyError: 'AndroidEnterpriseDedicatedDevice' error

Here is the code to reproduce:

import asyncio

from azure.identity.aio import ClientSecretCredential
from kiota_abstractions.api_error import APIError
from msgraph import GraphServiceClient
from msgraph.generated.device_management.managed_devices.managed_devices_request_builder import (
   ManagedDevicesRequestBuilder,
)
from msgraph.generated.models.group_collection_response import GroupCollectionResponse

class AzureGraph:
   def __init__(self) -> None:
       self.__credentials: ClientSecretCredential = self._get_azure_credentials()
       self._scopes: list[str] = ["https://graph.microsoft.com/.default"]
       self._client = GraphServiceClient(
           credentials=self.__credentials, scopes=self._scopes
       )

   def _get_azure_credentials(self) -> ClientSecretCredential:
       return ClientSecretCredential(
           tenant_id="tenant_id",
           client_id="client_id",
           client_secret="client_secret",
       )

   def list_managed_devices_filtered(self, search_query: str) -> None:
       async def _list_managed_devices_filtered() -> None:
           query_parameters = ManagedDevicesRequestBuilder.ManagedDevicesRequestBuilderGetQueryParameters(
               filter=search_query
           )
           request_configuration = ManagedDevicesRequestBuilder.ManagedDevicesRequestBuilderGetRequestConfiguration(
               query_parameters=query_parameters
           )

           try:
               groups: GroupCollectionResponse | None = (
                   await self._client.device_management.managed_devices.get(
                       request_configuration=request_configuration
                   )
               )
               _ = groups.value

           except APIError as e:
               raise SystemExit("Could not get Azure managed devices") from e

       asyncio.run(_list_managed_devices_filtered())



if __name__ == "__main__":
   az = AzureGraph()
   az.list_managed_devices_filtered("startswith(emailAddress, 'pouriya')")

Here is the full console output:

2023-11-13 11:40:22 INFO     Retrieving Azure Graph credentials
2023-11-13 11:40:22 DEBUG    Using selector: EpollSelector
2023-11-13 11:40:22 INFO     Request URL: '[https://login.microsoftonline.com/[REDACTED]/oauth2/v2.0/token](https://login.microsoftonline.com/%5BREDACTED%5D/oauth2/v2.0/token)'
Request method: 'POST'
Request headers:
    'Content-Type': 'application/x-www-form-urlencoded'
    'User-Agent': 'azsdk-python-identity/1.12.0 Python/3.11.3 (Linux-5.15.90.1-microsoft-standard-WSL2-x86_64-with-glibc2.31)'
A body is sent with the request
2023-11-13 11:40:22 INFO     Response status: 200
Response headers:
    'Cache-Control': 'no-store, no-cache'
    'Pragma': 'no-cache'
    'Content-Type': 'application/json; charset=utf-8'
    'Expires': '-1'
    'Strict-Transport-Security': 'REDACTED'
    'X-Content-Type-Options': 'REDACTED'
    'P3P': 'REDACTED'
    'x-ms-request-id': 'REDACTED'
    'x-ms-ests-server': 'REDACTED'
    'X-XSS-Protection': 'REDACTED'
    'Set-Cookie': 'REDACTED'
    'Set-Cookie': 'REDACTED'
    'Set-Cookie': 'REDACTED'
    'Date': 'Mon, 13 Nov 2023 10:40:21 GMT'
    'Content-Length': '1783'
2023-11-13 11:40:22 DEBUG    event={
    "client_id": "REDACTED",
    "response": {
        "access_token": "********",
        "expires_in": 3599,
        "ext_expires_in": 3599,
        "token_type": "Bearer"
    },
    "scope": [
        https://graph.microsoft.com/.default
    ],
    "token_endpoint": [https://login.microsoftonline.com/[REDACTED]/oauth2/v2.0/token](https://login.microsoftonline.com/%5BREDACTED%5D/oauth2/v2.0/token)
}
2023-11-13 11:40:22 INFO     ClientSecretCredential.get_token succeeded
2023-11-13 11:40:22 DEBUG    connect_tcp.started host='[graph.microsoft.com](http://graph.microsoft.com/)' port=443 local_address=None timeout=30 socket_options=None
2023-11-13 11:40:22 DEBUG    connect_tcp.complete return_value=<httpcore._backends.anyio.AnyIOStream object at 0x7f493cb47e20>
2023-11-13 11:40:22 DEBUG    start_tls.started ssl_context=<ssl.SSLContext object at 0x7f493d05cdc0> server_hostname='[graph.microsoft.com](http://graph.microsoft.com/)' timeout=30
2023-11-13 11:40:22 DEBUG    start_tls.complete return_value=<httpcore._backends.anyio.AnyIOStream object at 0x7f493cb47370>
2023-11-13 11:40:22 DEBUG    send_request_headers.started request=<Request [b'GET']>
2023-11-13 11:40:22 DEBUG    send_request_headers.complete
2023-11-13 11:40:22 DEBUG    send_request_body.started request=<Request [b'GET']>
2023-11-13 11:40:22 DEBUG    send_request_body.complete
2023-11-13 11:40:22 DEBUG    receive_response_headers.started request=<Request [b'GET']>
2023-11-13 11:40:24 DEBUG    receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Transfer-Encoding', b'chunked'), (b'Content-Type', b'application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8'), (b'Content-Encoding', b'gzip'), (b'Vary', b'Accept-Encoding'), (b'Strict-Transport-Security', b'max-age=31536000'), (b'request-id', b'1778798c-eaf1-4b76-a23f-10c066239fc3'), (b'client-request-id', b'fbf78a39-d798-4826-8343-870b23705abf'), (b'x-ms-ags-diagnostic', b'{"ServerInfo":{"DataCenter":"West Europe","Slice":"E","Ring":"5","ScaleUnit":"011","RoleInstance":"AM2PEPF0001BE82"}}'), (b'OData-Version', b'4.0'), (b'Date', b'Mon, 13 Nov 2023 10:40:23 GMT')]
2023-11-13 11:40:24 INFO     HTTP Request: GET https://graph.microsoft.com/v1.0/deviceManagement/managedDevices "HTTP/1.1 200 OK"
2023-11-13 11:40:24 DEBUG    receive_response_body.started request=<Request [b'GET']>
2023-11-13 11:40:24 DEBUG    receive_response_body.complete
2023-11-13 11:40:24 DEBUG    response_closed.started
2023-11-13 11:40:24 DEBUG    response_closed.complete
Traceback (most recent call last):
  File "OUR_APP/lib/python3.10/site-packages/kiota_serialization_json/json_parse_node.py", line 199, in get_enum_value
    return enum_class[camel_case_key]  # type: ignore
  File "/home/pouriya/.pyenv/versions/3.11.3/lib/python3.11/enum.py", line 440, in __getitem__
    return cls._member_map_[name]
KeyError: 'AndroidEnterpriseDedicatedDevice'

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/pouriya//src/azuregraph.py", line 225, in <module>
    az.list_managed_devices()
  File "/home/pouriya//src/azuregraph.py", line 184, in list_managed_devices
    asyncio.run(_list_managed_devices())
  File "/home/pouriya/.pyenv/versions/3.11.3/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/home/pouriya/.pyenv/versions/3.11.3/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "/home/pouriya//src/azuregraph.py", line 171, in _list_managed_devices
    await self._client.device_management.managed_devices.get()
  File "OUR_APP/lib/python3.10/site-packages/msgraph/generated/device_management/managed_devices/managed_devices_request_builder.py", line 66, in get
    return await self.request_adapter.send_async(request_info, ManagedDeviceCollectionResponse, error_mapping)
  File "OUR_APP/lib/python3.10/site-packages/kiota_http/httpx_request_adapter.py", line 181, in send_async
    value = root_node.get_object_value(parsable_factory)
  File "OUR_APP/lib/python3.10/site-packages/kiota_serialization_json/json_parse_node.py", line 212, in get_object_value
    self._assign_field_values(result)
  File "OUR_APP/lib/python3.10/site-packages/kiota_serialization_json/json_parse_node.py", line 281, in _assign_field_values
    field_deserializer(JsonParseNode(field_value))
  File "OUR_APP/lib/python3.10/site-packages/msgraph/generated/models/managed_device_collection_response.py", line 40, in <lambda>
    "value": lambda n : setattr(self, 'value', n.get_collection_of_object_values(ManagedDevice)),
  File "OUR_APP/lib/python3.10/site-packages/kiota_serialization_json/json_parse_node.py", line 163, in get_collection_of_object_values
    return list(
  File "OUR_APP/lib/python3.10/site-packages/kiota_serialization_json/json_parse_node.py", line 165, in <lambda>
    lambda x: self._create_new_node(x).get_object_value(factory),  # type: ignore
  File "OUR_APP/lib/python3.10/site-packages/kiota_serialization_json/json_parse_node.py", line 212, in get_object_value
    self._assign_field_values(result)
  File "OUR_APP/lib/python3.10/site-packages/kiota_serialization_json/json_parse_node.py", line 281, in _assign_field_values
    field_deserializer(JsonParseNode(field_value))
  File "OUR_APP/lib/python3.10/site-packages/msgraph/generated/models/managed_device.py", line 222, in <lambda>
    "deviceEnrollmentType": lambda n : setattr(self, 'device_enrollment_type', n.get_enum_value(DeviceEnrollmentType)),
  File "OUR_APP/lib/python3.10/site-packages/kiota_serialization_json/json_parse_node.py", line 201, in get_enum_value
    raise Exception(f'Invalid key: {camel_case_key} for enum {enum_class}.')
Exception: Invalid key: AndroidEnterpriseDedicatedDevice for enum <enum 'DeviceEnrollmentType'>.

The fix is to add AndroidEnterpriseDedicatedDevice = "androidUserEnrollmentWithServiceAccount", under DeviceEnrollmentType class inside msgraph/generated/models/device_enrollment_type.py

Please let me know if you have any other questions.

I could open a PR for this but since I reached out to @baywet , it became clear that this code is automatically generated and PRs might not get through.

@baywet baywet added bug Something isn't working dependencies Pull requests that update a dependency file labels Nov 13, 2023
@baywet
Copy link
Member

baywet commented Nov 13, 2023

Thanks for reporting this @pouriyajamshidi
This part of the code is automatically generated from the metadata, the issue here is the service is returning a value not described in the metadata.
We won't be accepting a pull request for that, as it would be overwritten on the next generation run.

@samwelkanda Can you create an ICM on the relevant team so they either stop returning those values or amend their metadata please?

(for reference, here is the endpoint we're referring to https://learn.microsoft.com/en-us/graph/api/intune-devices-manageddevice-list?view=graph-rest-1.0&tabs=http)

@pouriyajamshidi
Copy link
Author

Thanks @baywet for your prompt response.

@UnlawfulMonad
Copy link

This is a duplicate of #443 but this is a better report so I'll close that issue

@andrueastman
Copy link
Member

Possibly related to microsoft/kiota-serialization-json-python#265

@baywet
Copy link
Member

baywet commented Apr 15, 2024

@samwelkanda Can you confirm whether you had created an ICM at the time for the workload to add the missing enum values in the description please?
Everyone impacted by the issue, can you try with the version 1.2.0 of the json serialization package and see if it solves you problem please?

@srmo
Copy link

srmo commented Jun 19, 2024

Just encountered this with AndroidEnterpriseCorporateWorkProfile.
I then tried the 1.2.0 kiota serialization package and that worked ( @baywet ), i.e. it no longer throws the exception but returns the expected devices.

PS: I didn't perform any additional tests so can't rule out if kiota-serial 1.2.0 has sideeffects on the rest of my code

@baywet
Copy link
Member

baywet commented Jun 19, 2024

Thanks for confirming. Closing since the issue has been solved in the serialization library.

@baywet baywet closed this as completed Jun 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working dependencies Pull requests that update a dependency file
Projects
None yet
Development

No branches or pull requests

7 participants