| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
import pathlib |
| 5 |
import sqlite3 |
| 6 |
import textwrap |
| 7 |
import typing as t |
| 8 |
|
| 9 |
from globus_sdk import __version__, exc |
| 10 |
|
| 11 |
from .base import FileTokenStorage |
| 12 |
from .token_data import TokenStorageData |
| 13 |
|
| 14 |
|
| 15 |
class SQLiteTokenStorage(FileTokenStorage): |
| 16 |
""" |
| 17 |
A token storage which stores token data on disk in a SQLite database. |
| 18 |
|
| 19 |
See :class:`TokenStorage` for common interface details. |
| 20 |
|
| 21 |
:param filepath: The path on disk to a SQLite database file. |
| 22 |
:param connect_params: A dictionary of parameters to pass to ``sqlite3.connect()``. |
| 23 |
:param namespace: A unique string for partitioning token data (Default: "DEFAULT"). |
| 24 |
|
| 25 |
:raises GlobusSDKUsageError: If the filepath is ":memory:". This usage-mode is not |
| 26 |
supported in this class; use :class:`MemoryTokenStorage` instead if in-memory |
| 27 |
token storage is desired. |
| 28 |
""" |
| 29 |
|
| 30 |
file_format = "db" |
| 31 |
|
| 32 |
def __init__( |
| 33 |
self, |
| 34 |
filepath: pathlib.Path | str, |
| 35 |
*, |
| 36 |
connect_params: dict[str, t.Any] | None = None, |
| 37 |
namespace: str = "DEFAULT", |
| 38 |
) -> None: |
| 39 |
if filepath == ":memory:": |
| 40 |
raise exc.GlobusSDKUsageError( |
| 41 |
"SQLiteTokenStorage cannot be used with a ':memory:' database. " |
| 42 |
"If you want to store tokens in memory, use MemoryTokenStorage instead." |
| 43 |
) |
| 44 |
|
| 45 |
super().__init__(filepath, namespace=namespace) |
| 46 |
self._connection = self._init_and_connect(connect_params) |
| 47 |
|
| 48 |
def _init_and_connect( |
| 49 |
self, |
| 50 |
connect_params: dict[str, t.Any] | None, |
| 51 |
) -> sqlite3.Connection: |
| 52 |
connect_params = connect_params or {} |
| 53 |
if not self.file_exists(): |
| 54 |
with self.user_only_umask(): |
| 55 |
conn: sqlite3.Connection = sqlite3.connect( |
| 56 |
self.filepath, **connect_params |
| 57 |
) |
| 58 |
conn.executescript(textwrap.dedent(""" |
| 59 |
CREATE TABLE token_storage ( |
| 60 |
namespace VARCHAR NOT NULL, |
| 61 |
resource_server VARCHAR NOT NULL, |
| 62 |
token_data_json VARCHAR NOT NULL, |
| 63 |
PRIMARY KEY (namespace, resource_server) |
| 64 |
); |
| 65 |
CREATE TABLE sdk_storage_adapter_internal ( |
| 66 |
attribute VARCHAR NOT NULL, |
| 67 |
value VARCHAR NOT NULL, |
| 68 |
PRIMARY KEY (attribute) |
| 69 |
); |
| 70 |
""")) |
| 71 |
# mark the version which was used to create the DB |
| 72 |
# also mark the "database schema version" in case we ever need to handle |
| 73 |
# graceful upgrades |
| 74 |
conn.executemany( |
| 75 |
"INSERT INTO sdk_storage_adapter_internal(attribute, value) " |
| 76 |
"VALUES (?, ?)", |
| 77 |
[ |
| 78 |
("globus-sdk.version", __version__), |
| 79 |
# schema_version=1 indicates a schema built with the original |
| 80 |
# SQLiteAdapter |
| 81 |
# schema_version=2 indicates one built with SQLiteTokenStorage |
| 82 |
# |
| 83 |
# a schema_version of 1 therefore indicates that there should be |
| 84 |
# a 'config_storage' table present |
| 85 |
("globus-sdk.database_schema_version", "2"), |
| 86 |
], |
| 87 |
) |
| 88 |
conn.commit() |
| 89 |
else: |
| 90 |
conn = sqlite3.connect(self.filepath, **connect_params) |
| 91 |
return conn |
| 92 |
|
| 93 |
def close(self) -> None: |
| 94 |
""" |
| 95 |
Close the underlying database connection. |
| 96 |
""" |
| 97 |
self._connection.close() |
| 98 |
|
| 99 |
def store_token_data_by_resource_server( |
| 100 |
self, token_data_by_resource_server: t.Mapping[str, TokenStorageData] |
| 101 |
) -> None: |
| 102 |
""" |
| 103 |
Store token data for one or more resource servers in the current namespace. |
| 104 |
|
| 105 |
Token data is JSON-serialized before being inserted into the database. |
| 106 |
|
| 107 |
:param token_data_by_resource_server: A mapping of resource servers to token |
| 108 |
data. |
| 109 |
""" |
| 110 |
pairs = [] |
| 111 |
for resource_server, token_data in token_data_by_resource_server.items(): |
| 112 |
pairs.append((resource_server, token_data.to_dict())) |
| 113 |
|
| 114 |
self._connection.executemany( |
| 115 |
"REPLACE INTO token_storage(namespace, resource_server, token_data_json) " |
| 116 |
"VALUES(?, ?, ?)", |
| 117 |
[ |
| 118 |
(self.namespace, rs_name, json.dumps(token_data_dict)) |
| 119 |
for (rs_name, token_data_dict) in pairs |
| 120 |
], |
| 121 |
) |
| 122 |
self._connection.commit() |
| 123 |
|
| 124 |
def get_token_data_by_resource_server(self) -> dict[str, TokenStorageData]: |
| 125 |
""" |
| 126 |
Lookup all token data under the current namespace from the database. |
| 127 |
|
| 128 |
:returns: A dict of ``TokenStorageData`` objects indexed by their |
| 129 |
resource server. |
| 130 |
""" |
| 131 |
ret: dict[str, TokenStorageData] = {} |
| 132 |
for row in self._connection.execute( |
| 133 |
"SELECT resource_server, token_data_json " |
| 134 |
"FROM token_storage WHERE namespace=?", |
| 135 |
(self.namespace,), |
| 136 |
): |
| 137 |
resource_server, token_data_json = row |
| 138 |
token_data_dict = json.loads(token_data_json) |
| 139 |
ret[resource_server] = TokenStorageData.from_dict(token_data_dict) |
| 140 |
return ret |
| 141 |
|
| 142 |
def remove_token_data(self, resource_server: str) -> bool: |
| 143 |
""" |
| 144 |
Given a resource server to target, delete token data for that resource server |
| 145 |
from the database (limited to the current namespace). |
| 146 |
You can use this as part of a logout command implementation, loading token data |
| 147 |
as a dict, and then deleting the data for each resource server. |
| 148 |
|
| 149 |
:param resource_server: The name of the resource server to remove from the DB |
| 150 |
:returns: True if token data was deleted, False if none was found to delete. |
| 151 |
""" |
| 152 |
rowcount = self._connection.execute( |
| 153 |
"DELETE FROM token_storage WHERE namespace=? AND resource_server=?", |
| 154 |
(self.namespace, resource_server), |
| 155 |
).rowcount |
| 156 |
self._connection.commit() |
| 157 |
return rowcount != 0 |
| 158 |
|
| 159 |
def iter_namespaces(self) -> t.Iterator[str]: |
| 160 |
"""Iterate over all distinct namespaces in the SQLite database.""" |
| 161 |
seen: set[str] = set() |
| 162 |
for row in self._connection.execute( |
| 163 |
"SELECT DISTINCT namespace FROM token_storage;" |
| 164 |
): |
| 165 |
namespace = row[0] |
| 166 |
seen.add(namespace) |
| 167 |
yield namespace |