From 44ccfd7a834f88112848b56f5a99e9ea06b3745c Mon Sep 17 00:00:00 2001 From: Artem Shelkovnikov Date: Fri, 10 Jan 2025 12:44:48 +0100 Subject: [PATCH] Add authentication via Entra with a certificate (#3064) Co-authored-by: Sean Story --- NOTICE.txt | 67 +++++++ connectors/sources/sharepoint_online.py | 183 +++++++++++++++--- requirements/framework.txt | 1 + .../fixtures/sharepoint_online/connector.json | 98 ++++++++-- tests/sources/test_sharepoint_online.py | 148 +++++++++++--- 5 files changed, 428 insertions(+), 69 deletions(-) diff --git a/NOTICE.txt b/NOTICE.txt index 2ca29e78f..7c8399491 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -2010,6 +2010,31 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +azure-identity +1.19.0 +MIT License +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + azure-storage-blob 12.19.1 MIT License @@ -6277,6 +6302,32 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +msal-extensions +1.2.0 +MIT License + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + + multidict 6.1.0 Apache Software License @@ -6633,6 +6684,22 @@ ply BSD UNKNOWN +portalocker +2.10.1 +BSD License +Copyright 2022 Rick van Hattem + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + propcache 0.2.0 Apache Software License diff --git a/connectors/sources/sharepoint_online.py b/connectors/sources/sharepoint_online.py index 99bfb6157..f0e9f3f8d 100644 --- a/connectors/sources/sharepoint_online.py +++ b/connectors/sources/sharepoint_online.py @@ -18,6 +18,7 @@ from aiofiles.tempfile import NamedTemporaryFile from aiohttp.client_exceptions import ClientPayloadError, ClientResponseError from aiohttp.client_reqrep import RequestInfo +from azure.identity.aio import CertificateCredential from fastjsonschema import JsonSchemaValueException from connectors.access_control import ( @@ -193,7 +194,7 @@ class MicrosoftSecurityToken: - https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app """ - def __init__(self, http_session, tenant_id, tenant_name, client_id, client_secret): + def __init__(self, http_session, tenant_id, tenant_name, client_id): """Initializer. Args: @@ -207,7 +208,6 @@ def __init__(self, http_session, tenant_id, tenant_name, client_id, client_secre self._tenant_id = tenant_id self._tenant_name = tenant_name self._client_id = client_id - self._client_secret = client_secret self._token_cache = CacheWithTimeout() @@ -226,10 +226,8 @@ async def get(self): if cached_value: return cached_value - # We measure now before request to be on a pessimistic side - now = datetime.utcnow() try: - access_token, expires_in = await self._fetch_token() + access_token, expires_at = await self._fetch_token() except ClientResponseError as e: # Both Graph API and REST API return error codes that indicate different problems happening when authenticating. # Error Code serves as a good starting point classifying these errors, see the messages below: @@ -244,7 +242,7 @@ async def get(self): msg = f"Failed to authorize to Sharepoint REST API. Response Status: {e.status}, Message: {e.message}" raise TokenFetchFailed(msg) from e - self._token_cache.set_value(access_token, now + timedelta(seconds=expires_in)) + self._token_cache.set_value(access_token, expires_at) return access_token @@ -260,7 +258,16 @@ async def _fetch_token(self): raise NotImplementedError -class GraphAPIToken(MicrosoftSecurityToken): +class SecretAPIToken(MicrosoftSecurityToken): + def __init__(self, http_session, tenant_id, tenant_name, client_id, client_secret): + super().__init__(http_session, tenant_id, tenant_name, client_id) + self._client_secret = client_secret + + async def _fetch_token(self): + return await super()._fetch_token() + + +class GraphAPIToken(SecretAPIToken): """Token to connect to Microsoft Graph API endpoints.""" @retryable(retries=3) @@ -275,15 +282,17 @@ async def _fetch_token(self): headers = {"Content-Type": "application/x-www-form-urlencoded"} data = f"client_id={self._client_id}&scope=https://graph.microsoft.com/.default&client_secret={self._client_secret}&grant_type=client_credentials" + # We measure now before request to be on a pessimistic side + now = datetime.utcnow() async with self._http_session.post(url, headers=headers, data=data) as resp: json_response = await resp.json() access_token = json_response["access_token"] expires_in = int(json_response["expires_in"]) - return access_token, expires_in + return access_token, now + timedelta(seconds=expires_in) -class SharepointRestAPIToken(MicrosoftSecurityToken): +class SharepointRestAPIToken(SecretAPIToken): """Token to connect to Sharepoint REST API endpoints.""" @retryable(retries=DEFAULT_RETRY_COUNT) @@ -304,12 +313,51 @@ async def _fetch_token(self): } headers = {"Content-Type": "application/x-www-form-urlencoded"} + # We measure now before request to be on a pessimistic side + now = datetime.utcnow() async with self._http_session.post(url, headers=headers, data=data) as resp: json_response = await resp.json() access_token = json_response["access_token"] expires_in = int(json_response["expires_in"]) - return access_token, expires_in + return access_token, now + timedelta(seconds=expires_in) + + +class EntraAPIToken(MicrosoftSecurityToken): + """Token to connect to Microsoft Graph API endpoints.""" + + def __init__( + self, + http_session, + tenant_id, + tenant_name, + client_id, + certificate, + private_key, + scope, + ): + super().__init__(http_session, tenant_id, tenant_name, client_id) + self._certificate = certificate + self._private_key = private_key + self._scope = scope + + @retryable(retries=3) + async def _fetch_token(self): + """Fetch API token for usage with Graph API + + Returns: + (str, int) - a tuple containing access token as a string and number of seconds it will be valid for as an integer + """ + + secrets_concat = self._certificate + "\n" + self._private_key + + credentials = CertificateCredential( + self._tenant_id, self._client_id, certificate_data=secrets_concat.encode() + ) + + token = await credentials.get_token(self._scope) + + return token.token, datetime.utcfromtimestamp(token.expires_on) def retryable_aiohttp_call(retries): @@ -522,7 +570,15 @@ def _compute_retry_after(self, retry_after, retry_count, backoff): class SharepointOnlineClient: - def __init__(self, tenant_id, tenant_name, client_id, client_secret): + def __init__( + self, + tenant_id, + tenant_name, + client_id, + client_secret=None, + certificate=None, + private_key=None, + ): # Sharepoint / Graph API has quite strict throttling policies # If connector is overzealous, it can be banned for not respecting throttling policies # However if connector has a low setting for the tcp_connector limit, then it'll just be slow. @@ -544,12 +600,35 @@ def __init__(self, tenant_id, tenant_name, client_id, client_secret): "https://(.*).sharepoint.com" ) # Used later for url validation - self.graph_api_token = GraphAPIToken( - self._http_session, tenant_id, tenant_name, client_id, client_secret - ) - self.rest_api_token = SharepointRestAPIToken( - self._http_session, tenant_id, tenant_name, client_id, client_secret - ) + if client_secret and not certificate and not private_key: + self.graph_api_token = GraphAPIToken( + self._http_session, tenant_id, tenant_name, client_id, client_secret + ) + self.rest_api_token = SharepointRestAPIToken( + self._http_session, tenant_id, tenant_name, client_id, client_secret + ) + elif certificate and private_key: + self.graph_api_token = EntraAPIToken( + self._http_session, + tenant_id, + tenant_name, + client_id, + certificate, + private_key, + "https://graph.microsoft.com/.default", + ) + self.rest_api_token = EntraAPIToken( + self._http_session, + tenant_id, + tenant_name, + client_id, + certificate, + private_key, + f"https://{self._tenant_name}.sharepoint.com/.default", + ) + else: + msg = "Unexpected authentication: either a client_secret or certificate+private_key should be provided" + raise Exception(msg) self._logger = logger @@ -1157,11 +1236,27 @@ def client(self): tenant_id = self.configuration["tenant_id"] tenant_name = self.configuration["tenant_name"] client_id = self.configuration["client_id"] + auth_method = self.configuration["auth_method"] client_secret = self.configuration["secret_value"] + certificate = self.configuration["certificate"] + private_key = self.configuration["private_key"] - self._client = SharepointOnlineClient( - tenant_id, tenant_name, client_id, client_secret - ) + if auth_method == "secret": + self._client = SharepointOnlineClient( + tenant_id, tenant_name, client_id, client_secret=client_secret + ) + elif auth_method == "certificate": + self._client = SharepointOnlineClient( + tenant_id, + tenant_name, + client_id, + client_secret, + certificate=certificate, + private_key=private_key, + ) + else: + msg = f"Unexpected auth method: {auth_method}" + raise Exception(msg) return self._client @@ -1183,17 +1278,45 @@ def get_default_configuration(cls): "order": 3, "type": "str", }, + "auth_method": { + "label": "Authentication Method", + "order": 4, + "type": "str", + "display": "dropdown", + "options": [ + {"label": "Client Secret", "value": "secret"}, + {"label": "Certificate", "value": "certificate"}, + ], + "value": "secret", + }, "secret_value": { "label": "Secret value", - "order": 4, + "order": 5, + "sensitive": True, + "type": "str", + "depends_on": [{"field": "auth_method", "value": "secret"}], + }, + "certificate": { + "label": "Content of certificate file", + "display": "textarea", + "sensitive": True, + "order": 6, + "type": "str", + "depends_on": [{"field": "auth_method", "value": "certificate"}], + }, + "private_key": { + "label": "Content of private key file", + "display": "textarea", "sensitive": True, + "order": 7, "type": "str", + "depends_on": [{"field": "auth_method", "value": "certificate"}], }, "site_collections": { "display": "textarea", "label": "Comma-separated list of sites", "tooltip": "A comma-separated list of sites to ingest data from. If enumerating all sites, use * to include all available sites, or specify a list of site names. Otherwise, specify a list of site paths.", - "order": 5, + "order": 8, "type": "list", "value": "*", }, @@ -1201,7 +1324,7 @@ def get_default_configuration(cls): "display": "toggle", "label": "Enumerate all sites?", "tooltip": "If enabled, sites will be fetched in bulk, then filtered down to the configured list of sites. This is efficient when syncing many sites. If disabled, each configured site will be fetched with an individual request. This is efficient when syncing fewer sites.", - "order": 6, + "order": 9, "type": "bool", "value": True, }, @@ -1209,7 +1332,7 @@ def get_default_configuration(cls): "display": "toggle", "label": "Fetch sub-sites of configured sites?", "tooltip": "Whether subsites of the configured site(s) should be automatically fetched.", - "order": 7, + "order": 10, "type": "bool", "value": True, "depends_on": [{"field": "enumerate_all_sites", "value": False}], @@ -1217,7 +1340,7 @@ def get_default_configuration(cls): "use_text_extraction_service": { "display": "toggle", "label": "Use text extraction service", - "order": 8, + "order": 11, "tooltip": "Requires a separate deployment of the Elastic Text Extraction Service. Requires that pipeline settings disable text extraction.", "type": "bool", "ui_restrictions": ["advanced"], @@ -1226,7 +1349,7 @@ def get_default_configuration(cls): "use_document_level_security": { "display": "toggle", "label": "Enable document level security", - "order": 9, + "order": 12, "tooltip": "Document level security ensures identities and permissions set in Sharepoint Online are maintained in Elasticsearch. This enables you to restrict and personalize read-access users and groups have to documents in this index. Access control syncs ensure this metadata is kept up to date in your Elasticsearch documents.", "type": "bool", "value": False, @@ -1235,7 +1358,7 @@ def get_default_configuration(cls): "depends_on": [{"field": "use_document_level_security", "value": True}], "display": "toggle", "label": "Fetch drive item permissions", - "order": 10, + "order": 13, "tooltip": "Enable this option to fetch drive item specific permissions. This setting can increase sync time.", "type": "bool", "value": True, @@ -1244,7 +1367,7 @@ def get_default_configuration(cls): "depends_on": [{"field": "use_document_level_security", "value": True}], "display": "toggle", "label": "Fetch unique page permissions", - "order": 11, + "order": 14, "tooltip": "Enable this option to fetch unique page permissions. This setting can increase sync time. If this setting is disabled a page will inherit permissions from its parent site.", "type": "bool", "value": True, @@ -1253,7 +1376,7 @@ def get_default_configuration(cls): "depends_on": [{"field": "use_document_level_security", "value": True}], "display": "toggle", "label": "Fetch unique list permissions", - "order": 12, + "order": 15, "tooltip": "Enable this option to fetch unique list permissions. This setting can increase sync time. If this setting is disabled a list will inherit permissions from its parent site.", "type": "bool", "value": True, @@ -1262,7 +1385,7 @@ def get_default_configuration(cls): "depends_on": [{"field": "use_document_level_security", "value": True}], "display": "toggle", "label": "Fetch unique list item permissions", - "order": 13, + "order": 16, "tooltip": "Enable this option to fetch unique list item permissions. This setting can increase sync time. If this setting is disabled a list item will inherit permissions from its parent site.", "type": "bool", "value": True, diff --git a/requirements/framework.txt b/requirements/framework.txt index f5f967ecc..2fec55f27 100644 --- a/requirements/framework.txt +++ b/requirements/framework.txt @@ -44,3 +44,4 @@ notion-client==2.2.1 certifi==2024.7.4 aioboto3==12.4.0 pyasn1<0.6.1 +azure-identity==1.19.0 diff --git a/tests/sources/fixtures/sharepoint_online/connector.json b/tests/sources/fixtures/sharepoint_online/connector.json index 6679c09bd..8342f06b8 100644 --- a/tests/sources/fixtures/sharepoint_online/connector.json +++ b/tests/sources/fixtures/sharepoint_online/connector.json @@ -30,36 +30,100 @@ "order": 2, "ui_restrictions": [] }, - "secret_value": { + "client_id": { "depends_on": [], "display": "text", "tooltip": null, "default_value": null, - "label": "Secret Value", + "label": "Client Id", "sensitive": true, "type": "str", "required": true, "options": [], "validations": [], - "value": "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ", - "order": 4, + "value": "00000000-0000-0000-0000-000000000000", + "order": 3, "ui_restrictions": [] }, - "client_id": { + "auth_method": { + "default_value": null, + "depends_on": [], + "display": "dropdown", + "label": "Authentication Method", + "options": [ + { + "label": "Client Secret", + "value": "secret" + }, + { + "label": "Certificate", + "value": "certificate" + } + ], + "order": 4, + "required": true, + "sensitive": false, + "tooltip": null, + "type": "str", + "ui_restrictions": [], + "validations": [], + "value": "secret" + }, + "secret_value": { "depends_on": [], "display": "text", "tooltip": null, "default_value": null, - "label": "Client Id", + "label": "Secret Value", "sensitive": true, "type": "str", "required": true, "options": [], "validations": [], - "value": "00000000-0000-0000-0000-000000000000", - "order": 3, + "value": "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ", + "order": 5, "ui_restrictions": [] }, + "certificate": { + "default_value": null, + "depends_on": [ + { + "field": "auth_method", + "value": "certificate" + } + ], + "display": "textarea", + "label": "Content of certificate file", + "options": [], + "order": 5, + "required": true, + "sensitive": true, + "tooltip": null, + "type": "str", + "ui_restrictions": [], + "validations": [], + "value": "" + }, + "private_key": { + "default_value": null, + "depends_on": [ + { + "field": "auth_method", + "value": "certificate" + } + ], + "display": "textarea", + "label": "Content of private key file", + "options": [], + "order": 6, + "required": true, + "sensitive": true, + "tooltip": null, + "type": "str", + "ui_restrictions": [], + "validations": [], + "value": "" + }, "site_collections": { "depends_on": [], "display": "textarea", @@ -72,7 +136,7 @@ "options": [], "validations": [], "value": "*", - "order": 5, + "order": 7, "ui_restrictions": [] }, "enumerate_all_sites": { @@ -87,7 +151,7 @@ "options": [], "validations": [], "value": true, - "order": 6, + "order": 8, "ui_restrictions": [] }, "use_text_extraction_service": { @@ -102,7 +166,7 @@ "options": [], "validations": [], "value": false, - "order": 7, + "order": 9, "ui_restrictions": [] }, "use_document_level_security": { @@ -117,7 +181,7 @@ "options": [], "validations": [], "value": false, - "order": 8, + "order": 10, "ui_restrictions": [] }, "fetch_drive_item_permissions": { @@ -137,7 +201,7 @@ "options": [], "validations": [], "value": false, - "order": 9, + "order": 11, "ui_restrictions": [] }, "fetch_unique_page_permissions": { @@ -157,7 +221,7 @@ "options": [], "validations": [], "value": false, - "order": 10, + "order": 12, "ui_restrictions": [] }, "fetch_unique_list_permissions": { @@ -177,7 +241,7 @@ "options": [], "validations": [], "value": false, - "order": 11, + "order": 13, "ui_restrictions": [] }, "fetch_unique_list_item_permissions": { @@ -197,8 +261,8 @@ "options": [], "validations": [], "value": true, - "order": 12, + "order": 14, "ui_restrictions": [] } } -} \ No newline at end of file +} diff --git a/tests/sources/test_sharepoint_online.py b/tests/sources/test_sharepoint_online.py index 2a952eec8..7b8045e0b 100644 --- a/tests/sources/test_sharepoint_online.py +++ b/tests/sources/test_sharepoint_online.py @@ -10,7 +10,7 @@ from datetime import datetime, timedelta, timezone from functools import partial from io import BytesIO -from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patch +from unittest.mock import ANY, AsyncMock, MagicMock, Mock, PropertyMock, patch import aiohttp import pytest @@ -28,6 +28,7 @@ WILDCARD, BadRequestError, DriveItemsPage, + EntraAPIToken, GraphAPIToken, InternalServerError, InvalidSharepointTenant, @@ -229,7 +230,11 @@ @asynccontextmanager async def create_spo_source( + tenant_id="1", tenant_name="test", + client_id="2", + secret_value="3", + auth_method="secret", site_collections=WILDCARD, use_document_level_security=False, use_text_extraction_service=False, @@ -239,9 +244,10 @@ async def create_spo_source( ): async with create_source( SharepointOnlineDataSource, - tenant_id="1", - client_id="2", - secret_value="3", + auth_method=auth_method, + tenant_id=tenant_id, + client_id=client_id, + secret_value=secret_value, tenant_name=tenant_name, site_collections=site_collections, use_document_level_security=use_document_level_security, @@ -280,17 +286,17 @@ def access_control_is_equal(actual, expected): class TestMicrosoftSecurityToken: class StubMicrosoftSecurityToken(MicrosoftSecurityToken): - def __init__(self, bearer, expires_in): - super().__init__(None, None, None, None, None) + def __init__(self, bearer, expires_at): + super().__init__(None, None, None, None) self.bearer = bearer - self.expires_in = expires_in + self.expires_at = expires_at async def _fetch_token(self): - return (self.bearer, self.expires_in) + return (self.bearer, self.expires_at) class StubMicrosoftSecurityTokenWrongConfig(MicrosoftSecurityToken): def __init__(self, error_code, message=None): - super().__init__(None, None, None, None, None) + super().__init__(None, None, None, None) self.error_code = error_code self.message = message @@ -304,7 +310,7 @@ async def _fetch_token(self): @pytest.mark.asyncio async def test_fetch_token_raises_not_implemented_error(self): with pytest.raises(NotImplementedError) as e: - mst = MicrosoftSecurityToken(None, None, None, None, None) + mst = MicrosoftSecurityToken(None, None, None, None) await mst._fetch_token() @@ -324,13 +330,14 @@ async def test_get_returns_results_from_fetch_token(self): assert actual == bearer @pytest.mark.asyncio + @freeze_time() async def test_get_returns_cached_value_when_token_did_not_expire(self): original_bearer = "something" updated_bearer = "another" - expires_in = 1 + expires_at = datetime.utcnow() + timedelta(seconds=1) token = TestMicrosoftSecurityToken.StubMicrosoftSecurityToken( - original_bearer, expires_in + original_bearer, expires_at ) first_bearer = await token.get() @@ -345,16 +352,16 @@ async def test_get_returns_cached_value_when_token_did_not_expire(self): async def test_get_returns_new_value_when_token_expired(self): original_bearer = "something" updated_bearer = "another" - expires_in = 0.01 + expires_at = datetime.utcnow() + timedelta(seconds=-1) token = TestMicrosoftSecurityToken.StubMicrosoftSecurityToken( - original_bearer, expires_in + original_bearer, expires_at ) first_bearer = await token.get() token.bearer = updated_bearer - await asyncio.sleep(expires_in + 0.01) + await asyncio.sleep(0.01) second_bearer = await token.get() @@ -407,8 +414,10 @@ async def token(self): await session.close() @pytest.mark.asyncio + @freeze_time() async def test_fetch_token(self, token, mock_responses): bearer = "hello" + now = datetime.utcnow() expires_in = 15 mock_responses.post( @@ -419,13 +428,14 @@ async def test_fetch_token(self, token, mock_responses): actual_token, actual_expires_in = await token._fetch_token() assert actual_token == bearer - assert actual_expires_in == expires_in + assert actual_expires_in == now + timedelta(seconds=expires_in) @pytest.mark.asyncio + @freeze_time() async def test_fetch_token_retries(self, token, mock_responses, patch_sleep): bearer = "hello" expires_in = 15 - + now = datetime.utcnow() first_request_error = ClientResponseError(None, None) first_request_error.status = 500 first_request_error.message = "Something went wrong" @@ -440,7 +450,7 @@ async def test_fetch_token_retries(self, token, mock_responses, patch_sleep): actual_token, actual_expires_in = await token._fetch_token() assert actual_token == bearer - assert actual_expires_in == expires_in + assert actual_expires_in == now + timedelta(seconds=expires_in) class TestSharepointRestAPIToken: @@ -453,9 +463,11 @@ async def token(self): await session.close() @pytest.mark.asyncio + @freeze_time() async def test_fetch_token(self, token, mock_responses): bearer = "hello" expires_in = 15 + now = datetime.utcnow() mock_responses.post( re.compile(".*"), @@ -465,15 +477,17 @@ async def test_fetch_token(self, token, mock_responses): actual_token, actual_expires_in = await token._fetch_token() assert actual_token == bearer - assert actual_expires_in == expires_in + assert actual_expires_in == now + timedelta(seconds=expires_in) # This test is a duplicate of test for TestGraphAPIToken. # When we introduce reusable retryable function instead of a wrapper # Then this test can be removed @pytest.mark.asyncio + @freeze_time() async def test_fetch_token_retries(self, token, mock_responses, patch_sleep): bearer = "hello" expires_in = 15 + now = datetime.utcnow() first_request_error = ClientResponseError(None, None) first_request_error.status = 500 @@ -489,7 +503,73 @@ async def test_fetch_token_retries(self, token, mock_responses, patch_sleep): actual_token, actual_expires_in = await token._fetch_token() assert actual_token == bearer - assert actual_expires_in == expires_in + assert actual_expires_in == now + timedelta(seconds=expires_in) + + +class TestEntraAPIToken: + @pytest_asyncio.fixture + async def token(self): + session = aiohttp.ClientSession() + + yield EntraAPIToken( + session, + "abc123", + "tenant_name", + "client_id", + "certificate", + "private_key", + "scope", + ) + + await session.close() + + @pytest.mark.asyncio + async def test_fetch_token(self, token, mock_responses): + bearer = "hello" + expires_at = datetime.utcnow().timestamp() + 30 + + entra_token = MagicMock() + type(entra_token).token = PropertyMock(return_value=bearer) + type(entra_token).expires_on = PropertyMock(return_value=expires_at) + + certificate_credential_mock = AsyncMock() + certificate_credential_mock.get_token = AsyncMock(return_value=entra_token) + + with patch( + "connectors.sources.sharepoint_online.CertificateCredential", + return_value=certificate_credential_mock, + ): + actual_token, actual_expires_at = await token._fetch_token() + + assert actual_token == bearer + assert actual_expires_at == datetime.utcfromtimestamp(expires_at) + + @pytest.mark.asyncio + async def test_fetch_token_retries(self, token, mock_responses, patch_sleep): + bearer = "hello" + expires_at = datetime.utcnow().timestamp() + 30 + + entra_token = MagicMock() + type(entra_token).token = PropertyMock(return_value=bearer) + type(entra_token).expires_on = PropertyMock(return_value=expires_at) + + def effect(*args, **kwargs): + # Two exceptions, then return token + yield Exception + yield Exception + yield entra_token + + certificate_credential_mock = AsyncMock() + certificate_credential_mock.get_token = AsyncMock(side_effect=effect()) + + with patch( + "connectors.sources.sharepoint_online.CertificateCredential", + return_value=certificate_credential_mock, + ): + actual_token, actual_expires_at = await token._fetch_token() + + assert actual_token == bearer + assert actual_expires_at == datetime.utcfromtimestamp(expires_at) class TestMicrosoftAPISession: @@ -2924,8 +3004,16 @@ def test_get_default_configuration(self): assert config is not None @pytest.mark.asyncio - async def test_validate_config_empty_config(self, patch_sharepoint_client): - async with create_source(SharepointOnlineDataSource) as source: + async def test_validate_config_empty_config_with_secret_auth( + self, patch_sharepoint_client + ): + async with create_spo_source( + tenant_id="", + tenant_name="", + client_id="", + secret_value="", + auth_method="secret", + ) as source: with pytest.raises(ConfigurableFieldValueError) as e: await source.validate_config() @@ -2934,6 +3022,22 @@ async def test_validate_config_empty_config(self, patch_sharepoint_client): assert e.match("Client ID") assert e.match("Secret value") + @pytest.mark.asyncio + async def test_validate_config_empty_config_with_cert_auth( + self, patch_sharepoint_client + ): + async with create_spo_source( + tenant_id="", tenant_name="", client_id="", auth_method="certificate" + ) as source: + with pytest.raises(ConfigurableFieldValueError) as e: + await source.validate_config() + + assert e.match("Tenant ID") + assert e.match("Tenant name") + assert e.match("Client ID") + assert e.match("Content of certificate file") + assert e.match("Content of private key file") + @pytest.mark.asyncio async def test_validate_config(self, patch_sharepoint_client): async with create_spo_source() as source: