forked from elastic/connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sharepoint_online.py
2571 lines (2109 loc) · 101 KB
/
sharepoint_online.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
import asyncio
import os
import re
from collections.abc import Iterable, Sized
from contextlib import asynccontextmanager
from datetime import datetime, timedelta
from functools import partial, wraps
import aiofiles
import aiohttp
import fastjsonschema
from aiofiles.os import remove
from aiofiles.tempfile import NamedTemporaryFile
from aiohttp.client_exceptions import ClientPayloadError, ClientResponseError
from aiohttp.client_reqrep import RequestInfo
from fastjsonschema import JsonSchemaValueException
from connectors.access_control import (
ACCESS_CONTROL,
es_access_control_query,
prefix_identity,
)
from connectors.es.sink import OP_DELETE, OP_INDEX
from connectors.filtering.validation import (
AdvancedRulesValidator,
SyncRuleValidationResult,
)
from connectors.logger import logger
from connectors.source import CURSOR_SYNC_TIMESTAMP, BaseDataSource
from connectors.utils import (
TIKA_SUPPORTED_FILETYPES,
CacheWithTimeout,
CancellableSleeps,
convert_to_b64,
html_to_text,
iso_utc,
iso_zulu,
iterable_batches_generator,
nested_get_from_dict,
retryable,
url_encode,
)
SPO_API_MAX_BATCH_SIZE = 20
TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
if "OVERRIDE_URL" in os.environ:
logger.warning("x" * 50)
logger.warning(
f"SHAREPOINT ONLINE CONNECTOR CALLS ARE REDIRECTED TO {os.environ['OVERRIDE_URL']}"
)
logger.warning("IT'S SUPPOSED TO BE USED ONLY FOR TESTING")
logger.warning("x" * 50)
override_url = os.environ["OVERRIDE_URL"]
GRAPH_API_URL = override_url
GRAPH_API_AUTH_URL = override_url
REST_API_AUTH_URL = override_url
else:
GRAPH_API_URL = "https://graph.microsoft.com/v1.0"
GRAPH_API_AUTH_URL = "https://login.microsoftonline.com"
REST_API_AUTH_URL = "https://accounts.accesscontrol.windows.net"
DEFAULT_RETRY_COUNT = 5
DEFAULT_RETRY_SECONDS = 30
DEFAULT_PARALLEL_CONNECTION_COUNT = 10
DEFAULT_BACKOFF_MULTIPLIER = 5
FILE_WRITE_CHUNK_SIZE = 1024 * 64 # 64KB default SSD page size
MAX_DOCUMENT_SIZE = 10485760
WILDCARD = "*"
DRIVE_ITEMS_FIELDS = "id,content.downloadUrl,lastModifiedDateTime,lastModifiedBy,root,deleted,file,folder,package,name,webUrl,createdBy,createdDateTime,size,parentReference"
CURSOR_SITE_DRIVE_KEY = "site_drives"
# Microsoft Graph API Delta constants
# https://learn.microsoft.com/en-us/graph/delta-query-overview
DELTA_NEXT_LINK_KEY = "@odata.nextLink"
DELTA_LINK_KEY = "@odata.deltaLink"
# See https://github.com/pnp/pnpcore/blob/dev/src/sdk/PnP.Core/Model/SharePoint/Core/Public/Enums/PermissionKind.cs
# See also: https://learn.microsoft.com/en-us/previous-versions/office/sharepoint-csom/ee536458(v=office.15)
VIEW_ITEM_MASK = 0x1 # View items in lists, documents in document libraries, and Web discussion comments.
VIEW_PAGE_MASK = 0x20000 # View pages in a Site.
# See https://github.com/pnp/pnpcore/blob/dev/src/sdk/PnP.Core/Model/SharePoint/Core/Public/Enums/RoleType.cs
# See also: https://learn.microsoft.com/en-us/dotnet/api/microsoft.sharepoint.client.roletype?view=sharepoint-csom
READER = 2
CONTRIBUTOR = 3
WEB_DESIGNER = 4
ADMINISTRATOR = 5
EDITOR = 6
REVIEWER = 7
SYSTEM = 0xFF
# Note the exclusion of NONE(0), GUEST(1), RESTRICTED_READER(8), and RESTRICTED_GUEST(9)
VIEW_ROLE_TYPES = [
READER,
CONTRIBUTOR,
WEB_DESIGNER,
ADMINISTRATOR,
EDITOR,
REVIEWER,
SYSTEM,
]
# $expand param has a max of 20: see: https://developer.microsoft.com/en-us/graph/known-issues/?search=expand
SPO_MAX_EXPAND_SIZE = 20
class NotFound(Exception):
"""Internal exception class to handle 404s from the API that has a meaning, that collection
for specific object is empty.
For example List Items API from Sharepoint REST API returns 404 if list has no items.
It's not an exception for us, we just want to return [], and this exception class facilitates it.
"""
pass
class BadRequestError(Exception):
"""Internal exception class to handle 400's from the API.
Similar to the NotFound exception, this allows us to catch edge-case responses that should
be translated as empty resutls, and let us return []."""
pass
class InternalServerError(Exception):
"""Exception class to indicate that something went wrong on the server side."""
pass
class ThrottledError(Exception):
"""Internal exception class to indicate that request was throttled by the API"""
pass
class InvalidSharepointTenant(Exception):
"""Exception class to notify that tenant name is invalid or does not match tenant id provided"""
pass
class TokenFetchFailed(Exception):
"""Exception class to notify that connector was unable to fetch authentication token from either
Sharepoint REST API or Graph API.
Error message will indicate human-readable reason.
"""
pass
class PermissionsMissing(Exception):
"""Exception class to notify that specific Application Permission is missing for the credentials used.
See: https://learn.microsoft.com/en-us/graph/permissions-reference
"""
pass
class SyncCursorEmpty(Exception):
"""Exception class to notify that incremental sync can't run because sync_cursor is empty.
See: https://learn.microsoft.com/en-us/graph/delta-query-overview
"""
pass
class MicrosoftSecurityToken:
"""Abstract token for connecting to one of Microsoft Azure services.
This class is an abstract base class for getting auth token.
It takes care of caching the token and asking for new token once the
token expires.
Classes that inherit from this class need to implement `async def _fetch_token(self)` method
that needs to return a tuple: access_token<str> and expires_in<int>.
To read more about tenants and authentication, see:
- https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-create-new-tenant
- 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):
"""Initializer.
Args:
http_session (aiohttp.ClientSession): HTTP Client Session
tenant_id (str): Azure AD Tenant Id
tenant_name (str): Azure AD Tenant Name
client_id (str): Azure App Client Id
client_secret (str): Azure App Client Secret Value"""
self._http_session = http_session
self._tenant_id = tenant_id
self._tenant_name = tenant_name
self._client_id = client_id
self._client_secret = client_secret
self._token_cache = CacheWithTimeout()
async def get(self):
"""Get bearer token for provided credentials.
If token has been retrieved, it'll be taken from the cache.
Otherwise, call to `_fetch_token` is made to fetch the token
from 3rd-party service.
Returns:
str: bearer token for one of Microsoft services"""
cached_value = self._token_cache.get_value()
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()
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:
match e.status:
case 400:
msg = "Failed to authorize to Sharepoint REST API. Please verify, that provided Tenant Id, Tenant Name and Client ID are valid."
raise TokenFetchFailed(msg) from e
case 401:
msg = "Failed to authorize to Sharepoint REST API. Please verify, that provided Secret Value is valid."
raise TokenFetchFailed(msg) from e
case _:
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))
return access_token
async def _fetch_token(self):
"""Fetch token from Microsoft service.
This method needs to be implemented in the class that inherits MicrosoftSecurityToken.
Returns:
(str, int) - a tuple containing access token as a string and number of seconds it will be valid for as an integer
"""
raise NotImplementedError
class GraphAPIToken(MicrosoftSecurityToken):
"""Token to connect to Microsoft Graph API endpoints."""
@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
"""
url = f"{GRAPH_API_AUTH_URL}/{self._tenant_id}/oauth2/v2.0/token"
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"
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
class SharepointRestAPIToken(MicrosoftSecurityToken):
"""Token to connect to Sharepoint REST API endpoints."""
@retryable(retries=DEFAULT_RETRY_COUNT)
async def _fetch_token(self):
"""Fetch API token for usage with Sharepoint REST API
Returns:
(str, int) - a tuple containing access token as a string and number of seconds it will be valid for as an integer
"""
url = f"{REST_API_AUTH_URL}/{self._tenant_id}/tokens/OAuth/2"
# GUID in resource is always a constant used to create access token
data = {
"grant_type": "client_credentials",
"resource": f"00000003-0000-0ff1-ce00-000000000000/{self._tenant_name}.sharepoint.com@{self._tenant_id}",
"client_id": f"{self._client_id}@{self._tenant_id}",
"client_secret": self._client_secret,
}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
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
def retryable_aiohttp_call(retries):
# TODO: improve utils.retryable to allow custom logic
# that can help choose what to retry
def wrapper(func):
@wraps(func)
async def wrapped(*args, **kwargs):
retry = 1
while retry <= retries:
try:
async for item in func(*args, **kwargs, retry_count=retry):
yield item
break
except (NotFound, BadRequestError):
raise
except Exception:
if retry >= retries:
raise
retry += 1
return wrapped
return wrapper
class MicrosoftAPISession:
def __init__(self, http_session, api_token, scroll_field, logger_):
self._http_session = http_session
self._api_token = api_token
# Graph API and Sharepoint API scroll over slightly different fields:
# - odata.nextPage for Sharepoint REST API uses
# - @odata.nextPage for Graph API uses - notice the @ glyph
# Therefore for flexibility I made it a field passed in the initializer,
# but this abstraction can be better.
self._scroll_field = scroll_field
self._sleeps = CancellableSleeps()
self._logger = logger_
def set_logger(self, logger_):
self._logger = logger_
def close(self):
self._sleeps.cancel()
async def fetch(self, url):
return await self._get_json(url)
async def post(self, url, payload):
self._logger.debug(f"Post to url: '{url}' with body: {payload}")
async with self._post(url, payload) as resp:
return await resp.json()
async def pipe(self, url, stream):
async with self._get(url) as resp:
async for data in resp.content.iter_chunked(FILE_WRITE_CHUNK_SIZE):
await stream.write(data)
async def scroll(self, url):
scroll_url = url
while True:
graph_data = await self._get_json(scroll_url)
# We're yielding the whole page here, not one item
yield graph_data["value"]
if self._scroll_field in graph_data:
scroll_url = graph_data[self._scroll_field]
else:
break
async def scroll_delta_url(self, url):
scroll_url = url
while True:
graph_data = await self._get_json(scroll_url)
yield graph_data
if DELTA_NEXT_LINK_KEY in graph_data:
scroll_url = graph_data[DELTA_NEXT_LINK_KEY]
else:
break
async def _get_json(self, absolute_url):
self._logger.debug(f"Fetching url: {absolute_url}")
async with self._get(absolute_url) as resp:
return await resp.json()
@asynccontextmanager
@retryable_aiohttp_call(retries=DEFAULT_RETRY_COUNT)
async def _post(self, absolute_url, payload=None, retry_count=0):
try:
token = await self._api_token.get()
headers = {"authorization": f"Bearer {token}"}
self._logger.debug(f"Posting to Sharepoint Endpoint: {absolute_url}.")
async with self._http_session.post(
absolute_url, headers=headers, json=payload
) as resp:
if absolute_url.endswith("/$batch"): # response code of $batch lies
await self._check_batch_items_for_errors(absolute_url, resp)
yield resp
except aiohttp.client_exceptions.ClientOSError:
self._logger.warning(
"The Microsoft Graph API dropped the connection. It might indicate that the connector is making too many requests. Decrease concurrency settings, otherwise the Graph API may block this app."
)
raise
except ClientResponseError as e:
await self._handle_client_response_error(absolute_url, e, retry_count)
except ClientPayloadError as e:
await self._handle_client_payload_error(e, retry_count)
async def _check_batch_items_for_errors(self, url, batch_resp):
body = await batch_resp.json()
responses = body.get("responses", [])
for response in responses:
status = response.get("status", 200)
if status != 200:
self._logger.warning(f"Batch request item failed with: {response}")
headers = response.get("headers", {})
req_info = RequestInfo(url=url, method="POST", headers=headers)
raise ClientResponseError(
request_info=req_info,
headers=headers,
status=status,
message=nested_get_from_dict(
response, ["body", "error", "message"]
),
history=(batch_resp),
)
@asynccontextmanager
@retryable_aiohttp_call(retries=DEFAULT_RETRY_COUNT)
async def _get(self, absolute_url, retry_count=0):
try:
token = await self._api_token.get()
headers = {"authorization": f"Bearer {token}"}
self._logger.debug(f"Calling Sharepoint Endpoint: {absolute_url}")
async with self._http_session.get(
absolute_url,
headers=headers,
) as resp:
yield resp
except aiohttp.client_exceptions.ClientOSError:
self._logger.warning(
"Graph API dropped the connection. It might indicate, that connector makes too many requests - decrease concurrency settings, otherwise Graph API can block this app."
)
raise
except ClientResponseError as e:
await self._handle_client_response_error(absolute_url, e, retry_count)
except ClientPayloadError as e:
await self._handle_client_payload_error(e, retry_count)
async def _handle_client_payload_error(self, e, retry_count):
await self._sleeps.sleep(
self._compute_retry_after(
DEFAULT_RETRY_SECONDS, retry_count, DEFAULT_BACKOFF_MULTIPLIER
)
)
raise e
async def _handle_client_response_error(self, absolute_url, e, retry_count):
if e.status == 429 or e.status == 503:
response_headers = e.headers or {}
if "Retry-After" in response_headers:
retry_after = int(response_headers["Retry-After"])
else:
self._logger.warning(
f"Response Code from Sharepoint Online is {e.status} but Retry-After header is not found, using default retry time: {DEFAULT_RETRY_SECONDS} seconds"
)
retry_after = DEFAULT_RETRY_SECONDS
retry_seconds = self._compute_retry_after(
retry_after, retry_count, DEFAULT_BACKOFF_MULTIPLIER
)
self._logger.warning(
f"Rate Limited by Sharepoint: a new attempt will be performed in {retry_seconds} seconds (retry-after header: {retry_after}, retry_count: {retry_count}, backoff: {DEFAULT_BACKOFF_MULTIPLIER})"
)
await self._sleeps.sleep(retry_seconds)
raise ThrottledError from e
elif (
e.status == 403 or e.status == 401
): # Might work weird, but Graph returns 403 and REST returns 401
msg = f"Received Unauthorized response for {absolute_url}.\nVerify that the correct Graph API and Sharepoint permissions are granted to the app and admin consent is given. If the permissions and consent are correct, wait for several minutes and try again."
raise PermissionsMissing(msg) from e
elif e.status == 404:
raise NotFound from e # We wanna catch it in the code that uses this and ignore in some cases
elif e.status == 500:
raise InternalServerError from e
elif e.status == 400:
self._logger.warning(f"Received 400 response from {absolute_url}")
raise BadRequestError from e
else:
raise
def _compute_retry_after(self, retry_after, retry_count, backoff):
# Wait for what Sharepoint API asks after the first failure.
# Apply backoff if API is still not available.
if retry_count <= 1:
return retry_after
else:
return retry_after + retry_count * backoff
class SharepointOnlineClient:
def __init__(self, tenant_id, tenant_name, client_id, client_secret):
# 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.
# Change the value at your own risk
tcp_connector = aiohttp.TCPConnector(limit=DEFAULT_PARALLEL_CONNECTION_COUNT)
self._http_session = aiohttp.ClientSession( # TODO: lazy create this
connector=tcp_connector,
headers={
"accept": "application/json",
"content-type": "application/json",
},
timeout=aiohttp.ClientTimeout(total=None),
raise_for_status=True,
)
self._tenant_id = tenant_id
self._tenant_name = tenant_name
self._tenant_name_pattern = re.compile(
"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
)
self._logger = logger
self._graph_api_client = MicrosoftAPISession(
self._http_session, self.graph_api_token, "@odata.nextLink", self._logger
)
self._rest_api_client = MicrosoftAPISession(
self._http_session, self.rest_api_token, "odata.nextLink", self._logger
)
def set_logger(self, logger_):
self._logger = logger_
self._graph_api_client.set_logger(self._logger)
self._rest_api_client.set_logger(self._logger)
async def groups(self):
select = ""
async for page in self._graph_api_client.scroll(
f"{GRAPH_API_URL}/groups?$select={select}"
):
for group in page:
yield group
async def group_sites(self, group_id):
select = ""
try:
async for page in self._graph_api_client.scroll(
f"{GRAPH_API_URL}/groups/{group_id}/sites?$select={select}"
):
for group_site in page:
yield group_site
except NotFound:
# We can safely ignore cause Sharepoint can return 404 in case List Item is of specific types that do not support/have attachments
# Yes, makes no sense to me either.
return
async def site_collections(self):
try:
filter_ = url_encode("siteCollection/root ne null")
select = "siteCollection,webUrl"
async for page in self._graph_api_client.scroll(
f"{GRAPH_API_URL}/sites/?$filter={filter_}&$select={select}"
):
for site_collection in page:
yield site_collection
except PermissionsMissing:
self._logger.warning(
"Looks like 'Sites.Read.All' permission is missing to fetch all root-level site collections, hence fetching only tenant root site"
)
yield await self._graph_api_client.fetch(url=f"{GRAPH_API_URL}/sites/root")
async def site_role_assignments(self, site_web_url):
self._validate_sharepoint_rest_url(site_web_url)
expand = "Member/users,RoleDefinitionBindings"
url = f"{site_web_url}/_api/web/roleassignments?$expand={expand}"
try:
async for page in self._rest_api_client.scroll(url):
for role_assignment in page:
yield role_assignment
except NotFound:
self._logger.debug(f"No role assignments found for site: '{site_web_url}'")
return
async def site_admins(self, site_web_url):
self._validate_sharepoint_rest_url(site_web_url)
filter_param = url_encode("isSiteAdmin eq true")
url = f"{site_web_url}/_api/web/SiteUsers?$filter={filter_param}"
try:
async for page in self._rest_api_client.scroll(url):
for member in page:
yield member
except NotFound:
self._logger.debug(f"No site admins found for site: '${site_web_url}'")
return
async def site_groups_users(self, site_web_url, site_group_id):
self._validate_sharepoint_rest_url(site_web_url)
select_ = "Email,Id,UserPrincipalName,LoginName,Title"
url = f"{site_web_url}/_api/web/sitegroups/getbyid({site_group_id})/users?$select={select_}"
try:
async for page in self._rest_api_client.scroll(url):
for site_group_user in page:
yield site_group_user
except NotFound:
self._logger.warning(
f"NotFound error when fetching users for sitegroup '{site_group_id}' at '{site_web_url}'."
)
return
async def active_users_with_groups(self):
expand = "transitiveMemberOf($select=id)"
top = 999 # this is accepted, but does not get taken literally. Response size seems to max out at 100
filter_ = "accountEnabled eq true"
select = "UserName,userPrincipalName,Email,mail,transitiveMemberOf,id,createdDateTime"
url = f"{GRAPH_API_URL}/users?$expand={expand}&$top={top}&$filter={filter_}&$select={select}"
try:
async for page in self._graph_api_client.scroll(url):
for user in page:
yield user
except NotFound:
return
async def group_members(self, group_id):
url = f"{GRAPH_API_URL}/groups/{group_id}/members"
try:
async for page in self._graph_api_client.scroll(url):
for member in page:
yield member
except NotFound:
return
async def group_owners(self, group_id):
select = "id,mail,userPrincipalName"
url = f"{GRAPH_API_URL}/groups/{group_id}/owners?$select={select}"
try:
async for page in self._graph_api_client.scroll(url):
for owner in page:
yield owner
except NotFound:
return
async def site_users(self, site_web_url):
self._validate_sharepoint_rest_url(site_web_url)
url = f"{site_web_url}/_api/web/siteusers"
try:
async for page in self._rest_api_client.scroll(url):
for user in page:
yield user
except NotFound:
return
async def sites(
self,
sharepoint_host,
allowed_root_sites,
enumerate_all_sites=True,
fetch_subsites=False,
):
if allowed_root_sites == [WILDCARD] or enumerate_all_sites:
self._logger.debug(f"Looking up all sites to fetch: {allowed_root_sites}")
async for site in self._all_sites(sharepoint_host, allowed_root_sites):
yield site
else:
self._logger.debug(f"Looking up individual sites: {allowed_root_sites}")
for allowed_site in allowed_root_sites:
try:
if fetch_subsites:
async for site in self._fetch_site_and_subsites_by_path(
sharepoint_host, allowed_site
):
yield site
else:
yield await self._fetch_site(sharepoint_host, allowed_site)
except NotFound:
self._logger.warning(
f"Could not look up site '{allowed_site}' by relative path in parent site: {sharepoint_host}"
)
async def _all_sites(self, sharepoint_host, allowed_root_sites):
select = ""
try:
async for page in self._graph_api_client.scroll(
f"{GRAPH_API_URL}/sites/{sharepoint_host}/sites?search=*&$select={select}"
):
for site in page:
# Filter out site collections that are not needed
if [WILDCARD] != allowed_root_sites and site[
"name"
] not in allowed_root_sites:
continue
yield site
except PermissionsMissing as exception:
if allowed_root_sites == [WILDCARD]:
msg = "The configuration field 'Comma-separated list of sites' with '*' value is only compatible with 'Sites.Read.All' permission."
else:
msg = "To enumerate all sites, the connector requires 'Sites.Read.All' permission"
raise PermissionsMissing(msg) from exception
async def _fetch_site_and_subsites_by_path(self, sharepoint_host, allowed_site):
self._logger.debug(
f"Requesting site '{allowed_site}' and subsites by relative path in host: {sharepoint_host}"
)
site_with_subsites = await self._graph_api_client.fetch(
f"{GRAPH_API_URL}/sites/{sharepoint_host}:/sites/{allowed_site}?expand=sites"
)
async for site in self._recurse_sites(site_with_subsites):
yield site
async def _fetch_site(self, sharepoint_host, allowed_site):
self._logger.debug(
f"Requesting site '{allowed_site}' by relative path in parent site: {sharepoint_host}"
)
return await self._graph_api_client.fetch(
f"{GRAPH_API_URL}/sites/{sharepoint_host}:/sites/{allowed_site}"
)
async def _scroll_subsites_by_parent_id(self, parent_site_id):
self._logger.debug(f"Scrolling subsites of {parent_site_id}")
async for page in self._graph_api_client.scroll(
f"{GRAPH_API_URL}/sites/{parent_site_id}/sites?expand=sites"
):
for site in page:
async for subsite in self._recurse_sites(site): # pyright: ignore
yield subsite
async def _recurse_sites(self, site_with_subsites):
subsites = site_with_subsites.pop("sites", [])
site_with_subsites.pop("[email protected]", None) # remove unnecessary field
yield site_with_subsites
if subsites:
async for site in self._scroll_subsites_by_parent_id(
site_with_subsites["id"]
):
yield site
async def site_drives(self, site_id):
select = "createdDateTime,description,id,lastModifiedDateTime,name,webUrl,driveType,createdBy,lastModifiedBy,owner"
async for page in self._graph_api_client.scroll(
f"{GRAPH_API_URL}/sites/{site_id}/drives?$select={select}"
):
for site_drive in page:
yield site_drive
async def drive_items_delta(self, url):
async for response in self._graph_api_client.scroll_delta_url(url):
delta_link = (
response[DELTA_LINK_KEY] if DELTA_LINK_KEY in response else None
)
if "value" in response and len(response["value"]) > 0:
yield DriveItemsPage(response["value"], delta_link)
async def drive_items(self, drive_id, url=None):
url = (
(
f"{GRAPH_API_URL}/drives/{drive_id}/root/delta?$select={DRIVE_ITEMS_FIELDS}"
)
if not url
else url
)
async for page in self.drive_items_delta(url):
yield page
async def drive_items_permissions_batch(self, drive_id, drive_item_ids):
requests = []
for item_id in drive_item_ids:
permissions_uri = f"/drives/{drive_id}/items/{item_id}/permissions"
requests.append({"id": item_id, "method": "GET", "url": permissions_uri})
if not requests:
self._logger.debug(
"Skipping fetching empty batch of drive item permissions"
)
return
try:
batch_url = f"{GRAPH_API_URL}/$batch"
batch_request = {"requests": requests}
batch_response = await self._graph_api_client.post(batch_url, batch_request)
for response in batch_response.get("responses", []):
yield response
except NotFound:
return
async def download_drive_item(self, drive_id, item_id, async_buffer):
await self._graph_api_client.pipe(
f"{GRAPH_API_URL}/drives/{drive_id}/items/{item_id}/content", async_buffer
)
async def site_lists(self, site_id):
select = "createdDateTime,id,lastModifiedDateTime,name,webUrl,displayName,createdBy,lastModifiedBy"
try:
async for page in self._graph_api_client.scroll(
f"{GRAPH_API_URL}/sites/{site_id}/lists?$select={select}"
):
for site_list in page:
yield site_list
except NotFound:
return
async def site_list_has_unique_role_assignments(self, site_web_url, site_list_name):
self._validate_sharepoint_rest_url(site_web_url)
url = f"{site_web_url}/_api/lists/GetByTitle('{site_list_name}')/HasUniqueRoleAssignments"
try:
response = await self._rest_api_client.fetch(url)
return response.get("value", False)
except NotFound:
return False
async def site_list_role_assignments(self, site_web_url, site_list_name):
self._validate_sharepoint_rest_url(site_web_url)
expand = "Member/users,RoleDefinitionBindings"
url = f"{site_web_url}/_api/lists/GetByTitle('{site_list_name}')/roleassignments?$expand={expand}"
try:
async for page in self._rest_api_client.scroll(url):
for role_assignment in page:
yield role_assignment
except NotFound:
return
async def site_list_item_has_unique_role_assignments(
self, site_web_url, site_list_name, list_item_id
):
self._validate_sharepoint_rest_url(site_web_url)
url = f"{site_web_url}/_api/lists/GetByTitle('{site_list_name}')/items({list_item_id})/HasUniqueRoleAssignments"
try:
response = await self._rest_api_client.fetch(url)
return response.get("value", False)
except NotFound:
return False
except BadRequestError:
self._logger.warning(
f"Received error response when retrieving `{list_item_id}` from list: `{site_list_name}` in site: `{site_web_url}`"
)
return False
async def site_list_item_role_assignments(
self, site_web_url, site_list_name, list_item_id
):
self._validate_sharepoint_rest_url(site_web_url)
expand = "Member/users,RoleDefinitionBindings"
url = f"{site_web_url}/_api/lists/GetByTitle('{site_list_name}')/items({list_item_id})/roleassignments?$expand={expand}"
try:
async for page in self._rest_api_client.scroll(url):
for role_assignment in page:
yield role_assignment
except NotFound:
return
async def site_list_items(self, site_id, list_id):
select = "createdDateTime,id,lastModifiedDateTime,weburl,createdBy,lastModifiedBy,contentType"
expand = "fields($select=Title,Link,Attachments,LinkTitle,LinkFilename,Description,Conversation)"
async for page in self._graph_api_client.scroll(
f"{GRAPH_API_URL}/sites/{site_id}/lists/{list_id}/items?$select={select}&$expand={expand}"
):
for site_list in page:
yield site_list
async def site_list_item_attachments(self, site_web_url, list_title, list_item_id):
self._validate_sharepoint_rest_url(site_web_url)
url = f"{site_web_url}/_api/lists/GetByTitle('{list_title}')/items({list_item_id})?$expand=AttachmentFiles"
try:
list_item = await self._rest_api_client.fetch(url)
for attachment in list_item["AttachmentFiles"]:
yield attachment
except NotFound:
# We can safely ignore cause Sharepoint can return 404 in case List Item is of specific types that do not support/have attachments
# Yes, makes no sense to me either.
return
async def download_attachment(self, attachment_absolute_path, async_buffer):
self._validate_sharepoint_rest_url(attachment_absolute_path)
await self._rest_api_client.pipe(
f"{attachment_absolute_path}/$value", async_buffer
)
async def site_pages(self, site_web_url):
self._validate_sharepoint_rest_url(site_web_url)
# select = "Id,Title,LayoutWebpartsContent,CanvasContent1,Description,Created,AuthorId,Modified,EditorId"
select = "*,EncodedAbsUrl" # ^ is what we want, but site pages don't have consistent schemas, and this causes errors. Better to fetch all and slice
url = f"{site_web_url}/_api/web/lists/GetByTitle('Site%20Pages')/items?$select={select}"
try:
async for page in self._rest_api_client.scroll(url):
for site_page in page:
yield {
"Id": site_page.get("Id"),
"Title": site_page.get("Title"),
"webUrl": site_page.get("EncodedAbsUrl"),
"LayoutWebpartsContent": site_page.get("LayoutWebpartsContent"),
"CanvasContent1": site_page.get("CanvasContent1"),
"WikiField": site_page.get("WikiField"),
"Description": site_page.get("Description"),
"Created": site_page.get("Created"),
"AuthorId": site_page.get("AuthorId"),
"Modified": site_page.get("Modified"),
"EditorId": site_page.get("EditorId"),
"odata.id": site_page.get("odata.id"),
"OData__UIVersionString": site_page.get(
"OData__UIVersionString"
),
}
except NotFound:
# I'm not sure if site can have no pages, but given how weird API is I put this here
# Just to be on a safe side
return
async def site_page_has_unique_role_assignments(self, site_web_url, site_page_id):
self._validate_sharepoint_rest_url(site_web_url)
url = f"{site_web_url}/_api/web/lists/GetByTitle('Site Pages')/items('{site_page_id}')/HasUniqueRoleAssignments"
try:
response = await self._rest_api_client.fetch(url)
return response.get("value", False)
except NotFound:
return False
async def site_page_role_assignments(self, site_web_url, site_page_id):
self._validate_sharepoint_rest_url(site_web_url)
expand = "Member/users,RoleDefinitionBindings"
url = f"{site_web_url}/_api/web/lists/GetByTitle('Site Pages')/items('{site_page_id}')/roleassignments?$expand={expand}"
try:
async for page in self._rest_api_client.scroll(url):
for role_assignment in page:
yield role_assignment
except NotFound:
return
async def users_and_groups_for_role_assignment(self, site_web_url, role_assignment):
self._validate_sharepoint_rest_url(site_web_url)