Debian Codegraph @

src/globus_sdk/token_storage/json.py

raw
1 from __future__ import annotations
2
3 import json
4 import typing as t
5
6 from globus_sdk import __version__
7
8 from .base import FileTokenStorage
9 from .token_data import TokenStorageData
10
11 # use the non-annotation form of TypedDict to apply a non-identifier key
12 _JSONFileData_0 = t.TypedDict("_JSONFileData_0", {"globus-sdk.version": str})
13
14
15 # then inherit from that TypedDict to build the "real" TypedDict with the advantages of
16 # the annotation-based syntax
17 class _JSONFileData(_JSONFileData_0): # pylint: disable=inherit-non-class
18 data: dict[str, dict[str, t.Any]]
19 format_version: str
20
21
22 class JSONTokenStorage(FileTokenStorage):
23 """
24 A token storage which stores token data on disk in a JSON file.
25
26 This class defines a `format_version` which determines what the specific data shape.
27 Any data in a `supported_version` format which is not the primary `format_version`
28 will be automatically rewritten.
29
30 See :class:`TokenStorage` for common interface details.
31
32 :cvar "2.0" format_version: The data format version used when writing data.
33 :cvar ("1.0", "2.0") supported_versions: The list of data format versions which can
34 be read.
35 :param filepath: The path to a JSON file where token data should be stored.
36 :param namespace: A unique string for partitioning token data (Default: "DEFAULT").
37 """
38
39 format_version = "2.0"
40 supported_versions = ("1.0", "2.0")
41 file_format = "json"
42
43 def _invalid(self, msg: str) -> t.NoReturn:
44 raise ValueError(
45 f"{msg} while loading from '{self.filepath}' for JSON Token Storage"
46 )
47
48 def _raw_load(self) -> dict[str, t.Any]:
49 """
50 Load the file contents as JSON and return the resulting dict
51 object. If a dict is not found, raises an error.
52 """
53 with open(self.filepath, encoding="utf-8") as f:
54 val = json.load(f)
55 if not isinstance(val, dict):
56 self._invalid("Found non-dict root data")
57 return val
58
59 def _handle_formats(self, read_data: dict[str, t.Any]) -> _JSONFileData:
60 """Handle older data formats supported by this class
61
62 if the data is not in a known/recognized format, this will error
63 otherwise, reshape the data to the current supported format and return it
64 """
65 format_version = read_data.get("format_version")
66 if format_version not in self.supported_versions:
67 raise ValueError(
68 f"cannot store data using SimpleJSONTokenStorage({self.filepath}) "
69 "existing data file is in an unknown format "
70 f"(format_version={format_version})"
71 )
72
73 # 1.0 data was stored under a "by_rs" key without namespaces, to upgrade we
74 # move everything under the "DEFAULT" key and remove the "by_rs" key.
75 if format_version == "1.0":
76 if "by_rs" not in read_data:
77 self._invalid("Invalid v1.0 data (missing 'by_rs')")
78 read_data = {
79 "data": {
80 "DEFAULT": read_data["by_rs"],
81 },
82 "format_version": self.format_version,
83 "globus-sdk.version": __version__,
84 }
85
86 if not isinstance(read_data.get("data"), dict):
87 raise ValueError(
88 f"cannot store data using SimpleJSONTokenStorage({self.filepath}) "
89 "existing data file is malformed"
90 )
91 if any(
92 k not in read_data for k in ("data", "format_version", "globus-sdk.version")
93 ):
94 self._invalid("Missing required keys")
95 if not isinstance(data_dict := read_data["data"], dict) or any(
96 not isinstance(k, str) for k in data_dict
97 ):
98 self._invalid("Invalid 'data'")
99 if not isinstance(read_data["format_version"], str):
100 self._invalid("Invalid 'format_version'")
101 if not isinstance(read_data["globus-sdk.version"], str):
102 self._invalid("Invalid 'globus-sdk.version'")
103
104 return read_data # type: ignore[return-value]
105
106 def _load(self) -> _JSONFileData:
107 """
108 Load data from the file and ensure that the data is in a modern format which can
109 be handled by the rest of the adapter.
110
111 If the file is missing, this will return a "skeleton" for new data.
112 """
113 try:
114 data = self._raw_load()
115 except FileNotFoundError:
116 return {
117 "data": {},
118 "format_version": self.format_version,
119 "globus-sdk.version": __version__,
120 }
121 return self._handle_formats(data)
122
123 def store_token_data_by_resource_server(
124 self, token_data_by_resource_server: t.Mapping[str, TokenStorageData]
125 ) -> None:
126 """
127 Store token data for one or more resource server in the current namespace.
128
129 Token data, alongside Globus SDK version info, is serialized to JSON before
130 being written to the file at ``self.filepath``.
131
132 Under the assumption that this may be running on a system with multiple
133 local users, this sets the umask such that only the owner of the
134 resulting file can read or write it.
135
136 :param token_data_by_resource_server: A mapping of resource servers to token
137 data.
138 """
139 to_write = self._load()
140
141 # create the namespace if it does not exist
142 if self.namespace not in to_write["data"]:
143 to_write["data"][self.namespace] = {}
144
145 # add token data by resource server to namespaced data
146 for resource_server, token_data in token_data_by_resource_server.items():
147 to_write["data"][self.namespace][resource_server] = token_data.to_dict()
148
149 # update globus-sdk version
150 to_write["globus-sdk.version"] = __version__
151
152 # write the file, denying rwx to Group and World, exec to User
153 with self.user_only_umask():
154 with open(self.filepath, "w", encoding="utf-8") as f:
155 json.dump(to_write, f)
156
157 def get_token_data_by_resource_server(self) -> dict[str, TokenStorageData]:
158 """
159 Lookup all token data under the current namespace from the JSON file.
160
161 Returns a dict of ``TokenStorageData`` objects indexed by their resource server.
162 """
163 ret = {}
164 dicts_by_resource_server = self._load()["data"].get(self.namespace, {})
165 for resource_server, token_data_dict in dicts_by_resource_server.items():
166 ret[resource_server] = TokenStorageData.from_dict(token_data_dict)
167 return ret
168
169 def remove_token_data(self, resource_server: str) -> bool:
170 """
171 Remove all tokens for a resource server from the JSON data, then overwrite
172 ``self.filepath``.
173
174 Returns True if token data was removed, False if none was found to remove.
175
176 :param resource_server: The resource server string to remove tokens for
177 """
178 to_write = self._load()
179
180 # pop the token data out if it exists
181 popped = to_write["data"].get(self.namespace, {}).pop(resource_server, None)
182
183 # overwrite the file, denying rwx to Group and World, exec to User
184 with self.user_only_umask():
185 with open(self.filepath, "w", encoding="utf-8") as f:
186 json.dump(to_write, f)
187
188 return popped is not None