ms-graph 1.6.2__tar.gz → 1.7.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ms_graph-1.7.0/.gitignore +138 -0
- ms_graph-1.7.0/CHANGELOG.md +99 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/PKG-INFO +13 -18
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/__init__.py +2 -1
- ms_graph-1.7.0/ms_graph/session.py +301 -0
- ms_graph-1.7.0/ms_graph/vault.py +85 -0
- ms_graph-1.7.0/pyproject.toml +64 -0
- ms_graph-1.7.0/tests/test_session.py +153 -0
- ms_graph-1.7.0/tests/test_vault.py +63 -0
- ms_graph-1.7.0/tests/use_client.py +74 -0
- ms_graph-1.6.2/ms_graph/session.py +0 -182
- ms_graph-1.6.2/pyproject.toml +0 -43
- {ms_graph-1.6.2 → ms_graph-1.7.0}/LICENSE +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/README.md +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/client.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/drive_items.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/drives.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/groups.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/logger/logger_setup.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/mail.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/notes.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/personal_contacts.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/search.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/users.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/utils/range.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/workbooks_and_charts/__init__.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/workbooks_and_charts/application.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/workbooks_and_charts/comments.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/workbooks_and_charts/enums.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/workbooks_and_charts/range.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/workbooks_and_charts/table.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/workbooks_and_charts/workbook.py +0 -0
- {ms_graph-1.6.2 → ms_graph-1.7.0}/ms_graph/workbooks_and_charts/worksheets.py +0 -0
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
pip-wheel-metadata/
|
|
24
|
+
share/python-wheels/
|
|
25
|
+
*.egg-info/
|
|
26
|
+
.installed.cfg
|
|
27
|
+
*.egg
|
|
28
|
+
MANIFEST
|
|
29
|
+
|
|
30
|
+
# PyInstaller
|
|
31
|
+
# Usually these files are written by a python script from a template
|
|
32
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
33
|
+
*.manifest
|
|
34
|
+
*.spec
|
|
35
|
+
|
|
36
|
+
# Installer logs
|
|
37
|
+
pip-log.txt
|
|
38
|
+
pip-delete-this-directory.txt
|
|
39
|
+
|
|
40
|
+
# Unit test / coverage reports
|
|
41
|
+
htmlcov/
|
|
42
|
+
.tox/
|
|
43
|
+
.nox/
|
|
44
|
+
.coverage
|
|
45
|
+
.coverage.*
|
|
46
|
+
.cache
|
|
47
|
+
nosetests.xml
|
|
48
|
+
coverage.xml
|
|
49
|
+
*.cover
|
|
50
|
+
*.py,cover
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
target/
|
|
76
|
+
|
|
77
|
+
# Jupyter Notebook
|
|
78
|
+
.ipynb_checkpoints
|
|
79
|
+
|
|
80
|
+
# IPython
|
|
81
|
+
profile_default/
|
|
82
|
+
ipython_config.py
|
|
83
|
+
|
|
84
|
+
# pyenv
|
|
85
|
+
.python-version
|
|
86
|
+
|
|
87
|
+
# pipenv
|
|
88
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
89
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
90
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
91
|
+
# install all needed dependencies.
|
|
92
|
+
#Pipfile.lock
|
|
93
|
+
|
|
94
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
95
|
+
__pypackages__/
|
|
96
|
+
|
|
97
|
+
# Celery stuff
|
|
98
|
+
celerybeat-schedule
|
|
99
|
+
celerybeat.pid
|
|
100
|
+
|
|
101
|
+
# SageMath parsed files
|
|
102
|
+
*.sage.py
|
|
103
|
+
|
|
104
|
+
# Environments
|
|
105
|
+
.env
|
|
106
|
+
.venv
|
|
107
|
+
env/
|
|
108
|
+
venv/
|
|
109
|
+
ENV/
|
|
110
|
+
env.bak/
|
|
111
|
+
venv.bak/
|
|
112
|
+
|
|
113
|
+
# Spyder project settings
|
|
114
|
+
.spyderproject
|
|
115
|
+
.spyproject
|
|
116
|
+
|
|
117
|
+
# Rope project settings
|
|
118
|
+
.ropeproject
|
|
119
|
+
|
|
120
|
+
# mkdocs documentation
|
|
121
|
+
/site
|
|
122
|
+
|
|
123
|
+
# mypy
|
|
124
|
+
.mypy_cache/
|
|
125
|
+
.dmypy.json
|
|
126
|
+
dmypy.json
|
|
127
|
+
|
|
128
|
+
# Pyre type checker
|
|
129
|
+
.pyre/
|
|
130
|
+
|
|
131
|
+
# ignore special files
|
|
132
|
+
*.env
|
|
133
|
+
*.txt
|
|
134
|
+
*.ini
|
|
135
|
+
*.jsonc
|
|
136
|
+
/logs
|
|
137
|
+
*.whl
|
|
138
|
+
/config
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
## v1.7.0 (2026-08-20)
|
|
2
|
+
|
|
3
|
+
### Feat
|
|
4
|
+
|
|
5
|
+
- **vault**: ship the Infisical adapter instead of making callers write it
|
|
6
|
+
|
|
7
|
+
## v1.6.3 (2026-08-19)
|
|
8
|
+
|
|
9
|
+
### Fix
|
|
10
|
+
|
|
11
|
+
- **session**: redact credential headers from error logs
|
|
12
|
+
|
|
13
|
+
## v1.6.2 (2026-05-25)
|
|
14
|
+
|
|
15
|
+
### Fix
|
|
16
|
+
|
|
17
|
+
- install infisical extra for azkees to include infisical_sdk
|
|
18
|
+
|
|
19
|
+
## v1.6.1 (2026-05-25)
|
|
20
|
+
|
|
21
|
+
### Fix
|
|
22
|
+
|
|
23
|
+
- **pyproject.toml**: bump azkees to ^7.0.0 for Infisical support
|
|
24
|
+
|
|
25
|
+
## v1.6.0 (2026-05-25)
|
|
26
|
+
|
|
27
|
+
### Feat
|
|
28
|
+
|
|
29
|
+
- migrate from Azure Key Vault to Infisical via azkees InfisicalClient
|
|
30
|
+
|
|
31
|
+
## v1.5.3 (2026-03-30)
|
|
32
|
+
|
|
33
|
+
### Fix
|
|
34
|
+
|
|
35
|
+
- handle credentials=None with az_client in _state
|
|
36
|
+
|
|
37
|
+
## v1.5.2 (2026-03-29)
|
|
38
|
+
|
|
39
|
+
### Fix
|
|
40
|
+
|
|
41
|
+
- **ci**: trigger publish on tag push instead of release event
|
|
42
|
+
|
|
43
|
+
## v1.5.1 (2026-03-29)
|
|
44
|
+
|
|
45
|
+
### Fix
|
|
46
|
+
|
|
47
|
+
- **ci**: use PERSONAL_ACCESS_TOKEN for release to trigger publish workflow
|
|
48
|
+
|
|
49
|
+
## v1.5.0 (2026-03-29)
|
|
50
|
+
|
|
51
|
+
### Feat
|
|
52
|
+
|
|
53
|
+
- prepare package for PyPI publication
|
|
54
|
+
|
|
55
|
+
## v1.4.2 (2025-04-23)
|
|
56
|
+
|
|
57
|
+
### Fix
|
|
58
|
+
|
|
59
|
+
- **dependencies**: update azkees to v4.1.1 and logpy to v1.4.2
|
|
60
|
+
|
|
61
|
+
## v1.4.1 (2025-04-23)
|
|
62
|
+
|
|
63
|
+
### Fix
|
|
64
|
+
|
|
65
|
+
- **dependencies**: update azkees and logpy to latest tags
|
|
66
|
+
|
|
67
|
+
## v1.4.0 (2025-04-20)
|
|
68
|
+
|
|
69
|
+
### Feat
|
|
70
|
+
|
|
71
|
+
- **poetry.lock,-pyproject.toml**: Upgrading logpy
|
|
72
|
+
|
|
73
|
+
## v1.3.0 (2025-04-20)
|
|
74
|
+
|
|
75
|
+
### Feat
|
|
76
|
+
|
|
77
|
+
- **upgrading-logpy**: upgrading logpy
|
|
78
|
+
|
|
79
|
+
## v1.2.1 (2025-04-06)
|
|
80
|
+
|
|
81
|
+
### Fix
|
|
82
|
+
|
|
83
|
+
- **client.py**: Initialize token_exp with a default value in _token_seconds method
|
|
84
|
+
|
|
85
|
+
## v1.2.0 (2025-04-04)
|
|
86
|
+
|
|
87
|
+
### Feat
|
|
88
|
+
|
|
89
|
+
- **poetry.lock-pyproject.toml**: Update packages
|
|
90
|
+
|
|
91
|
+
## v1.1.0 (2024-07-06)
|
|
92
|
+
|
|
93
|
+
### Feat
|
|
94
|
+
|
|
95
|
+
- **pyproject.toml**: Aligning the project to poetry and commitizen standards
|
|
96
|
+
|
|
97
|
+
## v1.0.1 (2024-06-14)
|
|
98
|
+
|
|
99
|
+
## v1.0.0 (2024-06-14)
|
|
@@ -1,29 +1,25 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: ms-graph
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.7.0
|
|
4
4
|
Summary: A Python Client Application that allows interaction with the Microsoft Graph API.
|
|
5
|
-
|
|
5
|
+
Project-URL: Homepage, https://github.com/bek42/ms_graph
|
|
6
|
+
Project-URL: Repository, https://github.com/bek42/ms_graph
|
|
7
|
+
Project-URL: Changelog, https://github.com/bek42/ms_graph/blob/main/CHANGELOG.md
|
|
8
|
+
Author-email: bek42 <bharani.nitturi@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
6
10
|
License-File: LICENSE
|
|
7
|
-
Keywords:
|
|
8
|
-
Author: bek42
|
|
9
|
-
Author-email: bharani.nitturi@gmail.com
|
|
10
|
-
Requires-Python: >=3.12,<4.0
|
|
11
|
+
Keywords: api,excel,graph,microsoft,onedrive,onenote,outlook,sharepoint
|
|
11
12
|
Classifier: Development Status :: 5 - Production/Stable
|
|
12
13
|
Classifier: Intended Audience :: Developers
|
|
13
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
14
14
|
Classifier: Programming Language :: Python :: 3
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
-
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
-
Classifier: Programming Language :: Python :: 3.14
|
|
18
16
|
Classifier: Topic :: Internet :: WWW/HTTP
|
|
19
17
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
-
Requires-
|
|
21
|
-
Requires-Dist:
|
|
22
|
-
Requires-Dist:
|
|
23
|
-
Requires-Dist:
|
|
24
|
-
|
|
25
|
-
Project-URL: Homepage, https://github.com/bek42/ms_graph
|
|
26
|
-
Project-URL: Repository, https://github.com/bek42/ms_graph
|
|
18
|
+
Requires-Python: <4.0,>=3.12
|
|
19
|
+
Requires-Dist: azkees[infisical]<8.0.0,>=7.0.0
|
|
20
|
+
Requires-Dist: msal<2.0.0,>=1.29.0
|
|
21
|
+
Requires-Dist: pylogpy<2.0.0,>=1.6.2
|
|
22
|
+
Requires-Dist: requests<3.0.0,>=2.32.3
|
|
27
23
|
Description-Content-Type: text/markdown
|
|
28
24
|
|
|
29
25
|
# ms-graph
|
|
@@ -316,4 +312,3 @@ See [CHANGELOG.md](CHANGELOG.md) for version history.
|
|
|
316
312
|
## Author
|
|
317
313
|
|
|
318
314
|
[Bharani Nitturi](https://github.com/bek42)
|
|
319
|
-
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
""" Session Class to initiate GraphSession object. """
|
|
2
|
+
|
|
3
|
+
import json as json_lib
|
|
4
|
+
from typing import Dict, List, Optional, Union
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from ms_graph.logger.logger_setup import log
|
|
9
|
+
|
|
10
|
+
# Headers whose values are credentials. These must never reach a log sink: a
|
|
11
|
+
# Graph access token stays valid for roughly an hour, and container logs get
|
|
12
|
+
# copied into bug reports, support bundles and pasted terminal output long
|
|
13
|
+
# before that expires.
|
|
14
|
+
SENSITIVE_HEADERS = frozenset(
|
|
15
|
+
{
|
|
16
|
+
"authorization",
|
|
17
|
+
"proxy-authorization",
|
|
18
|
+
"cookie",
|
|
19
|
+
"set-cookie",
|
|
20
|
+
"x-api-key",
|
|
21
|
+
}
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
REDACTED = "<redacted>"
|
|
25
|
+
|
|
26
|
+
# Ceiling on how much of a body reaches the debug log. Graph returns whole
|
|
27
|
+
# file listings and workbook ranges; logging those in full buries everything
|
|
28
|
+
# else and can spill user content into the log.
|
|
29
|
+
MAX_LOGGED_BODY = 2048
|
|
30
|
+
|
|
31
|
+
# Without a timeout a stalled connection hangs the caller forever. Long-lived
|
|
32
|
+
# pollers are the usual victim -- they simply stop, with no error to show.
|
|
33
|
+
#
|
|
34
|
+
# Deliberately generous. requests applies this to the connect and to the gap
|
|
35
|
+
# between bytes, not to total duration, and some Graph endpoints (copy
|
|
36
|
+
# operations, large workbook recalculations, tenant-wide search) sit quiet for
|
|
37
|
+
# a while before the first byte. A tight value here would turn working calls
|
|
38
|
+
# in existing consumers into timeouts; this only converts an indefinite hang
|
|
39
|
+
# into a bounded failure. Pass `timeout` explicitly to tighten it per call.
|
|
40
|
+
DEFAULT_TIMEOUT = 120
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def redact_headers(headers: Optional[Dict[str, str]]) -> Dict[str, str]:
|
|
44
|
+
"""Copy `headers`, replacing credential values with a placeholder.
|
|
45
|
+
|
|
46
|
+
### Parameters
|
|
47
|
+
----
|
|
48
|
+
headers : dict
|
|
49
|
+
The headers to sanitise. Matching is case-insensitive, since
|
|
50
|
+
`requests` preserves whatever casing the server or caller used.
|
|
51
|
+
|
|
52
|
+
### Returns
|
|
53
|
+
----
|
|
54
|
+
dict :
|
|
55
|
+
The same mapping with sensitive values replaced by `REDACTED`.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
if not headers:
|
|
59
|
+
return {}
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
key: (REDACTED if key.lower() in SENSITIVE_HEADERS else value)
|
|
63
|
+
for key, value in headers.items()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def truncate_body(body: Union[str, bytes, None]) -> str:
|
|
68
|
+
"""Render a request or response body for logging, bounded in size.
|
|
69
|
+
|
|
70
|
+
### Parameters
|
|
71
|
+
----
|
|
72
|
+
body : str | bytes | None
|
|
73
|
+
The payload to render.
|
|
74
|
+
|
|
75
|
+
### Returns
|
|
76
|
+
----
|
|
77
|
+
str :
|
|
78
|
+
The decoded body, cut off at `MAX_LOGGED_BODY` characters with a note
|
|
79
|
+
recording the original length.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
if body is None:
|
|
83
|
+
return ""
|
|
84
|
+
|
|
85
|
+
if isinstance(body, bytes):
|
|
86
|
+
# errors="replace" rather than "ascii": Graph returns UTF-8, and file
|
|
87
|
+
# names routinely carry non-ASCII characters.
|
|
88
|
+
text = body.decode("utf-8", errors="replace")
|
|
89
|
+
else:
|
|
90
|
+
text = str(body)
|
|
91
|
+
|
|
92
|
+
if len(text) <= MAX_LOGGED_BODY:
|
|
93
|
+
return text
|
|
94
|
+
|
|
95
|
+
return f"{text[:MAX_LOGGED_BODY]}... [truncated, {len(text)} characters total]"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class GraphSession:
|
|
99
|
+
|
|
100
|
+
"""Serves as the Session for the Current Microsoft
|
|
101
|
+
Graph API."""
|
|
102
|
+
|
|
103
|
+
def __init__(self, client: object) -> None:
|
|
104
|
+
"""Initializes the `GraphSession` client.
|
|
105
|
+
|
|
106
|
+
### Overview:
|
|
107
|
+
----
|
|
108
|
+
The GraphSession object handles all the requests made
|
|
109
|
+
for the different endpoints on the Microsoft Graph API.
|
|
110
|
+
|
|
111
|
+
### Arguments:
|
|
112
|
+
----
|
|
113
|
+
client (str): The Microsoft Graph API Python Client.
|
|
114
|
+
|
|
115
|
+
### Usage:
|
|
116
|
+
----
|
|
117
|
+
>>> graph_session = GraphSession()
|
|
118
|
+
"""
|
|
119
|
+
from ms_graph.client import MicrosoftGraphClient
|
|
120
|
+
|
|
121
|
+
self.client: MicrosoftGraphClient = client
|
|
122
|
+
|
|
123
|
+
# One session for the life of the object rather than one per call, so
|
|
124
|
+
# the TLS handshake and connection pool are reused across requests.
|
|
125
|
+
self._request_session = requests.Session()
|
|
126
|
+
self._request_session.verify = True
|
|
127
|
+
|
|
128
|
+
def close(self) -> None:
|
|
129
|
+
"""Release the underlying HTTP connection pool."""
|
|
130
|
+
|
|
131
|
+
self._request_session.close()
|
|
132
|
+
|
|
133
|
+
def build_headers(self, additional_args: dict = None) -> Dict:
|
|
134
|
+
"""Used to build the headers needed to make the request.
|
|
135
|
+
|
|
136
|
+
### Parameters
|
|
137
|
+
----
|
|
138
|
+
additional_args : dict (optional, Default=None)
|
|
139
|
+
Any additional headers that need to be sent in the
|
|
140
|
+
request.
|
|
141
|
+
|
|
142
|
+
### Returns
|
|
143
|
+
----
|
|
144
|
+
dict :
|
|
145
|
+
A dictionary containing all the components.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
# Define the base headers.
|
|
149
|
+
headers = {
|
|
150
|
+
"Authorization": f"Bearer {self.client.access_token}"
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if additional_args:
|
|
154
|
+
headers.update(additional_args)
|
|
155
|
+
|
|
156
|
+
return headers
|
|
157
|
+
|
|
158
|
+
def build_url(self, endpoint: str) -> str:
|
|
159
|
+
"""Build the URL used the make string.
|
|
160
|
+
|
|
161
|
+
### Parameters
|
|
162
|
+
----
|
|
163
|
+
endpoint : str
|
|
164
|
+
The endpoint used to make the full URL.
|
|
165
|
+
|
|
166
|
+
### Returns
|
|
167
|
+
----
|
|
168
|
+
str:
|
|
169
|
+
The full URL with the endpoint needed.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
url = self.client.RESOURCE + self.client.api_version + "/" + endpoint
|
|
173
|
+
log.debug("Prepared URL - %s", url)
|
|
174
|
+
return url
|
|
175
|
+
|
|
176
|
+
def make_request(
|
|
177
|
+
self,
|
|
178
|
+
method: str,
|
|
179
|
+
endpoint: str,
|
|
180
|
+
params: dict = None,
|
|
181
|
+
data: dict = None,
|
|
182
|
+
json: dict = None,
|
|
183
|
+
additional_headers: dict = None,
|
|
184
|
+
expect_no_response: bool = False,
|
|
185
|
+
timeout: Optional[float] = DEFAULT_TIMEOUT,
|
|
186
|
+
) -> Union[Dict, List]:
|
|
187
|
+
"""Handles all the requests in the library.
|
|
188
|
+
|
|
189
|
+
### Overview:
|
|
190
|
+
---
|
|
191
|
+
A central function used to handle all the requests made in the library,
|
|
192
|
+
this function handles building the URL, defining Content-Type, passing
|
|
193
|
+
through payloads, and handling any errors that may arise during the request.
|
|
194
|
+
|
|
195
|
+
### Arguments:
|
|
196
|
+
----
|
|
197
|
+
method : str
|
|
198
|
+
The Request method, can be one of the
|
|
199
|
+
following: ["get","post","put","delete","patch"]
|
|
200
|
+
|
|
201
|
+
endpoint : str
|
|
202
|
+
The API URL endpoint, example is "quotes"
|
|
203
|
+
|
|
204
|
+
params : dict (optional, Default=None)
|
|
205
|
+
The URL params for the request.
|
|
206
|
+
|
|
207
|
+
data : dict (optional, Default=None)
|
|
208
|
+
A data payload for a request.
|
|
209
|
+
|
|
210
|
+
json : dict (optional, Default=None)
|
|
211
|
+
A json data payload for a request
|
|
212
|
+
|
|
213
|
+
expect_no_response: bool (optional, Default=False)
|
|
214
|
+
Some responses will only return a status code,
|
|
215
|
+
so if this is set to True it will only return
|
|
216
|
+
the status code.
|
|
217
|
+
|
|
218
|
+
timeout : float (optional, Default=30)
|
|
219
|
+
Seconds to wait for the server before giving up. Pass `None` to
|
|
220
|
+
wait indefinitely.
|
|
221
|
+
|
|
222
|
+
### Returns:
|
|
223
|
+
----
|
|
224
|
+
Union[List, Dict]:
|
|
225
|
+
The resource object or objects.
|
|
226
|
+
|
|
227
|
+
### Raises:
|
|
228
|
+
----
|
|
229
|
+
requests.HTTPError:
|
|
230
|
+
If the API returns a non-2xx status. The exception carries the
|
|
231
|
+
status line, the method and the URL, and the originating response
|
|
232
|
+
is attached as `.response`.
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
# Build the URL.
|
|
236
|
+
url = self.build_url(endpoint=endpoint)
|
|
237
|
+
|
|
238
|
+
# Define the headers.
|
|
239
|
+
headers = self.build_headers(additional_args=additional_headers)
|
|
240
|
+
|
|
241
|
+
# Define a new request.
|
|
242
|
+
request_request = requests.Request(
|
|
243
|
+
method=method.upper(),
|
|
244
|
+
headers=headers,
|
|
245
|
+
url=url,
|
|
246
|
+
params=params,
|
|
247
|
+
data=data,
|
|
248
|
+
json=json
|
|
249
|
+
).prepare()
|
|
250
|
+
|
|
251
|
+
# Send the request.
|
|
252
|
+
response: requests.Response = self._request_session.send(
|
|
253
|
+
request=request_request,
|
|
254
|
+
timeout=timeout,
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
if request_request.body is not None:
|
|
258
|
+
log.debug("Request body - %s", truncate_body(request_request.body))
|
|
259
|
+
log.debug("Response body - %s", truncate_body(response.content))
|
|
260
|
+
|
|
261
|
+
# If it"s okay and no details.
|
|
262
|
+
if response.ok and expect_no_response:
|
|
263
|
+
return {"status_code": response.status_code}
|
|
264
|
+
elif response.ok and len(response.content) > 0:
|
|
265
|
+
return response.json()
|
|
266
|
+
elif len(response.content) == 0 and response.ok:
|
|
267
|
+
return {
|
|
268
|
+
"message": "Request was successful, status code provided.",
|
|
269
|
+
"status_code": response.status_code
|
|
270
|
+
}
|
|
271
|
+
elif not response.ok:
|
|
272
|
+
|
|
273
|
+
# An error body is not guaranteed to be JSON -- a gateway or proxy
|
|
274
|
+
# in front of Graph may return HTML -- so fall back to raw text
|
|
275
|
+
# rather than letting the decode failure mask the real error.
|
|
276
|
+
try:
|
|
277
|
+
response_body = response.json()
|
|
278
|
+
except ValueError:
|
|
279
|
+
response_body = truncate_body(response.content)
|
|
280
|
+
|
|
281
|
+
# Define the error dict. Request headers are redacted: this dict is
|
|
282
|
+
# written straight to the error log, and the Authorization header
|
|
283
|
+
# holds a live bearer token.
|
|
284
|
+
error_dict = {
|
|
285
|
+
"error_code": response.status_code,
|
|
286
|
+
"response_url": response.url,
|
|
287
|
+
"response_body": response_body,
|
|
288
|
+
"request_headers": redact_headers(response.request.headers),
|
|
289
|
+
"response_method": response.request.method,
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
# Log the error.
|
|
293
|
+
log.error(
|
|
294
|
+
msg=json_lib.dumps(obj=error_dict, indent=4)
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
raise requests.HTTPError(
|
|
298
|
+
f"{response.status_code} {response.reason} for "
|
|
299
|
+
f"{response.request.method} {response.url}",
|
|
300
|
+
response=response,
|
|
301
|
+
)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Adapters between vault backends and the interface the Graph client expects.
|
|
2
|
+
|
|
3
|
+
`MicrosoftGraphClient` reads and writes its OAuth state through a
|
|
4
|
+
`vault_client` shaped like `azkees.az.Az`:
|
|
5
|
+
|
|
6
|
+
get_secret(name=...) -> {"value": "..."}
|
|
7
|
+
set_secret(name=..., value=...) -> bool
|
|
8
|
+
|
|
9
|
+
`azkees.InfisicalVaultHandler` does not match that on either count -- it takes
|
|
10
|
+
`key` positionally and returns the secret as a plain string. Every consumer
|
|
11
|
+
moving from Azure Key Vault to Infisical was therefore writing the same small
|
|
12
|
+
bridge by hand. It lives here instead.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from typing import Any, Dict, Optional
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class InfisicalVaultAdapter:
|
|
19
|
+
|
|
20
|
+
"""Presents an `azkees.InfisicalVaultHandler` as a Graph `vault_client`.
|
|
21
|
+
|
|
22
|
+
### Usage:
|
|
23
|
+
----
|
|
24
|
+
>>> from ms_graph.vault import InfisicalVaultAdapter
|
|
25
|
+
>>> vault = InfisicalVaultAdapter.from_section("ms-graph")
|
|
26
|
+
>>> client = MicrosoftGraphClient(..., vault_client=vault)
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, handler: Any) -> None:
|
|
30
|
+
"""Wrap an already-constructed handler.
|
|
31
|
+
|
|
32
|
+
### Arguments:
|
|
33
|
+
----
|
|
34
|
+
handler : azkees.InfisicalVaultHandler
|
|
35
|
+
Any object exposing `get_secret(key)` and `set_secret(key, value)`.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
self.handler = handler
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def from_section(
|
|
42
|
+
cls, section: str, keys_config_path: Optional[str] = None
|
|
43
|
+
) -> "InfisicalVaultAdapter":
|
|
44
|
+
"""Build a handler for `section` of api_keys.ini and wrap it.
|
|
45
|
+
|
|
46
|
+
### Arguments:
|
|
47
|
+
----
|
|
48
|
+
section : str
|
|
49
|
+
Section holding the Infisical credentials, e.g. "ms-graph".
|
|
50
|
+
|
|
51
|
+
keys_config_path : str (optional, Default=None)
|
|
52
|
+
Path to api_keys.ini. azkees falls back to the
|
|
53
|
+
keys_config_linux / keys_config_windows environment variables.
|
|
54
|
+
|
|
55
|
+
### Returns:
|
|
56
|
+
----
|
|
57
|
+
InfisicalVaultAdapter
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
# Imported here rather than at module scope so that importing
|
|
61
|
+
# ms_graph.vault does not require Infisical credentials to be present.
|
|
62
|
+
from azkees import InfisicalVaultHandler
|
|
63
|
+
|
|
64
|
+
return cls(
|
|
65
|
+
handler=InfisicalVaultHandler(
|
|
66
|
+
section=section, keys_config_path=keys_config_path
|
|
67
|
+
)
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def get_secret(self, name: str) -> Dict[str, str]:
|
|
71
|
+
"""Fetch a secret, wrapped in the dict shape the client expects.
|
|
72
|
+
|
|
73
|
+
### Raises:
|
|
74
|
+
----
|
|
75
|
+
azkees.InfisicalKeyNotFoundError:
|
|
76
|
+
Propagated unchanged when the secret is absent, so callers can
|
|
77
|
+
tell "missing" apart from "empty".
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
return {"value": self.handler.get_secret(name)}
|
|
81
|
+
|
|
82
|
+
def set_secret(self, name: str, value: str) -> bool:
|
|
83
|
+
"""Upsert a secret. Returns True on success."""
|
|
84
|
+
|
|
85
|
+
return self.handler.set_secret(name, value)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ms-graph"
|
|
3
|
+
version = "1.7.0"
|
|
4
|
+
description = "A Python Client Application that allows interaction with the Microsoft Graph API."
|
|
5
|
+
authors = [{ name = "bek42", email = "bharani.nitturi@gmail.com" }]
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.12,<4.0"
|
|
10
|
+
keywords = ["microsoft", "graph", "api", "onedrive", "outlook", "sharepoint", "excel", "onenote"]
|
|
11
|
+
# No "License :: OSI Approved" classifier: PEP 639 replaces it with the SPDX
|
|
12
|
+
# `license` field above, and declaring both is rejected by current backends.
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 5 - Production/Stable",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.12",
|
|
18
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
19
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"azkees[infisical]>=7.0.0,<8.0.0",
|
|
23
|
+
# 1.6 is the floor, not 1.5: pylogpy 1.5.x constructs azkees.az.Az at
|
|
24
|
+
# import and pulls the SMTP alerting credentials out of Azure Key Vault.
|
|
25
|
+
# 1.6+ uses azkees.InfisicalClient. Every consumer of this package
|
|
26
|
+
# inherits whichever version resolves here, so a >=1.5.2 range silently
|
|
27
|
+
# puts them back on Azure.
|
|
28
|
+
"pylogpy>=1.6.2,<2.0.0",
|
|
29
|
+
"msal>=1.29.0,<2.0.0",
|
|
30
|
+
"requests>=2.32.3,<3.0.0",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://github.com/bek42/ms_graph"
|
|
35
|
+
Repository = "https://github.com/bek42/ms_graph"
|
|
36
|
+
Changelog = "https://github.com/bek42/ms_graph/blob/main/CHANGELOG.md"
|
|
37
|
+
|
|
38
|
+
[dependency-groups]
|
|
39
|
+
dev = [
|
|
40
|
+
"commitizen>=3.27.0,<4.0.0",
|
|
41
|
+
"pytest>=8.0,<9.0",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[tool.commitizen]
|
|
45
|
+
name = "cz_conventional_commits"
|
|
46
|
+
tag_format = "v$version"
|
|
47
|
+
version_scheme = "pep440"
|
|
48
|
+
# Reads [project].version now that the metadata is PEP 621 rather than
|
|
49
|
+
# [tool.poetry]. Leaving this as "poetry" makes the bump job fail to find a
|
|
50
|
+
# version at all.
|
|
51
|
+
version_provider = "pep621"
|
|
52
|
+
update_changelog_on_bump = true
|
|
53
|
+
|
|
54
|
+
[build-system]
|
|
55
|
+
requires = ["hatchling"]
|
|
56
|
+
build-backend = "hatchling.build"
|
|
57
|
+
|
|
58
|
+
[tool.hatch.build.targets.wheel]
|
|
59
|
+
# The distribution is "ms-graph" but the import package is "ms_graph"; the
|
|
60
|
+
# backend cannot infer one from the other.
|
|
61
|
+
packages = ["ms_graph"]
|
|
62
|
+
|
|
63
|
+
[tool.hatch.build.targets.sdist]
|
|
64
|
+
include = ["ms_graph", "tests", "README.md", "LICENSE", "CHANGELOG.md"]
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Tests for GraphSession request handling and log hygiene.
|
|
2
|
+
|
|
3
|
+
These run offline: the transport is stubbed, so no Graph credentials or
|
|
4
|
+
network access are needed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
|
|
9
|
+
from unittest import mock
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
import requests
|
|
13
|
+
|
|
14
|
+
from ms_graph import session as session_module
|
|
15
|
+
from ms_graph.session import GraphSession, redact_headers, truncate_body
|
|
16
|
+
|
|
17
|
+
TOKEN = "SUPERSECRETTOKEN"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FakeClient:
|
|
21
|
+
"""Stands in for MicrosoftGraphClient, which needs real credentials."""
|
|
22
|
+
|
|
23
|
+
RESOURCE = "https://graph.microsoft.com/"
|
|
24
|
+
api_version = "v1.0"
|
|
25
|
+
access_token = TOKEN
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pytest.fixture(name="graph_session")
|
|
29
|
+
def fixture_graph_session() -> GraphSession:
|
|
30
|
+
return GraphSession(client=FakeClient())
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _make_response(status: int, reason: str, content: bytes) -> requests.Response:
|
|
34
|
+
response = requests.Response()
|
|
35
|
+
response.status_code = status
|
|
36
|
+
response.reason = reason
|
|
37
|
+
response._content = content # pylint: disable=protected-access
|
|
38
|
+
response.url = "https://graph.microsoft.com/v1.0/me/drive"
|
|
39
|
+
response.request = requests.Request(
|
|
40
|
+
method="GET",
|
|
41
|
+
url=response.url,
|
|
42
|
+
headers={"Authorization": f"Bearer {TOKEN}"},
|
|
43
|
+
).prepare()
|
|
44
|
+
return response
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class TestRedactHeaders:
|
|
48
|
+
|
|
49
|
+
def test_credential_headers_are_masked(self):
|
|
50
|
+
redacted = redact_headers(
|
|
51
|
+
{
|
|
52
|
+
"Authorization": f"Bearer {TOKEN}",
|
|
53
|
+
"Cookie": "session=abc",
|
|
54
|
+
"Accept": "application/json",
|
|
55
|
+
}
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
assert redacted["Authorization"] == "<redacted>"
|
|
59
|
+
assert redacted["Cookie"] == "<redacted>"
|
|
60
|
+
assert redacted["Accept"] == "application/json"
|
|
61
|
+
|
|
62
|
+
def test_matching_is_case_insensitive(self):
|
|
63
|
+
# requests preserves whatever casing the caller or server used.
|
|
64
|
+
assert redact_headers({"AUTHORIZATION": "x"})["AUTHORIZATION"] == "<redacted>"
|
|
65
|
+
assert redact_headers({"authorization": "x"})["authorization"] == "<redacted>"
|
|
66
|
+
|
|
67
|
+
def test_empty_input(self):
|
|
68
|
+
assert redact_headers(None) == {}
|
|
69
|
+
assert redact_headers({}) == {}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class TestTruncateBody:
|
|
73
|
+
|
|
74
|
+
def test_none_renders_empty(self):
|
|
75
|
+
assert truncate_body(None) == ""
|
|
76
|
+
|
|
77
|
+
def test_non_ascii_bytes_survive(self):
|
|
78
|
+
# The previous implementation decoded as ASCII and raised on any
|
|
79
|
+
# accented file name coming back from Graph.
|
|
80
|
+
assert truncate_body("café".encode("utf-8")) == "café"
|
|
81
|
+
|
|
82
|
+
def test_long_bodies_are_bounded(self):
|
|
83
|
+
rendered = truncate_body(b"a" * 5000)
|
|
84
|
+
|
|
85
|
+
assert "truncated" in rendered
|
|
86
|
+
assert len(rendered) < session_module.MAX_LOGGED_BODY + 100
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class TestMakeRequestErrors:
|
|
90
|
+
|
|
91
|
+
def test_bearer_token_never_reaches_the_log(self, graph_session, monkeypatch):
|
|
92
|
+
captured = []
|
|
93
|
+
monkeypatch.setattr(
|
|
94
|
+
session_module.log, "error", lambda msg=None, *a, **k: captured.append(str(msg))
|
|
95
|
+
)
|
|
96
|
+
response = _make_response(
|
|
97
|
+
404, "Not Found", json.dumps({"error": {"code": "itemNotFound"}}).encode()
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
with mock.patch.object(graph_session._request_session, "send", return_value=response):
|
|
101
|
+
with pytest.raises(requests.HTTPError):
|
|
102
|
+
graph_session.make_request(method="get", endpoint="me/drive")
|
|
103
|
+
|
|
104
|
+
logged = "\n".join(captured)
|
|
105
|
+
assert TOKEN not in logged
|
|
106
|
+
assert "<redacted>" in logged
|
|
107
|
+
|
|
108
|
+
def test_error_carries_status_and_response(self, graph_session, monkeypatch):
|
|
109
|
+
monkeypatch.setattr(session_module.log, "error", lambda *a, **k: None)
|
|
110
|
+
response = _make_response(404, "Not Found", b'{"error": {}}')
|
|
111
|
+
|
|
112
|
+
with mock.patch.object(graph_session._request_session, "send", return_value=response):
|
|
113
|
+
with pytest.raises(requests.HTTPError) as excinfo:
|
|
114
|
+
graph_session.make_request(method="get", endpoint="me/drive")
|
|
115
|
+
|
|
116
|
+
# The bare `raise requests.HTTPError()` this replaced told the caller
|
|
117
|
+
# nothing at all about what had failed.
|
|
118
|
+
assert "404" in str(excinfo.value)
|
|
119
|
+
assert excinfo.value.response is response
|
|
120
|
+
assert TOKEN not in str(excinfo.value)
|
|
121
|
+
|
|
122
|
+
def test_non_json_error_body_does_not_mask_the_error(self, graph_session, monkeypatch):
|
|
123
|
+
monkeypatch.setattr(session_module.log, "error", lambda *a, **k: None)
|
|
124
|
+
# A proxy in front of Graph can return HTML rather than JSON.
|
|
125
|
+
response = _make_response(502, "Bad Gateway", b"<html>down</html>")
|
|
126
|
+
|
|
127
|
+
with mock.patch.object(graph_session._request_session, "send", return_value=response):
|
|
128
|
+
with pytest.raises(requests.HTTPError) as excinfo:
|
|
129
|
+
graph_session.make_request(method="get", endpoint="me/drive")
|
|
130
|
+
|
|
131
|
+
assert "502" in str(excinfo.value)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class TestMakeRequestSuccess:
|
|
135
|
+
|
|
136
|
+
def test_timeout_is_passed_to_the_transport(self, graph_session):
|
|
137
|
+
response = _make_response(200, "OK", b'{"value": []}')
|
|
138
|
+
|
|
139
|
+
with mock.patch.object(
|
|
140
|
+
graph_session._request_session, "send", return_value=response
|
|
141
|
+
) as send:
|
|
142
|
+
graph_session.make_request(method="get", endpoint="me/drive")
|
|
143
|
+
|
|
144
|
+
# Without a timeout a stalled connection hangs the caller forever.
|
|
145
|
+
assert send.call_args.kwargs["timeout"] == session_module.DEFAULT_TIMEOUT
|
|
146
|
+
|
|
147
|
+
def test_empty_body_returns_status(self, graph_session):
|
|
148
|
+
response = _make_response(204, "No Content", b"")
|
|
149
|
+
|
|
150
|
+
with mock.patch.object(graph_session._request_session, "send", return_value=response):
|
|
151
|
+
result = graph_session.make_request(method="get", endpoint="me/drive")
|
|
152
|
+
|
|
153
|
+
assert result["status_code"] == 204
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Tests for the Infisical vault adapter.
|
|
2
|
+
|
|
3
|
+
Offline: a stub stands in for azkees.InfisicalVaultHandler, so no Infisical
|
|
4
|
+
credentials or network access are needed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from ms_graph.vault import InfisicalVaultAdapter
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class StubHandler:
|
|
13
|
+
"""Mimics azkees.InfisicalVaultHandler's actual signatures.
|
|
14
|
+
|
|
15
|
+
Note both mismatches with what the Graph client expects: `key` is
|
|
16
|
+
positional rather than `name`, and a bare string comes back rather than
|
|
17
|
+
a {"value": ...} mapping.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self):
|
|
21
|
+
self.store = {"graphcid": "the-client-id"}
|
|
22
|
+
self.set_calls = []
|
|
23
|
+
|
|
24
|
+
def get_secret(self, key: str) -> str:
|
|
25
|
+
if key not in self.store:
|
|
26
|
+
raise KeyError(key)
|
|
27
|
+
return self.store[key]
|
|
28
|
+
|
|
29
|
+
def set_secret(self, key: str, value: str) -> bool:
|
|
30
|
+
self.set_calls.append((key, value))
|
|
31
|
+
return True
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.fixture(name="handler")
|
|
35
|
+
def fixture_handler() -> StubHandler:
|
|
36
|
+
return StubHandler()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@pytest.fixture(name="vault")
|
|
40
|
+
def fixture_vault(handler: StubHandler) -> InfisicalVaultAdapter:
|
|
41
|
+
return InfisicalVaultAdapter(handler=handler)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_get_secret_returns_the_mapping_the_client_expects(vault):
|
|
45
|
+
# client.py does `result["value"]`; a bare string would subscript to a
|
|
46
|
+
# single character rather than failing loudly.
|
|
47
|
+
assert vault.get_secret(name="graphcid") == {"value": "the-client-id"}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_get_secret_accepts_name_as_a_keyword(vault):
|
|
51
|
+
# MicrosoftGraphClient._state calls get_secret(name=...).
|
|
52
|
+
assert vault.get_secret(name="graphcid")["value"] == "the-client-id"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_set_secret_translates_to_positional_key(vault, handler):
|
|
56
|
+
# The handler takes `key`, so passing `name=` through would raise.
|
|
57
|
+
assert vault.set_secret(name="msgraphstate", value="{}") is True
|
|
58
|
+
assert handler.set_calls == [("msgraphstate", "{}")]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_missing_secret_propagates(vault):
|
|
62
|
+
with pytest.raises(KeyError):
|
|
63
|
+
vault.get_secret(name="absent")
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Manual smoke script to check basic functionality against a real tenant.
|
|
3
|
+
|
|
4
|
+
Not part of the automated suite -- it needs live Infisical credentials and
|
|
5
|
+
performs an interactive login. Run it by hand:
|
|
6
|
+
|
|
7
|
+
uv run python tests/use_client.py
|
|
8
|
+
|
|
9
|
+
Requires api_keys.ini to be reachable (via the keys_config_linux /
|
|
10
|
+
keys_config_windows environment variables) with an [ms-graph] section holding
|
|
11
|
+
infisical_url, infisical_client_id, infisical_client_secret,
|
|
12
|
+
infisical_project_id, infisical_environment and infisical_secret_path.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from pprint import pprint
|
|
16
|
+
|
|
17
|
+
from azkees import InfisicalKeyNotFoundError
|
|
18
|
+
|
|
19
|
+
from ms_graph.client import MicrosoftGraphClient
|
|
20
|
+
from ms_graph.vault import InfisicalVaultAdapter
|
|
21
|
+
|
|
22
|
+
# Section of api_keys.ini holding the Infisical credentials. The Azure Key
|
|
23
|
+
# Vault sections in that file are legacy; this project reads Infisical only.
|
|
24
|
+
VAULT_SECTION = "ms-graph"
|
|
25
|
+
|
|
26
|
+
SCOPES = [
|
|
27
|
+
"Files.Read",
|
|
28
|
+
"Files.Read.All",
|
|
29
|
+
"Files.ReadWrite",
|
|
30
|
+
"Files.ReadWrite.All",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
# Names of the secrets as stored in Infisical.
|
|
34
|
+
CLIENT_ID_KEY = "graphcid"
|
|
35
|
+
CLIENT_SECRET_KEY = "graphsc"
|
|
36
|
+
REDIRECT_URI_KEY = "graphi"
|
|
37
|
+
STATE_KEY = "msgraphstate"
|
|
38
|
+
|
|
39
|
+
vault = InfisicalVaultAdapter.from_section(VAULT_SECTION)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def fetch(key: str) -> str:
|
|
43
|
+
"""Read one secret, naming the missing key if it is not there."""
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
return vault.get_secret(name=key)["value"]
|
|
47
|
+
except InfisicalKeyNotFoundError as exc:
|
|
48
|
+
raise InfisicalKeyNotFoundError(
|
|
49
|
+
f"'{key}' not found in section [{VAULT_SECTION}]"
|
|
50
|
+
) from exc
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Initialize the Client. The vault also stores the OAuth state, so the client
|
|
54
|
+
# reads and refreshes it through the same adapter.
|
|
55
|
+
graph_client = MicrosoftGraphClient(
|
|
56
|
+
client_id=fetch(CLIENT_ID_KEY),
|
|
57
|
+
client_secret=fetch(CLIENT_SECRET_KEY),
|
|
58
|
+
redirect_uri=fetch(REDIRECT_URI_KEY),
|
|
59
|
+
scope=SCOPES,
|
|
60
|
+
vault_client=vault,
|
|
61
|
+
credentials=fetch(STATE_KEY),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
# Login to the Client.
|
|
65
|
+
graph_client.login()
|
|
66
|
+
|
|
67
|
+
# Grab the Drive Services.
|
|
68
|
+
drive_services = graph_client.drives()
|
|
69
|
+
|
|
70
|
+
# List the Root Drive.
|
|
71
|
+
pprint(drive_services.get_root_drive())
|
|
72
|
+
|
|
73
|
+
# List the Root Drive Deltas.
|
|
74
|
+
pprint(drive_services.get_root_drive_delta())
|
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
""" Session Class to initiate GraphSession object. """
|
|
2
|
-
|
|
3
|
-
import json as json_lib
|
|
4
|
-
from ms_graph.logger.logger_setup import log
|
|
5
|
-
from typing import Dict, List, Union
|
|
6
|
-
|
|
7
|
-
import requests
|
|
8
|
-
|
|
9
|
-
class GraphSession():
|
|
10
|
-
|
|
11
|
-
"""Serves as the Session for the Current Microsoft
|
|
12
|
-
Graph API."""
|
|
13
|
-
|
|
14
|
-
def __init__(self, client: object) -> None:
|
|
15
|
-
"""Initializes the `GraphSession` client.
|
|
16
|
-
|
|
17
|
-
### Overview:
|
|
18
|
-
----
|
|
19
|
-
The GraphSession object handles all the requests made
|
|
20
|
-
for the different endpoints on the Microsoft Graph API.
|
|
21
|
-
|
|
22
|
-
### Arguments:
|
|
23
|
-
----
|
|
24
|
-
client (str): The Microsoft Graph API Python Client.
|
|
25
|
-
|
|
26
|
-
### Usage:
|
|
27
|
-
----
|
|
28
|
-
>>> graph_session = GraphSession()
|
|
29
|
-
"""
|
|
30
|
-
from ms_graph.client import MicrosoftGraphClient
|
|
31
|
-
|
|
32
|
-
self.client: MicrosoftGraphClient = client
|
|
33
|
-
|
|
34
|
-
def build_headers(self, additional_args: dict = None) -> Dict:
|
|
35
|
-
"""Used to build the headers needed to make the request.
|
|
36
|
-
|
|
37
|
-
### Parameters
|
|
38
|
-
----
|
|
39
|
-
additional_args : dict (optional, Default=None)
|
|
40
|
-
Any additional headers that need to be sent in the
|
|
41
|
-
request.
|
|
42
|
-
|
|
43
|
-
### Returns
|
|
44
|
-
----
|
|
45
|
-
dict :
|
|
46
|
-
A dictionary containing all the components.
|
|
47
|
-
"""
|
|
48
|
-
|
|
49
|
-
# Define the base headers.
|
|
50
|
-
headers = {
|
|
51
|
-
"Authorization": f"Bearer {self.client.access_token}"
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
if additional_args:
|
|
55
|
-
headers.update(additional_args)
|
|
56
|
-
|
|
57
|
-
return headers
|
|
58
|
-
|
|
59
|
-
def build_url(self, endpoint: str) -> str:
|
|
60
|
-
"""Build the URL used the make string.
|
|
61
|
-
|
|
62
|
-
### Parameters
|
|
63
|
-
----
|
|
64
|
-
endpoint : str
|
|
65
|
-
The endpoint used to make the full URL.
|
|
66
|
-
|
|
67
|
-
### Returns
|
|
68
|
-
----
|
|
69
|
-
str:
|
|
70
|
-
The full URL with the endpoint needed.
|
|
71
|
-
"""
|
|
72
|
-
|
|
73
|
-
url = self.client.RESOURCE + self.client.api_version + "/" + endpoint
|
|
74
|
-
log.debug("Prepared URL - %s", url)
|
|
75
|
-
return url
|
|
76
|
-
|
|
77
|
-
def make_request(
|
|
78
|
-
self,
|
|
79
|
-
method: str,
|
|
80
|
-
endpoint: str,
|
|
81
|
-
params: dict = None,
|
|
82
|
-
data: dict = None,
|
|
83
|
-
json: dict = None,
|
|
84
|
-
additional_headers: dict = None,
|
|
85
|
-
expect_no_response: bool = False
|
|
86
|
-
) -> Union[Dict, List]:
|
|
87
|
-
"""Handles all the requests in the library.
|
|
88
|
-
|
|
89
|
-
### Overview:
|
|
90
|
-
---
|
|
91
|
-
A central function used to handle all the requests made in the library,
|
|
92
|
-
this function handles building the URL, defining Content-Type, passing
|
|
93
|
-
through payloads, and handling any errors that may arise during the request.
|
|
94
|
-
|
|
95
|
-
### Arguments:
|
|
96
|
-
----
|
|
97
|
-
method : str
|
|
98
|
-
The Request method, can be one of the
|
|
99
|
-
following: ["get","post","put","delete","patch"]
|
|
100
|
-
|
|
101
|
-
endpoint : str
|
|
102
|
-
The API URL endpoint, example is "quotes"
|
|
103
|
-
|
|
104
|
-
params : dict (optional, Default=None)
|
|
105
|
-
The URL params for the request.
|
|
106
|
-
|
|
107
|
-
data : dict (optional, Default=None)
|
|
108
|
-
A data payload for a request.
|
|
109
|
-
|
|
110
|
-
json : dict (optional, Default=None)
|
|
111
|
-
A json data payload for a request
|
|
112
|
-
|
|
113
|
-
expect_no_response: bool (optional, Default=False)
|
|
114
|
-
Some responses will only return a status code,
|
|
115
|
-
so if this is set to True it will only return
|
|
116
|
-
the status code.
|
|
117
|
-
|
|
118
|
-
### Returns:
|
|
119
|
-
----
|
|
120
|
-
Union[List, Dict]:
|
|
121
|
-
The resource object or objects.
|
|
122
|
-
"""
|
|
123
|
-
|
|
124
|
-
# Build the URL.
|
|
125
|
-
url = self.build_url(endpoint=endpoint)
|
|
126
|
-
|
|
127
|
-
# Define the headers.
|
|
128
|
-
headers = self.build_headers(additional_args=additional_headers)
|
|
129
|
-
|
|
130
|
-
# Define a new session.
|
|
131
|
-
request_session = requests.Session()
|
|
132
|
-
request_session.verify = True
|
|
133
|
-
|
|
134
|
-
# Define a new request.
|
|
135
|
-
request_request = requests.Request(
|
|
136
|
-
method=method.upper(),
|
|
137
|
-
headers=headers,
|
|
138
|
-
url=url,
|
|
139
|
-
params=params,
|
|
140
|
-
data=data,
|
|
141
|
-
json=json
|
|
142
|
-
).prepare()
|
|
143
|
-
|
|
144
|
-
# Send the request.
|
|
145
|
-
response: requests.Response = request_session.send(
|
|
146
|
-
request=request_request
|
|
147
|
-
)
|
|
148
|
-
|
|
149
|
-
if request_request.body is not None:
|
|
150
|
-
log.debug(request_request.body)
|
|
151
|
-
log.debug(response.content)
|
|
152
|
-
|
|
153
|
-
# Close the session.
|
|
154
|
-
request_session.close()
|
|
155
|
-
|
|
156
|
-
# If it"s okay and no details.
|
|
157
|
-
if response.ok and expect_no_response:
|
|
158
|
-
return {"status_code": response.status_code}
|
|
159
|
-
elif response.ok and len(response.content) > 0:
|
|
160
|
-
return response.json()
|
|
161
|
-
elif len(response.content) == 0 and response.ok:
|
|
162
|
-
return {
|
|
163
|
-
"message": "Request was successful, status code provided.",
|
|
164
|
-
"status_code": response.status_code
|
|
165
|
-
}
|
|
166
|
-
elif not response.ok:
|
|
167
|
-
|
|
168
|
-
# Define the error dict.
|
|
169
|
-
error_dict = {
|
|
170
|
-
"error_code": response.status_code,
|
|
171
|
-
"response_url": response.url,
|
|
172
|
-
"response_body": json_lib.loads(response.content.decode("ascii")),
|
|
173
|
-
"response_request": dict(response.request.headers),
|
|
174
|
-
"response_method": response.request.method,
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
# Log the error.
|
|
178
|
-
log.error(
|
|
179
|
-
msg=json_lib.dumps(obj=error_dict, indent=4)
|
|
180
|
-
)
|
|
181
|
-
|
|
182
|
-
raise requests.HTTPError()
|
ms_graph-1.6.2/pyproject.toml
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
[tool.poetry]
|
|
2
|
-
name = "ms-graph"
|
|
3
|
-
version = "1.6.2"
|
|
4
|
-
description = "A Python Client Application that allows interaction with the Microsoft Graph API."
|
|
5
|
-
authors = ["bek42 <bharani.nitturi@gmail.com>"]
|
|
6
|
-
license = "MIT"
|
|
7
|
-
readme = "README.md"
|
|
8
|
-
keywords = ["microsoft", "graph", "api", "onedrive", "outlook", "sharepoint", "excel", "onenote"]
|
|
9
|
-
classifiers = [
|
|
10
|
-
"Development Status :: 5 - Production/Stable",
|
|
11
|
-
"Intended Audience :: Developers",
|
|
12
|
-
"License :: OSI Approved :: MIT License",
|
|
13
|
-
"Programming Language :: Python :: 3",
|
|
14
|
-
"Programming Language :: Python :: 3.12",
|
|
15
|
-
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
16
|
-
"Topic :: Internet :: WWW/HTTP",
|
|
17
|
-
]
|
|
18
|
-
|
|
19
|
-
[tool.poetry.dependencies]
|
|
20
|
-
python = ">=3.12,<4.0"
|
|
21
|
-
azkees = {version = "^7.0.0", extras = ["infisical"]}
|
|
22
|
-
pylogpy = "^1.5.2"
|
|
23
|
-
msal = "^1.29.0"
|
|
24
|
-
requests = "^2.32.3"
|
|
25
|
-
|
|
26
|
-
[tool.poetry.urls]
|
|
27
|
-
Homepage = "https://github.com/bek42/ms_graph"
|
|
28
|
-
Repository = "https://github.com/bek42/ms_graph"
|
|
29
|
-
Changelog = "https://github.com/bek42/ms_graph/blob/main/CHANGELOG.md"
|
|
30
|
-
|
|
31
|
-
[tool.poetry.group.dev.dependencies]
|
|
32
|
-
commitizen = "^3.27.0"
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
[tool.commitizen]
|
|
36
|
-
name = "cz_conventional_commits"
|
|
37
|
-
tag_format = "v$version"
|
|
38
|
-
version_scheme = "pep440"
|
|
39
|
-
version_provider = "poetry"
|
|
40
|
-
update_changelog_on_bump = true
|
|
41
|
-
[build-system]
|
|
42
|
-
requires = ["poetry-core"]
|
|
43
|
-
build-backend = "poetry.core.masonry.api"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|