microsoftgraph/msgraph-sdk-python-core

Multiple GraphClient instantiations overwriting scopes

stephenleeoyo opened this issue · 2 comments

I am writing a custom MS Graph API wrapper package that follows the principle of least privilege, where each module in my package instantiates a GraphClient with its own necessary scopes needed to function properly. I discovered that the GraphClient's __new__ method is preventing two separate modules from each instantiating a GraphClient with their own scopes - rather, they are forced to share the same instance, with the second set of instantiated scopes taking precedence.

To circumvent this, I have been able to dig deep and blend the scopes manually across instantiations, but it's a rather ugly line of code hitting a bunch of protected variables, and I have no certainty the object structure won't change going forward:

class MyClass:
    def __init__(self, credential, **kwargs):
        if GraphClient._GraphClient__instance is not None and 'scopes' in kwargs:
            old = GraphClient._GraphClient__instance.graph_session.adapters.get('https://')._first_middleware.scopes
            kwargs['scopes'] = list(set(kwargs['scopes'] + old))
        self.client = GraphClient(credential=credential, **kwargs)

I don't mind the usage of the shared GraphClient instances, but perhaps providing a built-in option to persist the existing scopes would be a much cleaner solution.

To replicate my example:

from msgraph.core import GraphClient
from azure.identity import DefaultAzureCredential

dac = DefaultAzureCredential()

gc1 = GraphClient(credential=dac, scopes=['user.read'])
gc2 = GraphClient(credential=dac, scopes=['files.readwrite.all'])

print(gc1.graph_session.adapters.get("https://")._first_middleware.scopes)
print(gc2.graph_session.adapters.get("https://")._first_middleware.scopes)

returns

['files.readwrite.all']
['files.readwrite.all']

Note that the user.read scope provided to gc1 has been overwritten.

Hello @stephenleeoyo, my sincere apologies for the delays attending this issue. Would you be so kind to try again using the newest version of the SDK, please? Let me know if the issue persists.

Hello @stephenleeoyo,

I am closing this issue for now. My sincere apologies for the delay in our response. Please use the newest version of the SDK and stay tuned for the GA version coming soon.

Feel free to reach put again if you find a similar issue with the new SDK.

Kind regards,

Isaac Vargas