-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcredential_storage.py
279 lines (233 loc) · 9.74 KB
/
credential_storage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# Copyright Quantinuum
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from abc import ABC, abstractmethod
from datetime import datetime, timedelta, timezone
from typing import Optional
import jwt
from .config import QuantinuumConfig
class CredentialStorage(ABC):
"""Base class for storing Quantinuum username and authentication tokens.
``pytket-quantinuum`` interacts with Quantinuum services by making API requests,
such as submitting quantum programs and retrieving results. These requests
often require an ID token, which is obtained through the Quantinuum login API.
The login process also returns a refresh token, allowing the ID token to be
refreshed without requiring a new login.
``CredentialStorage`` defines the interface for storing and accessing these
credentials, with derived classes providing specific implementations.
"""
def __init__(
self,
id_token_timedelt: timedelta = timedelta(minutes=55),
refresh_token_timedelt: timedelta = timedelta(days=29),
) -> None:
"""
:param id_token_timedelt: The time duration for which the ID token is valid.
Defaults to 55 minutes.
:param refresh_token_timedelt: The time duration for which the refresh token
is valid. Defaults to 29 days.
"""
self._id_timedelt = id_token_timedelt
self._refresh_timedelt = refresh_token_timedelt
@abstractmethod
def save_refresh_token(self, refresh_token: str) -> None:
"""Save refresh token.
:param refresh_token: refresh token.
"""
@abstractmethod
def save_id_token(self, id_token: str) -> None:
"""Save ID token.
:param id_token: ID token.
"""
@abstractmethod
def save_user_name(self, user_name: str) -> None:
"""Save username.
:param user_name: Quantinuum username.
"""
def save_tokens(self, id_token: str, refresh_token: str) -> None:
"""Save ID token and refresh token.
:param id_token: ID token.
:param refresh_token: refresh token.
"""
self.save_id_token(id_token)
self.save_refresh_token(refresh_token)
@abstractmethod
def delete_credential(self) -> None:
"""Delete credential."""
@property
def id_token(self) -> Optional[str]:
"""Return the ID token if valid."""
@property
def refresh_token(self) -> Optional[str]:
"""Return the refresh token if valid."""
@property
def user_name(self) -> Optional[str]:
"""Return the username if exists."""
class MemoryCredentialStorage(CredentialStorage):
"""In-memory credential storage.
This storage option allows credentials to be temporarily stored in memory during
the application's runtime.
"""
def __init__(
self,
id_token_timedelt: timedelta = timedelta(minutes=55),
refresh_token_timedelt: timedelta = timedelta(days=29),
) -> None:
"""Construct a MemoryCredentialStorage instance.
:param id_token_timedelt: The time duration for which the ID token is valid.
Defaults to 55 minutes.
:param refresh_token_timedelt: The time duration for which the refresh token
is valid. Defaults to 29 days.
"""
super().__init__(id_token_timedelt, refresh_token_timedelt)
self._user_name: Optional[str] = None
# Password storage is only included for debug purposes
self._password: Optional[str] = None
self._id_token: Optional[str] = None
self._refresh_token: Optional[str] = None
self._id_token_timeout: Optional[datetime] = None
self._refresh_token_timeout: Optional[datetime] = None
def save_user_name(self, user_name: str) -> None:
self._user_name = user_name
def save_refresh_token(self, refresh_token: str) -> None:
self._refresh_token = refresh_token
self._refresh_token_timeout = (
datetime.now(timezone.utc) + self._refresh_timedelt
)
def save_id_token(self, id_token: str) -> None:
self._id_token = id_token
self._id_token_timeout = datetime.now(timezone.utc) + self._id_timedelt
@property
def id_token(self) -> Optional[str]:
if self._id_token is not None:
timeout = (
jwt.decode(
self._id_token,
algorithms=["HS256"],
options={"verify_signature": False},
)["exp"]
- 60
)
if self._id_token_timeout is not None:
timeout = min(timeout, self._id_token_timeout.timestamp())
if datetime.now(timezone.utc).timestamp() > timeout:
self._id_token = None
return self._id_token
@property
def refresh_token(self) -> Optional[str]:
if (
self._refresh_token is not None
and self._refresh_token_timeout is not None
and datetime.now(timezone.utc) > self._refresh_token_timeout
):
self._refresh_token = None
return self._refresh_token
@property
def user_name(self) -> Optional[str]:
return self._user_name
def delete_credential(self) -> None:
del self._user_name
del self._password
del self._id_token
del self._refresh_token
self._user_name = None
self._password = None
self._id_token = None
self._id_token_timeout = None
self._refresh_token = None
self._refresh_token_timeout = None
class QuantinuumConfigCredentialStorage(CredentialStorage):
"""Store username and tokens in the default pytket configuration file.
This storage option allows authentication status to persist beyond the current
session, reducing the need to re-enter credentials when constructing new
backends.
Example:
>>> backend = QuantinuumBackend(
>>> device_name=machine,
>>> api_handler=QuantinuumAPI(token_store=QuantinuumConfigCredentialStorage()),
>>> )
"""
def __init__(
self,
id_token_timedelt: timedelta = timedelta(minutes=55),
refresh_token_timedelt: timedelta = timedelta(days=29),
) -> None:
"""Construct a QuantinuumConfigCredentialStorage instance.
:param id_token_timedelt: The time duration for which the ID token is valid.
Defaults to 55 minutes.
:param refresh_token_timedelt: The time duration for which the refresh token
is valid. Defaults to 29 days.
"""
super().__init__(id_token_timedelt, refresh_token_timedelt)
def save_user_name(self, user_name: str) -> None:
hconfig = QuantinuumConfig.from_default_config_file()
hconfig.username = user_name
hconfig.update_default_config_file()
def save_refresh_token(self, refresh_token: str) -> None:
hconfig = QuantinuumConfig.from_default_config_file()
hconfig.refresh_token = refresh_token
refresh_token_timeout = datetime.now(timezone.utc) + self._refresh_timedelt
hconfig.refresh_token_timeout = refresh_token_timeout.strftime(
"%Y-%m-%d %H:%M:%S.%z"
)
hconfig.update_default_config_file()
def save_id_token(self, id_token: str) -> None:
hconfig = QuantinuumConfig.from_default_config_file()
hconfig.id_token = id_token
id_token_timeout = datetime.now(timezone.utc) + self._id_timedelt
hconfig.id_token_timeout = id_token_timeout.strftime("%Y-%m-%d %H:%M:%S.%z")
hconfig.update_default_config_file()
@property
def id_token(self) -> Optional[str]:
hconfig = QuantinuumConfig.from_default_config_file()
id_token = hconfig.id_token
if id_token is not None:
timeout = (
jwt.decode(
id_token,
algorithms=["HS256"],
options={"verify_signature": False},
)["exp"]
- 60
)
if hconfig.id_token_timeout is not None:
id_token_timeout = datetime.strptime(
hconfig.id_token_timeout, "%Y-%m-%d %H:%M:%S.%z"
)
timeout = min(timeout, id_token_timeout.timestamp())
if datetime.now(timezone.utc).timestamp() > timeout:
return None
return id_token
@property
def refresh_token(self) -> Optional[str]:
hconfig = QuantinuumConfig.from_default_config_file()
refresh_token = hconfig.refresh_token
if refresh_token is not None and hconfig.refresh_token_timeout is not None:
refresh_token_timeout = datetime.strptime(
hconfig.refresh_token_timeout, "%Y-%m-%d %H:%M:%S.%z"
)
if datetime.now(timezone.utc) > refresh_token_timeout:
return None
return refresh_token
@property
def user_name(self) -> Optional[str]:
hconfig = QuantinuumConfig.from_default_config_file()
return hconfig.username
def delete_credential(self) -> None:
hconfig = QuantinuumConfig.from_default_config_file()
hconfig.username = None
hconfig.refresh_token = None
hconfig.id_token = None
hconfig.refresh_token_timeout = None
hconfig.id_token_timeout = None
hconfig.update_default_config_file()