Debian Codegraph @

src/globus_sdk/token_storage/legacy/file_adapters.py

raw
1 from __future__ import annotations
2
3 import json
4 import pathlib
5 import typing as t
6
7 import globus_sdk
8 from globus_sdk import __version__
9
10 from .base import FileAdapter
11
12 # use the non-annotation form of TypedDict to apply a non-identifier key
13 _JSONFileData_0 = t.TypedDict("_JSONFileData_0", {"globus-sdk.version": str})
14
15
16 # then inherit from that TypedDict to build the "real" TypedDict with the advantages of
17 # the annotation-based syntax
18 class _JSONFileData(_JSONFileData_0): # pylint: disable=inherit-non-class
19 by_rs: dict[str, t.Any]
20 format_version: str
21
22
23 class SimpleJSONFileAdapter(FileAdapter):
24 """
25 :param filename: the name of the file to write to and read from
26
27 A storage adapter for storing tokens in JSON files.
28 """
29
30 # the version for the current data format used by the file adapter
31 #
32 # if the format needs to be changed in the future, the adapter can dispatch on
33 # the declared format version in the file to decide how to handle the data
34 format_version = "1.0"
35 # the supported versions (data not in these versions causes an error)
36 supported_versions = ("1.0",)
37
38 def __init__(self, filename: pathlib.Path | str) -> None:
39 self.filename = str(filename)
40
41 def _invalid(self, msg: str) -> t.NoReturn:
42 raise ValueError(
43 f"{msg} while loading from '{self.filename}' for JSON File Adapter"
44 )
45
46 def _raw_load(self) -> dict[str, t.Any]:
47 """
48 Load the file contents as JSON and return the resulting dict
49 object. If a dict is not found, raises an error.
50 """
51 with open(self.filename, encoding="utf-8") as f:
52 val = json.load(f)
53 if not isinstance(val, dict):
54 self._invalid("Found non-dict root data")
55 return val
56
57 def _handle_formats(self, read_data: dict[str, t.Any]) -> _JSONFileData:
58 """Handle older data formats supported by globus_sdk.token_storage
59
60 if the data is not in a known/recognized format, this will error
61 otherwise, reshape the data to the current supported format and return it
62 """
63 format_version = read_data.get("format_version")
64 if format_version not in self.supported_versions:
65 raise ValueError(
66 f"cannot store data using SimpleJSONFileAdapter({self.filename} "
67 "existing data file is in an unknown format "
68 f"(format_version={format_version})"
69 )
70 if not isinstance(read_data.get("by_rs"), dict):
71 raise ValueError(
72 f"cannot store data using SimpleJSONFileAdapter({self.filename} "
73 "existing data file is malformed"
74 )
75 if any(
76 k not in read_data
77 for k in ("by_rs", "format_version", "globus-sdk.version")
78 ):
79 self._invalid("Missing required keys")
80 if not isinstance(by_rs_dict := read_data["by_rs"], dict) or any(
81 not isinstance(k, str) for k in by_rs_dict
82 ):
83 self._invalid("Invalid 'by_rs'")
84 if not isinstance(read_data["format_version"], str):
85 self._invalid("Invalid 'format_version'")
86 if not isinstance(read_data["globus-sdk.version"], str):
87 self._invalid("Invalid 'globus-sdk.version'")
88 return read_data # type: ignore[return-value]
89
90 def _load(self) -> _JSONFileData:
91 """
92 Load data from the file and ensure that the data is in a modern format which can
93 be handled by the rest of the adapter.
94
95 If the file is missing, this will return a "skeleton" for new data.
96 """
97 try:
98 data = self._raw_load()
99 except FileNotFoundError:
100 return {
101 "by_rs": {},
102 "format_version": self.format_version,
103 "globus-sdk.version": __version__,
104 }
105 return self._handle_formats(data)
106
107 def store(self, token_response: globus_sdk.OAuthTokenResponse) -> None:
108 """
109 By default, ``self.on_refresh`` is just an alias for this function.
110
111 Given a token response, extract all the token data and write it to
112 ``self.filename`` as JSON data.
113 Additionally will write the version of ``globus_sdk.token_storage``
114 which was in use.
115
116 Under the assumption that this may be running on a system with multiple
117 local users, this sets the umask such that only the owner of the
118 resulting file can read or write it.
119
120 :param token_response: The token data received from the refresh
121 """
122 to_write = self._load()
123
124 # copy the data from the by_resource_server attribute
125 #
126 # if the file did not exist and we're handling the initial token response, this
127 # is a full copy of all of the token data
128 #
129 # if the file already exists and we're handling a token refresh, we only modify
130 # newly received tokens
131 to_write["by_rs"].update(token_response.by_resource_server)
132
133 # deny rwx to Group and World, exec to User
134 with self.user_only_umask():
135 with open(self.filename, "w", encoding="utf-8") as f:
136 json.dump(to_write, f)
137
138 def get_by_resource_server(self) -> dict[str, t.Any]:
139 """
140 Read only the by_resource_server formatted data from the file, discarding any
141 other keys.
142
143 This returns a dict in the same format as
144 ``OAuthTokenResponse.by_resource_server``
145 """
146 return self._load()["by_rs"]
147
148 def get_token_data(self, resource_server: str) -> dict[str, t.Any] | None:
149 return self.get_by_resource_server().get(resource_server)