Debian Codegraph @

src/cbs.pyx

raw
1 #-------------------------------------------------------------------------
2 # Copyright (c) Microsoft Corporation. All rights reserved.
3 # Licensed under the MIT License. See License.txt in the project root for
4 # license information.
5 #--------------------------------------------------------------------------
6
7 # Python imports
8 from enum import Enum
9 import time
10 import logging
11
12 # C imports
13 from libc cimport stdint
14 from libc.stdlib cimport malloc, free
15 from libc.string cimport memset
16
17 cimport c_cbs
18 cimport c_utils
19 cimport c_strings
20 cimport c_session
21
22
23 _logger = logging.getLogger(__name__)
24
25
26 cpdef create_sas_token(const char* key, const char* scope, const char* keyname, size_t expiry):
27 cdef c_strings.STRING_HANDLE str_value
28 str_value = c_utils.SASToken_CreateString(key, scope, keyname, expiry)
29
30 if <void*>str_value == NULL:
31 raise ValueError("Failed to create SAS token.")
32 if c_utils.SASToken_Validate(str_value) != True:
33 raise ValueError("Generated invalid SAS token")
34 cdef bytes py_str = c_strings.STRING_c_str(str_value)
35 c_strings.STRING_delete(str_value)
36 return py_str
37
38
39 cdef class CBSTokenAuth(object):
40
41 cdef const char* audience
42 cdef const char* token_type
43 cdef const char* token
44 cdef stdint.uint64_t expires_at
45 cdef stdint.uint64_t _refresh_window
46 cdef c_cbs.CBS_HANDLE _cbs_handle
47 cdef c_cbs.AUTH_STATUS state
48 cdef stdint.uint64_t auth_timeout
49 cdef stdint.uint64_t _token_put_time
50 cdef unsigned int token_status_code
51 cdef const char* token_status_description
52 cdef const char* connection_id
53 cdef cSession _session
54
55 def __cinit__(self, const char* audience, const char* token_type, const char* token, stdint.uint64_t expires_at, cSession session, stdint.uint64_t timeout, const char* connection_id, stdint.uint64_t refresh_window):
56 self.state = AUTH_STATUS_IDLE
57 self.audience = audience
58 self.token_type = token_type
59 self.token = token
60 self.expires_at = expires_at
61 self.auth_timeout = timeout
62 self.connection_id = connection_id
63 self._token_put_time = 0
64 if refresh_window > 0:
65 self._refresh_window = refresh_window
66 else:
67 current_time = int(time.time())
68 remaining_time = expires_at - current_time
69 self._refresh_window = int(float(remaining_time) * 0.1)
70 self._cbs_handle = c_cbs.cbs_create(<c_session.SESSION_HANDLE>session._c_value)
71 self._session = session
72 if <void*>self._cbs_handle == NULL:
73 raise MemoryError("Unable to create CBS Handle.")
74 if c_cbs.cbs_open_async(self._cbs_handle, <c_cbs.ON_CBS_OPEN_COMPLETE>on_cbs_open_complete, <void*>self, <c_cbs.ON_CBS_ERROR>on_cbs_error, <void*>self) != 0:
75 raise ValueError("Unable to open CBS link.")
76
77 def __dealloc__(self):
78 _logger.debug("Deallocating CBSTokenAuth")
79 self.destroy()
80
81 cpdef destroy(self):
82 if <void*>self._cbs_handle is not NULL:
83 _logger.debug("Destroying CBSTokenAuth for connection %r", self.connection_id)
84 c_cbs.cbs_destroy(self._cbs_handle)
85 self._cbs_handle = <c_cbs.CBS_HANDLE>NULL
86 self._session = None
87
88 cpdef close(self):
89 if c_cbs.cbs_close(self._cbs_handle) != 0:
90 self._value_error("Unable to close CBS link.")
91
92 cpdef set_trace(self, bint trace_on):
93 if c_cbs.cbs_set_trace(self._cbs_handle, trace_on) != 0:
94 raise ValueError("Unable to set debug trace.")
95
96 cpdef authenticate(self):
97 if self.state == AUTH_STATUS_IN_PROGRESS:
98 return
99 current_time = int(time.time())
100 if current_time >= self.expires_at:
101 raise ValueError("Token has expired")
102 self._token_put_time = current_time
103 if <void*>c_cbs.cbs_put_token_async(
104 self._cbs_handle,
105 self.token_type,
106 self.audience,
107 self.token,
108 <c_cbs.ON_CBS_OPERATION_COMPLETE>on_cbs_put_token_complete,
109 <void*>self) == NULL:
110 raise ValueError("Put-Token request failed.")
111 else:
112 self.state = AUTH_STATUS_IN_PROGRESS
113
114 cpdef get_status(self):
115 self._update_status()
116 return self.state
117
118 cpdef get_failure_info(self):
119 return self.token_status_code, self.token_status_description
120
121 cpdef refresh(self, const char* refresh_token, stdint.uint64_t expires_at):
122 self._update_status()
123 if self.state == AUTH_STATUS_REFRESH_REQUIRED:
124 self.token = refresh_token
125 self.authenticate()
126 self.expires_at = expires_at
127
128 cpdef _update_status(self):
129 error_code = 0
130 is_refresh_required = False
131 if self.state == AUTH_STATUS_OK or self.state == AUTH_STATUS_REFRESH_REQUIRED:
132 is_expired, is_refresh_required = self._check_expiration_and_refresh_status()
133 if is_expired:
134 self.state = AUTH_STATUS_EXPIRED
135 elif is_refresh_required:
136 self.state = AUTH_STATUS_REFRESH_REQUIRED
137 elif self.state == AUTH_STATUS_IN_PROGRESS:
138 put_timeout = self._check_put_timeout_status()
139 if put_timeout:
140 self.state = AUTH_STATUS_TIMEOUT
141
142 cpdef _check_put_timeout_status(self):
143 seconds_since_epoc = int(time.time())
144 if self.auth_timeout > 0:
145 return (seconds_since_epoc - self._token_put_time) >= self.auth_timeout
146 else:
147 return False
148
149 cpdef _check_expiration_and_refresh_status(self):
150 seconds_since_epoc = int(time.time())
151 is_expired = seconds_since_epoc >= self.expires_at
152 is_refresh_required = (self.expires_at - seconds_since_epoc) <= self._refresh_window
153 return is_expired, is_refresh_required
154
155 cpdef _cbs_open_complete(self, result):
156 self.on_cbs_open_complete(result)
157
158 cpdef on_cbs_open_complete(self, result):
159 _logger.info("CBS for connection %r completed opening with status: %r", self.connection_id, result)
160 if result == c_cbs.CBS_OPEN_COMPLETE_RESULT_TAG.CBS_OPEN_ERROR:
161 self.state = AUTH_STATUS_FAILURE
162
163 cpdef _cbs_error(self):
164 self.on_cbs_error()
165
166 cpdef on_cbs_error(self):
167 _logger.info("CBS error occurred on connection %r.", self.connection_id)
168
169 cpdef _cbs_put_token_compelete(self, c_cbs.CBS_OPERATION_RESULT_TAG result, unsigned int status_code, const char* status_description):
170 if result == CBS_OPERATION_RESULT_OK:
171 self.state = AUTH_STATUS_OK
172 else:
173 self.state = AUTH_STATUS_ERROR
174 self.token_status_code = status_code
175 self.token_status_description = status_description
176 self.on_cbs_put_token_complete(result, status_code, status_description)
177
178 cpdef on_cbs_put_token_complete(self, c_cbs.CBS_OPERATION_RESULT_TAG result, unsigned int status_code, const char* status_description):
179 _logger.info("Token put complete with result: %r, status: %r, description: %r, connection: %r", result, status_code, status_description, self.connection_id)
180
181
182 #### Callbacks
183
184 cdef void on_cbs_open_complete(void *context, c_cbs.CBS_OPEN_COMPLETE_RESULT_TAG open_complete_result):
185 if <void*>context != NULL:
186 context_pyobj = <PyObject*>context
187 if context_pyobj.ob_refcnt == 0: # context is being garbage collected, skip the callback
188 _logger.warning("Can't call on_cbs_open_complete during garbage collection.")
189 return
190 context_obj = <object>context
191 context_obj._cbs_open_complete(open_complete_result)
192
193
194 cdef void on_cbs_error(void* context):
195 if <void*>context != NULL:
196 context_pyobj = <PyObject*>context
197 if context_pyobj.ob_refcnt == 0: # context is being garbage collected, skip the callback
198 _logger.warning("Can't call on_cbs_error during garbage collection.")
199 return
200 context_obj = <object>context
201 context_obj._cbs_error()
202
203
204 cdef void on_cbs_put_token_complete(void* context, c_cbs.CBS_OPERATION_RESULT_TAG complete_result, unsigned int status_code, const char* status_description):
205 cdef unsigned int verified_status_code
206 cdef const char* verified_description
207 if <void*>context != NULL:
208 context_pyobj = <PyObject*>context
209 if context_pyobj.ob_refcnt == 0: # context is being garbage collected, skip the callback
210 _logger.warning("Can't call on_cbs_put_token_complete during garbage collection.")
211 return
212 context_obj = <object>context
213 try:
214 if <void*>status_code != NULL:
215 verified_status_code = status_code
216 else:
217 verified_status_code = 0
218 if <void*>status_description != NULL:
219 verified_description = status_description
220 else:
221 verified_description = b"CBS Session closed."
222 context_obj._cbs_put_token_compelete(complete_result, verified_status_code, verified_description)
223 except KeyboardInterrupt:
224 context_obj._cbs_put_token_compelete(
225 CBS_OPERATION_RESULT_INSTANCE_CLOSED, 1, b"Client shutdown with keyboard interrupt.")