| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import abc |
| 4 |
import contextlib |
| 5 |
import os |
| 6 |
import pathlib |
| 7 |
import re |
| 8 |
import sys |
| 9 |
import typing as t |
| 10 |
import uuid |
| 11 |
|
| 12 |
import globus_sdk |
| 13 |
|
| 14 |
from .token_data import TokenStorageData |
| 15 |
|
| 16 |
if t.TYPE_CHECKING: |
| 17 |
from globus_sdk.globus_app import GlobusAppConfig |
| 18 |
|
| 19 |
|
| 20 |
class TokenStorage(metaclass=abc.ABCMeta): |
| 21 |
""" |
| 22 |
The interface for interacting with a store of :class:`TokenStorageData` objects. |
| 23 |
|
| 24 |
Implementations must partition their token data objects by ``namespace``. |
| 25 |
Within a namespace, token data must be indexed by ``resource_server``. |
| 26 |
|
| 27 |
:param namespace: A unique string for partitioning token data (Default: "DEFAULT"). |
| 28 |
|
| 29 |
:ivar globus_sdk.IDTokenDecoder | None id_token_decoder: A decoder to use |
| 30 |
when decoding ``id_token`` JWTs from Globus Auth. By default, a new decoder |
| 31 |
is used each time decoding is performed. |
| 32 |
""" |
| 33 |
|
| 34 |
def __init__(self, namespace: str = "DEFAULT") -> None: |
| 35 |
self.namespace = namespace |
| 36 |
self.id_token_decoder: globus_sdk.IDTokenDecoder | None = None |
| 37 |
|
| 38 |
@abc.abstractmethod |
| 39 |
def store_token_data_by_resource_server( |
| 40 |
self, token_data_by_resource_server: t.Mapping[str, TokenStorageData] |
| 41 |
) -> None: |
| 42 |
""" |
| 43 |
Store token data for one or more resource server in the current namespace. |
| 44 |
|
| 45 |
:param token_data_by_resource_server: mapping of resource server to token data. |
| 46 |
""" |
| 47 |
|
| 48 |
@abc.abstractmethod |
| 49 |
def get_token_data_by_resource_server(self) -> dict[str, TokenStorageData]: |
| 50 |
""" |
| 51 |
Retrieve all token data stored in the current namespace. |
| 52 |
|
| 53 |
:returns: a dict of ``TokenStorageData`` objects indexed by their |
| 54 |
resource server. |
| 55 |
""" |
| 56 |
|
| 57 |
def get_token_data(self, resource_server: str) -> TokenStorageData | None: |
| 58 |
""" |
| 59 |
Retrieve token data for a particular resource server in the current namespace. |
| 60 |
|
| 61 |
:param resource_server: The resource_server string to get token data for. |
| 62 |
:returns: token data if found or else None. |
| 63 |
""" |
| 64 |
return self.get_token_data_by_resource_server().get(resource_server) |
| 65 |
|
| 66 |
@abc.abstractmethod |
| 67 |
def remove_token_data(self, resource_server: str) -> bool: |
| 68 |
""" |
| 69 |
Remove token data for a resource server in the current namespace. |
| 70 |
|
| 71 |
:param resource_server: The resource server string to remove token data for. |
| 72 |
:returns: True if token data was deleted, False if none was found to delete. |
| 73 |
""" |
| 74 |
|
| 75 |
def store_token_response( |
| 76 |
self, token_response: globus_sdk.OAuthTokenResponse |
| 77 |
) -> None: |
| 78 |
""" |
| 79 |
Store token data from an :class:`OAuthTokenResponse` in the current namespace. |
| 80 |
|
| 81 |
:param token_response: A token response object from an authentication flow. |
| 82 |
""" |
| 83 |
token_data_by_resource_server = {} |
| 84 |
|
| 85 |
identity_id = self._extract_identity_id(token_response) |
| 86 |
|
| 87 |
for resource_server, token_dict in token_response.by_resource_server.items(): |
| 88 |
token_data_by_resource_server[resource_server] = TokenStorageData( |
| 89 |
resource_server=token_dict["resource_server"], |
| 90 |
identity_id=identity_id, |
| 91 |
scope=token_dict["scope"], |
| 92 |
access_token=token_dict["access_token"], |
| 93 |
refresh_token=token_dict.get("refresh_token"), |
| 94 |
expires_at_seconds=token_dict["expires_at_seconds"], |
| 95 |
token_type=token_dict.get("token_type"), |
| 96 |
) |
| 97 |
self.store_token_data_by_resource_server(token_data_by_resource_server) |
| 98 |
|
| 99 |
def _extract_identity_id( |
| 100 |
self, token_response: globus_sdk.OAuthTokenResponse |
| 101 |
) -> str | None: |
| 102 |
""" |
| 103 |
Get identity_id from id_token if available. |
| 104 |
|
| 105 |
.. note:: |
| 106 |
|
| 107 |
This method is private, but is used in ValidatingTokenStorage to |
| 108 |
override the extraction of ``identity_id`` information. |
| 109 |
|
| 110 |
Generalizing customization of ``identity_id`` extraction will require |
| 111 |
implementation of a user-facing mechanism for controlling calls to |
| 112 |
``decode_id_token()``. |
| 113 |
""" |
| 114 |
# dependent token responses cannot contain an `id_token` field, as the |
| 115 |
# top-level data is an array |
| 116 |
if isinstance(token_response, globus_sdk.OAuthDependentTokenResponse): |
| 117 |
return None |
| 118 |
|
| 119 |
if id_token := token_response.get("id_token"): |
| 120 |
if self.id_token_decoder: |
| 121 |
decoded_id_token = self.id_token_decoder.decode(id_token) |
| 122 |
else: |
| 123 |
decoded_id_token = token_response.decode_id_token() |
| 124 |
return decoded_id_token["sub"] # type: ignore[no-any-return] |
| 125 |
else: |
| 126 |
return None |
| 127 |
|
| 128 |
def close(self) -> None: # noqa: B027 |
| 129 |
""" |
| 130 |
Close any resources associated with this token storage. |
| 131 |
|
| 132 |
By default, this does nothing, but subclasses may override it. |
| 133 |
""" |
| 134 |
|
| 135 |
|
| 136 |
class FileTokenStorage(TokenStorage, metaclass=abc.ABCMeta): |
| 137 |
""" |
| 138 |
A base class for token storages which store tokens in a local file. |
| 139 |
|
| 140 |
Common functionality for file-based token storages like file creation and class |
| 141 |
instantiation for a GlobusApp is defined here. |
| 142 |
|
| 143 |
:cvar file_format: The file format suffix associated with files of this type. This |
| 144 |
is used when constructing the file path for a GlobusApp. |
| 145 |
|
| 146 |
:param filepath: The path to a file where token data should be stored. |
| 147 |
:param namespace: A unique string for partitioning token data (Default: "DEFAULT"). |
| 148 |
""" |
| 149 |
|
| 150 |
# File suffix associated with files of this type (e.g., "csv") |
| 151 |
file_format: str = "_UNSET_" # must be overridden by subclasses |
| 152 |
|
| 153 |
def __init__( |
| 154 |
self, filepath: pathlib.Path | str, *, namespace: str = "DEFAULT" |
| 155 |
) -> None: |
| 156 |
""" |
| 157 |
:param filepath: the name of the file to write to and read from |
| 158 |
:param namespace: A user-supplied namespace for partitioning token data |
| 159 |
""" |
| 160 |
self.filepath = str(filepath) |
| 161 |
try: |
| 162 |
self._ensure_containing_dir_exists() |
| 163 |
except OSError as e: |
| 164 |
msg = ( |
| 165 |
"Encountered an error while initializing the token storage file " |
| 166 |
f"'{self.filepath}'" |
| 167 |
) |
| 168 |
raise ValueError(msg) from e |
| 169 |
super().__init__(namespace=namespace) |
| 170 |
|
| 171 |
def __init_subclass__(cls, **kwargs: t.Any): |
| 172 |
if cls.file_format == "_UNSET_": |
| 173 |
raise TypeError(f"{cls.__name__} must set a 'file_format' class attribute") |
| 174 |
|
| 175 |
@classmethod |
| 176 |
def for_globus_app( |
| 177 |
cls, |
| 178 |
client_id: uuid.UUID | str, |
| 179 |
app_name: str, |
| 180 |
config: GlobusAppConfig, |
| 181 |
namespace: str, |
| 182 |
) -> TokenStorage: |
| 183 |
""" |
| 184 |
Initialize a TokenStorage instance for a GlobusApp, using the supplied |
| 185 |
info to determine the file location. |
| 186 |
|
| 187 |
:param client_id: The client ID of the Globus App. |
| 188 |
:param app_name: The name of the Globus App. |
| 189 |
:param config: The GlobusAppConfig object for the Globus App. |
| 190 |
:param namespace: A user-supplied namespace for partitioning token data. |
| 191 |
""" |
| 192 |
filepath = _default_globus_app_filepath(client_id, app_name, config.environment) |
| 193 |
return cls(filepath=f"{filepath}.{cls.file_format}", namespace=namespace) |
| 194 |
|
| 195 |
def _ensure_containing_dir_exists(self) -> None: |
| 196 |
""" |
| 197 |
Ensure that the directory containing the given filepath exists. |
| 198 |
""" |
| 199 |
os.makedirs(os.path.dirname(self.filepath), exist_ok=True) |
| 200 |
|
| 201 |
def file_exists(self) -> bool: |
| 202 |
""" |
| 203 |
Check if the file used by this file storage adapter exists. |
| 204 |
""" |
| 205 |
return os.path.exists(self.filepath) |
| 206 |
|
| 207 |
@contextlib.contextmanager |
| 208 |
def user_only_umask(self) -> t.Iterator[None]: |
| 209 |
""" |
| 210 |
A context manager to deny rwx to Group and World, x to User |
| 211 |
|
| 212 |
This does not create a file, but ensures that if a file is created while in the |
| 213 |
context manager, its permissions will be correct on unix systems. |
| 214 |
|
| 215 |
.. note:: |
| 216 |
|
| 217 |
On Windows, this has no effect. To control the permissions on files used for |
| 218 |
token storage, use ``%LOCALAPPDATA%`` or ``%APPDATA%``. |
| 219 |
These directories should only be accessible to the current user. |
| 220 |
""" |
| 221 |
old_umask = os.umask(0o177) |
| 222 |
try: |
| 223 |
yield |
| 224 |
finally: |
| 225 |
os.umask(old_umask) |
| 226 |
|
| 227 |
|
| 228 |
def _default_globus_app_filepath( |
| 229 |
client_id: uuid.UUID | str, app_name: str, environment: str |
| 230 |
) -> str: |
| 231 |
r""" |
| 232 |
Construct a default TokenStorage filepath for a GlobusApp. |
| 233 |
For flexibility, the filepath will omit the file format suffix. |
| 234 |
|
| 235 |
On Windows, this will be: |
| 236 |
``~\AppData\Local\globus\app\{client_id}\{app_name}\tokens`` |
| 237 |
|
| 238 |
On Linux and macOS, we use: |
| 239 |
``~/.globus/app/{client_id}/{app_name}/tokens`` |
| 240 |
""" |
| 241 |
environment_prefix = f"{environment}-" |
| 242 |
if environment == "production": |
| 243 |
environment_prefix = "" |
| 244 |
filename = f"{environment_prefix}tokens" |
| 245 |
app_name = _slugify_app_name(app_name) |
| 246 |
|
| 247 |
if sys.platform == "win32": |
| 248 |
# try to get the app data dir, preferring the local appdata |
| 249 |
datadir = os.getenv("LOCALAPPDATA", os.getenv("APPDATA")) |
| 250 |
if not datadir: |
| 251 |
home = os.path.expanduser("~") |
| 252 |
datadir = os.path.join(home, "AppData", "Local") |
| 253 |
return os.path.join( |
| 254 |
datadir, "globus", "app", str(client_id), app_name, filename |
| 255 |
) |
| 256 |
else: |
| 257 |
return os.path.expanduser( |
| 258 |
f"~/.globus/app/{str(client_id)}/{app_name}/{filename}" |
| 259 |
) |
| 260 |
|
| 261 |
|
| 262 |
# https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions |
| 263 |
_RESERVED_FS_CHARS = re.compile(r'[<>:"/\\|?*]') |
| 264 |
# https://stackoverflow.com/a/31976060 |
| 265 |
_RESERVED_FS_NAMES = re.compile(r"con|prn|aux|nul|com\d|lpt\d") |
| 266 |
|
| 267 |
|
| 268 |
def _slugify_app_name(app_name: str) -> str: |
| 269 |
""" |
| 270 |
Slugify a globus app name for use in a file path. |
| 271 |
|
| 272 |
* Reserved filesystem characters are replaced with a '+'. ('a?' -> 'a+') |
| 273 |
* Periods and Spaces are replaced with a '-'. ('a. b' -> 'a--b') |
| 274 |
* Control characters are removed. ('a\0b' -> 'ab') |
| 275 |
* The string is lowercased. ('AB' -> 'ab') |
| 276 |
|
| 277 |
:raises: GlobusSDKUsageError if the app name is empty after slugification. |
| 278 |
:raises: GlobusSDKUsageError if the app name is a reserved filesystem name (after |
| 279 |
slugification). |
| 280 |
""" |
| 281 |
app_name = _RESERVED_FS_CHARS.sub("+", app_name) |
| 282 |
app_name = app_name.replace(".", "-").replace(" ", "-") |
| 283 |
app_name = "".join(c for c in app_name if c.isprintable()) |
| 284 |
app_name = app_name.lower() |
| 285 |
|
| 286 |
if _RESERVED_FS_NAMES.fullmatch(app_name): |
| 287 |
msg = ( |
| 288 |
f'App name results in a reserved filename ("{app_name}"). ' |
| 289 |
"Please choose a different name." |
| 290 |
) |
| 291 |
raise globus_sdk.GlobusSDKUsageError(msg) |
| 292 |
|
| 293 |
if not app_name: |
| 294 |
msg = "App name results in the empty string. Please choose a different name." |
| 295 |
raise globus_sdk.GlobusSDKUsageError(msg) |
| 296 |
|
| 297 |
return app_name |