| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
import pathlib |
| 5 |
import sqlite3 |
| 6 |
import typing as t |
| 7 |
|
| 8 |
import globus_sdk |
| 9 |
from globus_sdk import __version__ |
| 10 |
|
| 11 |
from .base import FileAdapter |
| 12 |
|
| 13 |
|
| 14 |
class SQLiteAdapter(FileAdapter): |
| 15 |
""" |
| 16 |
:param dbname: The name of the DB file to write to and read from. If the string |
| 17 |
":memory:" is used, an in-memory database will be used instead. |
| 18 |
:param namespace: A "namespace" to use within the database. All operations will |
| 19 |
be performed indexed under this string, so that multiple distinct sets of tokens |
| 20 |
may be stored in the database. You might use usernames as the namespace to |
| 21 |
implement a multi-user system, or profile names to allow multiple Globus |
| 22 |
accounts to be used by a single user. |
| 23 |
:param connect_params: A pass-through dictionary for fine-tuning the SQLite |
| 24 |
connection. |
| 25 |
|
| 26 |
A storage adapter for storing tokens in sqlite databases. |
| 27 |
|
| 28 |
SQLite adapters are for more complex cases, where there may be multiple users or |
| 29 |
"profiles" in play, and additionally a dynamic set of resource servers which need to |
| 30 |
be stored in an extensible way. |
| 31 |
|
| 32 |
The ``namespace`` is a user-supplied way of partitioning data, and any token |
| 33 |
responses passed to the storage adapter are broken apart and stored indexed by |
| 34 |
*resource_server*. If you have a more complex use-case in which this scheme will be |
| 35 |
insufficient, you should encode that in your choice of ``namespace`` values. |
| 36 |
|
| 37 |
The ``connect_params`` is an optional dictionary whose elements are passed directly |
| 38 |
to the underlying ``sqlite3.connect()`` method, enabling developers to fine-tune the |
| 39 |
connection to the SQLite database. Refer to the ``sqlite3.connect()`` |
| 40 |
documentation for SQLite-specific parameters. |
| 41 |
""" |
| 42 |
|
| 43 |
def __init__( |
| 44 |
self, |
| 45 |
dbname: pathlib.Path | str, |
| 46 |
*, |
| 47 |
namespace: str = "DEFAULT", |
| 48 |
connect_params: dict[str, t.Any] | None = None, |
| 49 |
) -> None: |
| 50 |
self.filename = self.dbname = str(dbname) |
| 51 |
self.namespace = namespace |
| 52 |
self._connection = self._init_and_connect(connect_params) |
| 53 |
|
| 54 |
def _is_memory_db(self) -> bool: |
| 55 |
return self.dbname == ":memory:" |
| 56 |
|
| 57 |
def _init_and_connect( |
| 58 |
self, |
| 59 |
connect_params: dict[str, t.Any] | None, |
| 60 |
) -> sqlite3.Connection: |
| 61 |
init_tables = self._is_memory_db() or not self.file_exists() |
| 62 |
connect_params = connect_params or {} |
| 63 |
if init_tables and not self._is_memory_db(): # real file needs to be created |
| 64 |
with self.user_only_umask(): |
| 65 |
conn: sqlite3.Connection = sqlite3.connect( |
| 66 |
self.dbname, **connect_params |
| 67 |
) |
| 68 |
else: |
| 69 |
conn = sqlite3.connect(self.dbname, **connect_params) |
| 70 |
if init_tables: |
| 71 |
conn.executescript(""" |
| 72 |
CREATE TABLE config_storage ( |
| 73 |
namespace VARCHAR NOT NULL, |
| 74 |
config_name VARCHAR NOT NULL, |
| 75 |
config_data_json VARCHAR NOT NULL, |
| 76 |
PRIMARY KEY (namespace, config_name) |
| 77 |
); |
| 78 |
CREATE TABLE token_storage ( |
| 79 |
namespace VARCHAR NOT NULL, |
| 80 |
resource_server VARCHAR NOT NULL, |
| 81 |
token_data_json VARCHAR NOT NULL, |
| 82 |
PRIMARY KEY (namespace, resource_server) |
| 83 |
); |
| 84 |
CREATE TABLE sdk_storage_adapter_internal ( |
| 85 |
attribute VARCHAR NOT NULL, |
| 86 |
value VARCHAR NOT NULL, |
| 87 |
PRIMARY KEY (attribute) |
| 88 |
); |
| 89 |
""") |
| 90 |
# mark the version which was used to create the DB |
| 91 |
# also mark the "database schema version" in case we ever need to handle |
| 92 |
# graceful upgrades |
| 93 |
conn.executemany( |
| 94 |
"INSERT INTO sdk_storage_adapter_internal(attribute, value) " |
| 95 |
"VALUES (?, ?)", |
| 96 |
[ |
| 97 |
("globus-sdk.version", __version__), |
| 98 |
("globus-sdk.database_schema_version", "1"), |
| 99 |
], |
| 100 |
) |
| 101 |
conn.commit() |
| 102 |
return conn |
| 103 |
|
| 104 |
def close(self) -> None: |
| 105 |
""" |
| 106 |
Close the underlying database connection. |
| 107 |
""" |
| 108 |
self._connection.close() |
| 109 |
|
| 110 |
def store_config( |
| 111 |
self, config_name: str, config_dict: t.Mapping[str, t.Any] |
| 112 |
) -> None: |
| 113 |
""" |
| 114 |
:param config_name: A string name for the configuration value |
| 115 |
:param config_dict: A dict of config which will be stored serialized as JSON |
| 116 |
|
| 117 |
Store a config dict under the current namespace in the config table. |
| 118 |
Allows arbitrary configuration data to be namespaced under the namespace, so |
| 119 |
that application config may be associated with the stored tokens. |
| 120 |
|
| 121 |
Uses sqlite "REPLACE" to perform the operation. |
| 122 |
""" |
| 123 |
self._connection.execute( |
| 124 |
"REPLACE INTO config_storage(namespace, config_name, config_data_json) " |
| 125 |
"VALUES (?, ?, ?)", |
| 126 |
(self.namespace, config_name, json.dumps(config_dict)), |
| 127 |
) |
| 128 |
self._connection.commit() |
| 129 |
|
| 130 |
def read_config(self, config_name: str) -> dict[str, t.Any] | None: |
| 131 |
""" |
| 132 |
:param config_name: A string name for the configuration value |
| 133 |
|
| 134 |
Load a config dict under the current namespace in the config table. |
| 135 |
If no value is found, returns None |
| 136 |
""" |
| 137 |
row = self._connection.execute( |
| 138 |
"SELECT config_data_json FROM config_storage " |
| 139 |
"WHERE namespace=? AND config_name=?", |
| 140 |
(self.namespace, config_name), |
| 141 |
).fetchone() |
| 142 |
|
| 143 |
if row is None: |
| 144 |
return None |
| 145 |
config_data_json = row[0] |
| 146 |
val = json.loads(config_data_json) |
| 147 |
if not isinstance(val, dict): |
| 148 |
raise ValueError("reading config data and got non-dict result") |
| 149 |
return val |
| 150 |
|
| 151 |
def remove_config(self, config_name: str) -> bool: |
| 152 |
""" |
| 153 |
:param config_name: A string name for the configuration value |
| 154 |
|
| 155 |
Delete a previously stored configuration value. |
| 156 |
|
| 157 |
Returns True if data was deleted, False if none was found to delete. |
| 158 |
""" |
| 159 |
rowcount = self._connection.execute( |
| 160 |
"DELETE FROM config_storage WHERE namespace=? AND config_name=?", |
| 161 |
(self.namespace, config_name), |
| 162 |
).rowcount |
| 163 |
self._connection.commit() |
| 164 |
return rowcount != 0 |
| 165 |
|
| 166 |
def store(self, token_response: globus_sdk.OAuthTokenResponse) -> None: |
| 167 |
""" |
| 168 |
:param token_response: a globus_sdk.OAuthTokenResponse object containing token |
| 169 |
data to store |
| 170 |
|
| 171 |
By default, ``self.on_refresh`` is just an alias for this function. |
| 172 |
|
| 173 |
Given a token response, extract the token data for the resource servers and |
| 174 |
write it to ``self.dbname``, stored under the adapter's namespace |
| 175 |
""" |
| 176 |
pairs = [] |
| 177 |
for rs_name, token_data in token_response.by_resource_server.items(): |
| 178 |
pairs.append((rs_name, token_data)) |
| 179 |
|
| 180 |
self._connection.executemany( |
| 181 |
"REPLACE INTO token_storage(namespace, resource_server, token_data_json) " |
| 182 |
"VALUES(?, ?, ?)", |
| 183 |
[ |
| 184 |
(self.namespace, rs_name, json.dumps(token_data)) |
| 185 |
for (rs_name, token_data) in pairs |
| 186 |
], |
| 187 |
) |
| 188 |
self._connection.commit() |
| 189 |
|
| 190 |
def get_token_data(self, resource_server: str) -> dict[str, t.Any] | None: |
| 191 |
""" |
| 192 |
Load the token data JSON for a specific resource server. |
| 193 |
|
| 194 |
In the event that the server cannot be found in the DB, return None. |
| 195 |
|
| 196 |
:param resource_server: The name of a resource server to lookup in the DB, as |
| 197 |
one would use as a key in OAuthTokenResponse.by_resource_server |
| 198 |
""" |
| 199 |
for row in self._connection.execute( |
| 200 |
"SELECT token_data_json FROM token_storage " |
| 201 |
"WHERE namespace=? AND resource_server=?", |
| 202 |
(self.namespace, resource_server), |
| 203 |
): |
| 204 |
(token_data_json,) = row |
| 205 |
val = json.loads(token_data_json) |
| 206 |
if not isinstance(val, dict): |
| 207 |
raise ValueError("data error: token data was not saved as a dict") |
| 208 |
return val |
| 209 |
return None |
| 210 |
|
| 211 |
def get_by_resource_server(self) -> dict[str, t.Any]: |
| 212 |
""" |
| 213 |
Load the token data JSON and return the resulting dict objects, indexed by |
| 214 |
resource server. |
| 215 |
|
| 216 |
This should look identical to an OAuthTokenResponse.by_resource_server in format |
| 217 |
and content. (But it is not attached to a token response object.) |
| 218 |
""" |
| 219 |
data = {} |
| 220 |
for row in self._connection.execute( |
| 221 |
"SELECT resource_server, token_data_json " |
| 222 |
"FROM token_storage WHERE namespace=?", |
| 223 |
(self.namespace,), |
| 224 |
): |
| 225 |
resource_server, token_data_json = row |
| 226 |
data[resource_server] = json.loads(token_data_json) |
| 227 |
return data |
| 228 |
|
| 229 |
def remove_tokens_for_resource_server(self, resource_server: str) -> bool: |
| 230 |
""" |
| 231 |
Given a resource server to target, delete tokens for that resource server from |
| 232 |
the database (limited to the current namespace). |
| 233 |
You can use this as part of a logout command implementation, loading token data |
| 234 |
as a dict, and then deleting the data for each resource server. |
| 235 |
|
| 236 |
Returns True if token data was deleted, False if none was found to delete. |
| 237 |
|
| 238 |
:param resource_server: The name of the resource server to remove from the DB, |
| 239 |
as one would use as a key in OAuthTokenResponse.by_resource_server |
| 240 |
""" |
| 241 |
rowcount = self._connection.execute( |
| 242 |
"DELETE FROM token_storage WHERE namespace=? AND resource_server=?", |
| 243 |
(self.namespace, resource_server), |
| 244 |
).rowcount |
| 245 |
self._connection.commit() |
| 246 |
return rowcount != 0 |
| 247 |
|
| 248 |
def iter_namespaces( |
| 249 |
self, *, include_config_namespaces: bool = False |
| 250 |
) -> t.Iterator[str]: |
| 251 |
""" |
| 252 |
Iterate over the namespaces which are in use in this storage adapter's database. |
| 253 |
The presence of tokens for a namespace does not indicate that those tokens are |
| 254 |
valid, only that they have been stored and have not been removed. |
| 255 |
|
| 256 |
:param include_config_namespaces: Include namespaces which appear only in the |
| 257 |
configuration storage section of the sqlite database. By default, only |
| 258 |
namespaces which were used for token storage will be returned |
| 259 |
""" |
| 260 |
seen: set[str] = set() |
| 261 |
for row in self._connection.execute( |
| 262 |
"SELECT DISTINCT namespace FROM token_storage;" |
| 263 |
): |
| 264 |
namespace = row[0] |
| 265 |
seen.add(namespace) |
| 266 |
yield namespace |
| 267 |
|
| 268 |
if include_config_namespaces: |
| 269 |
for row in self._connection.execute( |
| 270 |
"SELECT DISTINCT namespace FROM config_storage;" |
| 271 |
): |
| 272 |
namespace = row[0] |
| 273 |
if namespace not in seen: |
| 274 |
yield namespace |