clear-skies 2.0.5__py3-none-any.whl → 2.0.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of clear-skies might be problematic. Click here for more details.

Files changed (252) hide show
  1. {clear_skies-2.0.5.dist-info → clear_skies-2.0.7.dist-info}/METADATA +1 -1
  2. clear_skies-2.0.7.dist-info/RECORD +251 -0
  3. clearskies/__init__.py +61 -0
  4. clearskies/action.py +7 -0
  5. clearskies/authentication/__init__.py +15 -0
  6. clearskies/authentication/authentication.py +46 -0
  7. clearskies/authentication/authorization.py +16 -0
  8. clearskies/authentication/authorization_pass_through.py +20 -0
  9. clearskies/authentication/jwks.py +163 -0
  10. clearskies/authentication/public.py +5 -0
  11. clearskies/authentication/secret_bearer.py +553 -0
  12. clearskies/autodoc/__init__.py +8 -0
  13. clearskies/autodoc/formats/__init__.py +5 -0
  14. clearskies/autodoc/formats/oai3_json/__init__.py +7 -0
  15. clearskies/autodoc/formats/oai3_json/oai3_json.py +87 -0
  16. clearskies/autodoc/formats/oai3_json/oai3_schema_resolver.py +15 -0
  17. clearskies/autodoc/formats/oai3_json/parameter.py +35 -0
  18. clearskies/autodoc/formats/oai3_json/request.py +68 -0
  19. clearskies/autodoc/formats/oai3_json/response.py +28 -0
  20. clearskies/autodoc/formats/oai3_json/schema/__init__.py +11 -0
  21. clearskies/autodoc/formats/oai3_json/schema/array.py +9 -0
  22. clearskies/autodoc/formats/oai3_json/schema/default.py +13 -0
  23. clearskies/autodoc/formats/oai3_json/schema/enum.py +7 -0
  24. clearskies/autodoc/formats/oai3_json/schema/object.py +35 -0
  25. clearskies/autodoc/formats/oai3_json/test.json +1985 -0
  26. clearskies/autodoc/py.typed +0 -0
  27. clearskies/autodoc/request/__init__.py +15 -0
  28. clearskies/autodoc/request/header.py +6 -0
  29. clearskies/autodoc/request/json_body.py +6 -0
  30. clearskies/autodoc/request/parameter.py +8 -0
  31. clearskies/autodoc/request/request.py +47 -0
  32. clearskies/autodoc/request/url_parameter.py +6 -0
  33. clearskies/autodoc/request/url_path.py +6 -0
  34. clearskies/autodoc/response/__init__.py +5 -0
  35. clearskies/autodoc/response/response.py +9 -0
  36. clearskies/autodoc/schema/__init__.py +31 -0
  37. clearskies/autodoc/schema/array.py +10 -0
  38. clearskies/autodoc/schema/base64.py +8 -0
  39. clearskies/autodoc/schema/boolean.py +5 -0
  40. clearskies/autodoc/schema/date.py +5 -0
  41. clearskies/autodoc/schema/datetime.py +5 -0
  42. clearskies/autodoc/schema/double.py +5 -0
  43. clearskies/autodoc/schema/enum.py +17 -0
  44. clearskies/autodoc/schema/integer.py +6 -0
  45. clearskies/autodoc/schema/long.py +5 -0
  46. clearskies/autodoc/schema/number.py +6 -0
  47. clearskies/autodoc/schema/object.py +13 -0
  48. clearskies/autodoc/schema/password.py +5 -0
  49. clearskies/autodoc/schema/schema.py +11 -0
  50. clearskies/autodoc/schema/string.py +5 -0
  51. clearskies/backends/__init__.py +65 -0
  52. clearskies/backends/api_backend.py +1178 -0
  53. clearskies/backends/backend.py +136 -0
  54. clearskies/backends/cursor_backend.py +335 -0
  55. clearskies/backends/memory_backend.py +797 -0
  56. clearskies/backends/secrets_backend.py +106 -0
  57. clearskies/column.py +1233 -0
  58. clearskies/columns/__init__.py +71 -0
  59. clearskies/columns/audit.py +206 -0
  60. clearskies/columns/belongs_to_id.py +483 -0
  61. clearskies/columns/belongs_to_model.py +132 -0
  62. clearskies/columns/belongs_to_self.py +105 -0
  63. clearskies/columns/boolean.py +113 -0
  64. clearskies/columns/category_tree.py +275 -0
  65. clearskies/columns/category_tree_ancestors.py +51 -0
  66. clearskies/columns/category_tree_children.py +127 -0
  67. clearskies/columns/category_tree_descendants.py +48 -0
  68. clearskies/columns/created.py +95 -0
  69. clearskies/columns/created_by_authorization_data.py +116 -0
  70. clearskies/columns/created_by_header.py +99 -0
  71. clearskies/columns/created_by_ip.py +92 -0
  72. clearskies/columns/created_by_routing_data.py +97 -0
  73. clearskies/columns/created_by_user_agent.py +92 -0
  74. clearskies/columns/date.py +234 -0
  75. clearskies/columns/datetime.py +282 -0
  76. clearskies/columns/email.py +76 -0
  77. clearskies/columns/float.py +153 -0
  78. clearskies/columns/has_many.py +505 -0
  79. clearskies/columns/has_many_self.py +56 -0
  80. clearskies/columns/has_one.py +14 -0
  81. clearskies/columns/integer.py +160 -0
  82. clearskies/columns/json.py +128 -0
  83. clearskies/columns/many_to_many_ids.py +337 -0
  84. clearskies/columns/many_to_many_ids_with_data.py +274 -0
  85. clearskies/columns/many_to_many_models.py +158 -0
  86. clearskies/columns/many_to_many_pivots.py +134 -0
  87. clearskies/columns/phone.py +159 -0
  88. clearskies/columns/select.py +92 -0
  89. clearskies/columns/string.py +102 -0
  90. clearskies/columns/timestamp.py +164 -0
  91. clearskies/columns/updated.py +110 -0
  92. clearskies/columns/uuid.py +86 -0
  93. clearskies/configs/README.md +105 -0
  94. clearskies/configs/__init__.py +162 -0
  95. clearskies/configs/actions.py +43 -0
  96. clearskies/configs/any.py +13 -0
  97. clearskies/configs/any_dict.py +22 -0
  98. clearskies/configs/any_dict_or_callable.py +23 -0
  99. clearskies/configs/authentication.py +23 -0
  100. clearskies/configs/authorization.py +23 -0
  101. clearskies/configs/boolean.py +16 -0
  102. clearskies/configs/boolean_or_callable.py +18 -0
  103. clearskies/configs/callable_config.py +18 -0
  104. clearskies/configs/columns.py +34 -0
  105. clearskies/configs/conditions.py +30 -0
  106. clearskies/configs/config.py +24 -0
  107. clearskies/configs/datetime.py +18 -0
  108. clearskies/configs/datetime_or_callable.py +19 -0
  109. clearskies/configs/endpoint.py +23 -0
  110. clearskies/configs/endpoint_list.py +29 -0
  111. clearskies/configs/float.py +16 -0
  112. clearskies/configs/float_or_callable.py +18 -0
  113. clearskies/configs/integer.py +16 -0
  114. clearskies/configs/integer_or_callable.py +18 -0
  115. clearskies/configs/joins.py +30 -0
  116. clearskies/configs/list_any_dict.py +30 -0
  117. clearskies/configs/list_any_dict_or_callable.py +31 -0
  118. clearskies/configs/model_class.py +35 -0
  119. clearskies/configs/model_column.py +65 -0
  120. clearskies/configs/model_columns.py +56 -0
  121. clearskies/configs/model_destination_name.py +25 -0
  122. clearskies/configs/model_to_id_column.py +43 -0
  123. clearskies/configs/readable_model_column.py +9 -0
  124. clearskies/configs/readable_model_columns.py +9 -0
  125. clearskies/configs/schema.py +23 -0
  126. clearskies/configs/searchable_model_columns.py +9 -0
  127. clearskies/configs/security_headers.py +39 -0
  128. clearskies/configs/select.py +26 -0
  129. clearskies/configs/select_list.py +47 -0
  130. clearskies/configs/string.py +29 -0
  131. clearskies/configs/string_dict.py +32 -0
  132. clearskies/configs/string_list.py +32 -0
  133. clearskies/configs/string_list_or_callable.py +35 -0
  134. clearskies/configs/string_or_callable.py +18 -0
  135. clearskies/configs/timedelta.py +18 -0
  136. clearskies/configs/timezone.py +18 -0
  137. clearskies/configs/url.py +23 -0
  138. clearskies/configs/validators.py +45 -0
  139. clearskies/configs/writeable_model_column.py +9 -0
  140. clearskies/configs/writeable_model_columns.py +9 -0
  141. clearskies/configurable.py +76 -0
  142. clearskies/contexts/__init__.py +11 -0
  143. clearskies/contexts/cli.py +117 -0
  144. clearskies/contexts/context.py +98 -0
  145. clearskies/contexts/wsgi.py +76 -0
  146. clearskies/contexts/wsgi_ref.py +82 -0
  147. clearskies/decorators.py +33 -0
  148. clearskies/di/__init__.py +15 -0
  149. clearskies/di/additional_config.py +130 -0
  150. clearskies/di/additional_config_auto_import.py +17 -0
  151. clearskies/di/di.py +973 -0
  152. clearskies/di/inject/__init__.py +23 -0
  153. clearskies/di/inject/by_class.py +21 -0
  154. clearskies/di/inject/by_name.py +18 -0
  155. clearskies/di/inject/di.py +13 -0
  156. clearskies/di/inject/environment.py +14 -0
  157. clearskies/di/inject/input_output.py +20 -0
  158. clearskies/di/inject/now.py +13 -0
  159. clearskies/di/inject/requests.py +13 -0
  160. clearskies/di/inject/secrets.py +14 -0
  161. clearskies/di/inject/utcnow.py +13 -0
  162. clearskies/di/inject/uuid.py +15 -0
  163. clearskies/di/injectable.py +29 -0
  164. clearskies/di/injectable_properties.py +131 -0
  165. clearskies/di/test_module/__init__.py +6 -0
  166. clearskies/di/test_module/another_module/__init__.py +2 -0
  167. clearskies/di/test_module/module_class.py +5 -0
  168. clearskies/end.py +183 -0
  169. clearskies/endpoint.py +1314 -0
  170. clearskies/endpoint_group.py +336 -0
  171. clearskies/endpoints/__init__.py +25 -0
  172. clearskies/endpoints/advanced_search.py +526 -0
  173. clearskies/endpoints/callable.py +388 -0
  174. clearskies/endpoints/create.py +205 -0
  175. clearskies/endpoints/delete.py +139 -0
  176. clearskies/endpoints/get.py +271 -0
  177. clearskies/endpoints/health_check.py +183 -0
  178. clearskies/endpoints/list.py +574 -0
  179. clearskies/endpoints/restful_api.py +427 -0
  180. clearskies/endpoints/schema.py +189 -0
  181. clearskies/endpoints/simple_search.py +286 -0
  182. clearskies/endpoints/update.py +193 -0
  183. clearskies/environment.py +104 -0
  184. clearskies/exceptions/__init__.py +19 -0
  185. clearskies/exceptions/authentication.py +2 -0
  186. clearskies/exceptions/authorization.py +2 -0
  187. clearskies/exceptions/client_error.py +2 -0
  188. clearskies/exceptions/input_errors.py +4 -0
  189. clearskies/exceptions/missing_dependency.py +2 -0
  190. clearskies/exceptions/moved_permanently.py +3 -0
  191. clearskies/exceptions/moved_temporarily.py +3 -0
  192. clearskies/exceptions/not_found.py +2 -0
  193. clearskies/functional/__init__.py +7 -0
  194. clearskies/functional/routing.py +92 -0
  195. clearskies/functional/string.py +112 -0
  196. clearskies/functional/validations.py +76 -0
  197. clearskies/input_outputs/__init__.py +13 -0
  198. clearskies/input_outputs/cli.py +171 -0
  199. clearskies/input_outputs/exceptions/__init__.py +2 -0
  200. clearskies/input_outputs/exceptions/cli_input_error.py +2 -0
  201. clearskies/input_outputs/exceptions/cli_not_found.py +2 -0
  202. clearskies/input_outputs/headers.py +45 -0
  203. clearskies/input_outputs/input_output.py +138 -0
  204. clearskies/input_outputs/programmatic.py +69 -0
  205. clearskies/input_outputs/py.typed +0 -0
  206. clearskies/input_outputs/wsgi.py +77 -0
  207. clearskies/model.py +1922 -0
  208. clearskies/py.typed +0 -0
  209. clearskies/query/__init__.py +12 -0
  210. clearskies/query/condition.py +223 -0
  211. clearskies/query/join.py +136 -0
  212. clearskies/query/query.py +196 -0
  213. clearskies/query/sort.py +27 -0
  214. clearskies/schema.py +82 -0
  215. clearskies/secrets/__init__.py +6 -0
  216. clearskies/secrets/additional_configs/__init__.py +32 -0
  217. clearskies/secrets/additional_configs/mysql_connection_dynamic_producer.py +61 -0
  218. clearskies/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssh_cert_bastion.py +160 -0
  219. clearskies/secrets/akeyless.py +182 -0
  220. clearskies/secrets/exceptions/__init__.py +1 -0
  221. clearskies/secrets/exceptions/not_found.py +2 -0
  222. clearskies/secrets/secrets.py +38 -0
  223. clearskies/security_header.py +15 -0
  224. clearskies/security_headers/__init__.py +11 -0
  225. clearskies/security_headers/cache_control.py +67 -0
  226. clearskies/security_headers/cors.py +50 -0
  227. clearskies/security_headers/csp.py +94 -0
  228. clearskies/security_headers/hsts.py +22 -0
  229. clearskies/security_headers/x_content_type_options.py +0 -0
  230. clearskies/security_headers/x_frame_options.py +0 -0
  231. clearskies/test_base.py +8 -0
  232. clearskies/typing.py +11 -0
  233. clearskies/validator.py +37 -0
  234. clearskies/validators/__init__.py +33 -0
  235. clearskies/validators/after_column.py +62 -0
  236. clearskies/validators/before_column.py +13 -0
  237. clearskies/validators/in_the_future.py +32 -0
  238. clearskies/validators/in_the_future_at_least.py +11 -0
  239. clearskies/validators/in_the_future_at_most.py +10 -0
  240. clearskies/validators/in_the_past.py +32 -0
  241. clearskies/validators/in_the_past_at_least.py +10 -0
  242. clearskies/validators/in_the_past_at_most.py +10 -0
  243. clearskies/validators/maximum_length.py +26 -0
  244. clearskies/validators/maximum_value.py +29 -0
  245. clearskies/validators/minimum_length.py +26 -0
  246. clearskies/validators/minimum_value.py +29 -0
  247. clearskies/validators/required.py +34 -0
  248. clearskies/validators/timedelta.py +59 -0
  249. clearskies/validators/unique.py +30 -0
  250. clear_skies-2.0.5.dist-info/RECORD +0 -4
  251. {clear_skies-2.0.5.dist-info → clear_skies-2.0.7.dist-info}/WHEEL +0 -0
  252. {clear_skies-2.0.5.dist-info → clear_skies-2.0.7.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,553 @@
1
+ import clearskies.configs
2
+ import clearskies.decorators
3
+ import clearskies.di
4
+ from clearskies import autodoc
5
+ from clearskies.authentication.authentication import Authentication
6
+
7
+
8
+ class SecretBearer(Authentication, clearskies.di.InjectableProperties):
9
+ """
10
+ Secret Bearer performs authentication by checking against a static API key stored in either environment variables or a secret manager.
11
+
12
+ This can be used in two different ways:
13
+
14
+ 1. Attached to an endpoint to enforce authentication
15
+ 2. Attached to an API backend to specify how to authenticate to the API endpoint.
16
+
17
+ ### Authenticating Endpoints.
18
+
19
+ When attached to an endpoint this will enforce authentication. Clients authenticate themselves by providing the secret value
20
+ via the `authorization` header. In the following example we configure the secret bearer class to get the secretfrom an
21
+ environment variable which is set in the code itself. Normally you wouldn't set environment variables like this,
22
+ but it's done here to create a self-contained example that is easy to run:
23
+
24
+ ```python
25
+ import os
26
+ import clearskies
27
+
28
+ os.environ["MY_AUTH_SECRET"] = "SUPERSECRET"
29
+
30
+ wsgi = clearskies.contexts.WsgiRef(
31
+ clearskies.endpoints.Callable(
32
+ lambda: {"hello": "world"},
33
+ authentication=clearskies.authentication.SecretBearer(environment_key="MY_AUTH_SECRET"),
34
+ )
35
+ )
36
+ wsgi()
37
+ ```
38
+ We can then call it with and without the authentication header:
39
+
40
+ ```bash
41
+ $ curl 'http://localhost:8080' -H 'Authorization: SUPERSECRET' | jq
42
+ {
43
+ "status": "success",
44
+ "error": "",
45
+ "data": {
46
+ "hello": "world"
47
+ },
48
+ "pagination": {},
49
+ "input_errors": {}
50
+ }
51
+
52
+ $ curl 'http://localhost:8080' | jq
53
+ {
54
+ "status": "client_error",
55
+ "error": "Not Authenticated",
56
+ "data": [],
57
+ "pagination": {},
58
+ "input_errors": {}
59
+ }
60
+
61
+ $ curl 'http://localhost:8080' -H 'Authorization: NOTTHESECRET' | jq
62
+ {
63
+ "status": "client_error",
64
+ "error": "Not Authenticated",
65
+ "data": [],
66
+ "pagination": {},
67
+ "input_errors": {}
68
+ }
69
+ ```
70
+
71
+ ### Authenticating to APIs
72
+
73
+ The secret bearer class can also be attached to an API Backend to provide authentication to remote APIs. To
74
+ demonstrate, here is an example server that expects a secret token in the authorization header:
75
+
76
+ ```python
77
+ import os
78
+ import clearskies
79
+ from clearskies import columns
80
+
81
+ os.environ["MY_SECRET"] = "SUPERSECRET"
82
+
83
+
84
+ class Widget(clearskies.Model):
85
+ id_column_name = "id"
86
+ backend = clearskies.backends.MemoryBackend()
87
+
88
+ id = columns.Uuid()
89
+ name = columns.String()
90
+ category = columns.String()
91
+ cost = columns.Float()
92
+ created_at = columns.Created()
93
+ updated_at = columns.Updated()
94
+
95
+
96
+ wsgi = clearskies.contexts.WsgiRef(
97
+ clearskies.endpoints.RestfulApi(
98
+ url="widgets",
99
+ model_class=Widget,
100
+ authentication=clearskies.authentication.SecretBearer(environment_key="MY_SECRET"),
101
+ readable_column_names=["id", "name", "category", "cost", "created_at", "updated_at"],
102
+ writeable_column_names=["name", "category", "cost"],
103
+ sortable_column_names=["name", "category", "cost"],
104
+ searchable_column_names=["id", "name", "category", "cost"],
105
+ default_sort_column_name="name",
106
+ )
107
+ )
108
+ wsgi()
109
+ ```
110
+
111
+ Then here is a client app (you can launch the above server and then run this in a new terminal) that
112
+ similarly uses the secret bearer class to authenticate to the server:
113
+
114
+ ```python
115
+ import os
116
+ import clearskies
117
+ from clearskies import columns
118
+
119
+ os.environ["MY_SECRET"] = "SUPERSECRET"
120
+
121
+
122
+ class Widget(clearskies.Model):
123
+ id_column_name = "id"
124
+ backend = clearskies.backends.ApiBackend(
125
+ base_url="http://localhost:8080",
126
+ authentication=clearskies.authentication.SecretBearer(environment_key="MY_SECRET"),
127
+ )
128
+
129
+ id = columns.String()
130
+ name = columns.String()
131
+ category = columns.String()
132
+ cost = columns.Float()
133
+ created_at = columns.Datetime()
134
+ updated_at = columns.Datetime()
135
+
136
+
137
+ def api_demo(widgets: Widget) -> Widget:
138
+ thinga = widgets.create({"name": "Thinga", "category": "Doohickey", "cost": 125})
139
+ mabob = widgets.create({"name": "Mabob", "category": "Doohicky", "cost": 150})
140
+ return widgets
141
+
142
+
143
+ cli = clearskies.contexts.Cli(
144
+ clearskies.endpoints.Callable(
145
+ api_demo,
146
+ model_class=Widget,
147
+ return_records=True,
148
+ readable_column_names=["id", "name", "category", "cost", "created_at", "updated_at"],
149
+ ),
150
+ classes=[Widget],
151
+ )
152
+ cli()
153
+ ```
154
+
155
+ The above app declares a model class that matches the output from our server/api. Note that the id,
156
+ created_at, and updated_at columns all changed types to their "plain" types. This is very normal. The API
157
+ is the one that is responsible for assigning ids and setting created/updated timestamps, so from the
158
+ perspective of our client, these are plain string/datetime fields. If we used the UUID or created/updated
159
+ columns, then when the client called the API it would try to set all of these columns. Since they are not
160
+ writeable columns, the API would return an input error. If you launch the above server/API and then run
161
+ the given client script, you'll see output like this:
162
+
163
+ ```json
164
+ {
165
+ "status": "success",
166
+ "error": "",
167
+ "data": [
168
+ {
169
+ "id": "54eef01d-7c87-4959-b525-dcb9047d9692",
170
+ "name": "Mabob",
171
+ "category": "Doohicky",
172
+ "cost": 150.0,
173
+ "created_at": "2025-06-13T15:19:27+00:00",
174
+ "updated_at": "2025-06-13T15:19:27+00:00",
175
+ },
176
+ {
177
+ "id": "ed1421b8-88ad-49d2-a130-c34b4ac4dfcf",
178
+ "name": "Thinga",
179
+ "category": "Doohickey",
180
+ "cost": 125.0,
181
+ "created_at": "2025-06-13T15:19:27+00:00",
182
+ "updated_at": "2025-06-13T15:19:27+00:00",
183
+ },
184
+ ],
185
+ "pagination": {},
186
+ "input_errors": {},
187
+ }
188
+ ```
189
+ """
190
+
191
+ is_public = False
192
+ can_authorize = False
193
+
194
+ environment = clearskies.di.inject.Environment()
195
+ secrets = clearskies.di.inject.Secrets()
196
+
197
+ """
198
+ The path in our secret manager from which the secret should be fetched.
199
+
200
+ Of course, to use `secret_key`, you must also provide a secret manager. The below example uses the dependency
201
+ injection system to create a faux secret manager to demonstrate how it works in general:
202
+
203
+ ```python
204
+ from types import SimpleNamespace
205
+ import clearskies
206
+
207
+ def fetch_secret(path):
208
+ if path == "/path/to/my/secret":
209
+ return "SUPERSECRET"
210
+ raise KeyError(f"Attempt to fetch non-existent secret: {path}")
211
+
212
+ fake_secret_manager = SimpleNamespace(get=fetch_secret)
213
+
214
+ wsgi = clearskies.contexts.WsgiRef(
215
+ clearskies.endpoints.Callable(
216
+ lambda: {"hello": "world"},
217
+ authentication=clearskies.authentication.SecretBearer(secret_key="/path/to/my/secret"),
218
+ ),
219
+ bindings={
220
+ "secrets": fake_secret_manager,
221
+ },
222
+ )
223
+ wsgi()
224
+ ```
225
+
226
+ And when invoked:
227
+
228
+ ```bash
229
+ $ curl 'http://localhost:8080/' -H "Authorization: SUPERSECRET" | jq
230
+ {
231
+ "status": "success",
232
+ "error": "",
233
+ "data": {
234
+ "hello": "world"
235
+ },
236
+ "pagination": {},
237
+ "input_errors": {}
238
+ }
239
+
240
+ $ curl 'http://localhost:8080/' -H "Authorization: definitely-not-the-api-key" | jq
241
+ {
242
+ "status": "client_error",
243
+ "error": "Not Authenticated",
244
+ "data": [],
245
+ "pagination": {},
246
+ "input_errors": {}
247
+ }
248
+ ```
249
+
250
+ """
251
+ secret_key = clearskies.configs.String(default="")
252
+
253
+ """
254
+ The path in our secret manager where an alternate secret can also be fetched
255
+
256
+ The alternate secret is exclusively used to authenticate incoming requests. This allows for secret
257
+ rotation - Point secret_key to a new secret and alternate_secret_key to the old secret. Both will then
258
+ be accepted and you can migrate your applications to only send the new secret. Once they are all updated,
259
+ remove the alternate_secret_key:
260
+
261
+ ```python
262
+ from types import SimpleNamespace
263
+ import clearskies
264
+
265
+ def fetch_secret(path):
266
+ if path == "/path/to/my/secret":
267
+ return "SUPERSECRET"
268
+ if path == "/path/to/alternate/secret":
269
+ return "ALSOOKAY"
270
+ raise KeyError(f"Attempt to fetch non-existent secret: {path}")
271
+
272
+ fake_secret_manager = SimpleNamespace(get=fetch_secret)
273
+
274
+ wsgi = clearskies.contexts.WsgiRef(
275
+ clearskies.endpoints.Callable(
276
+ lambda: {"hello": "world"},
277
+ authentication=clearskies.authentication.SecretBearer(
278
+ secret_key="/path/to/my/secret",
279
+ alternate_secret_key="/path/to/alternate/secret",
280
+ ),
281
+ ),
282
+ bindings={
283
+ "secrets": fake_secret_manager,
284
+ },
285
+ )
286
+ wsgi()
287
+ ```
288
+
289
+ And when invoked:
290
+
291
+ ```bash
292
+ $ curl 'http://localhost:8080/' -H "Authorization: SUPERSECRET" | jq
293
+ {
294
+ "status": "success",
295
+ "error": "",
296
+ "data": {
297
+ "hello": "world"
298
+ },
299
+ "pagination": {},
300
+ "input_errors": {}
301
+ }
302
+
303
+ $ curl 'http://localhost:8080/' -H "Authorization: ALSOOKAY" | jq
304
+ {
305
+ "status": "success",
306
+ "error": "",
307
+ "data": {
308
+ "hello": "world"
309
+ },
310
+ "pagination": {},
311
+ "input_errors": {}
312
+ }
313
+
314
+ $ curl 'http://localhost:8080/' -H "Authorization: NOTTHESECRET" | jq
315
+ {
316
+ "status": "client_error",
317
+ "error": "Not Authenticated",
318
+ "data": [],
319
+ "pagination": {},
320
+ "input_errors": {}
321
+ }
322
+ ```
323
+
324
+ """
325
+ alternate_secret_key = clearskies.configs.String(default="")
326
+
327
+ """
328
+ The name of the environment variable from which we should fetch our key.
329
+ """
330
+ environment_key = clearskies.configs.String(default="")
331
+
332
+ """
333
+ The name of an alternate environment variable from which we should fetch our key.
334
+
335
+ This allows for secret rotation by allowing the API to accept a secret from two different
336
+ environment variables: an old value and a new value. You can then migrate your client applications
337
+ to use the new key and, once they are all migrated, remove the old key from the application
338
+ configuration. Here's an example:
339
+
340
+ ```python
341
+ import os
342
+ import clearskies
343
+
344
+ os.environ["MY_AUTH_SECRET"] = "SUPERSECRET"
345
+ os.environ["MY_ALT_SECRET"] = "ALSOOKAY"
346
+
347
+ wsgi = clearskies.contexts.WsgiRef(
348
+ clearskies.endpoints.Callable(
349
+ lambda: {"hello": "world"},
350
+ authentication=clearskies.authentication.SecretBearer(
351
+ environment_key="MY_AUTH_SECRET",
352
+ alternate_environment_key="MY_ALT_SECRET",
353
+ ),
354
+ ),
355
+ )
356
+ wsgi()
357
+ ```
358
+
359
+ And when invoked:
360
+
361
+ ```bash
362
+ $ curl 'http://localhost:8080/' -H "Authorization: SUPERSECRET" | jq
363
+ {
364
+ "status": "success",
365
+ "error": "",
366
+ "data": {
367
+ "hello": "world"
368
+ },
369
+ "pagination": {},
370
+ "input_errors": {}
371
+ }
372
+
373
+ $ curl 'http://localhost:8080/' -H "Authorization: ALSOOKAY" | jq
374
+ {
375
+ "status": "success",
376
+ "error": "",
377
+ "data": {
378
+ "hello": "world"
379
+ },
380
+ "pagination": {},
381
+ "input_errors": {}
382
+ }
383
+
384
+ $ curl 'http://localhost:8080/' -H "Authorization: NOTTHESECRET" | jq
385
+ {
386
+ "status": "client_error",
387
+ "error": "Not Authenticated",
388
+ "data": [],
389
+ "pagination": {},
390
+ "input_errors": {}
391
+ }
392
+ ```
393
+
394
+ """
395
+ alternate_environment_key = clearskies.configs.String(default="")
396
+
397
+ """
398
+ The expected prefix (if any) that should come before the secret key in the authorization header.
399
+
400
+ This applies to both the incoming authentication process and outgoing authentication headers. Some systems
401
+ require a prefix before the auth token in the HTTP header (e.g. `Authorization: TOKEN [auth key here]`).
402
+ You can provide that prefix to `header_prefix` in order for the endpoint to require a prefix or the api backend
403
+ to provide such a prefix. Note that the prefix is case-insensitive and it does not assume a space between the
404
+ prefix and the token (so, if you want a space, you must explicitly put it in the prefix). Here's an example:
405
+
406
+ ```python
407
+ import os
408
+ import clearskies
409
+
410
+ os.environ["MY_AUTH_SECRET"] = "SUPERSECRET"
411
+
412
+ wsgi = clearskies.contexts.WsgiRef(
413
+ clearskies.endpoints.Callable(
414
+ lambda: {"hello": "world"},
415
+ authentication=clearskies.authentication.SecretBearer(
416
+ environment_key="MY_AUTH_SECRET",
417
+ header_prefix="secret-token ",
418
+ ),
419
+ ),
420
+ )
421
+ wsgi()
422
+ ```
423
+
424
+ And then usage:
425
+
426
+ ```bash
427
+ $ curl 'http://localhost:8080/' -H "Authorization: SECRET-TOKEN SUPERSECRET" | jq
428
+ {
429
+ "status": "success",
430
+ "error": "",
431
+ "data": {
432
+ "hello": "world"
433
+ },
434
+ "pagination": {},
435
+ "input_errors": {}
436
+ }
437
+
438
+ $ curl 'http://localhost:8080/' -H "Authorization: SUPERSECRET" | jq
439
+ {
440
+ "status": "client_error",
441
+ "error": "Not Authenticated",
442
+ "data": [],
443
+ "pagination": {},
444
+ "input_errors": {}
445
+ }
446
+ ```
447
+ """
448
+ header_prefix = clearskies.configs.String(default="")
449
+
450
+ """
451
+ The length of our header prefix
452
+ """
453
+ header_prefix_length = None
454
+
455
+ """
456
+ The name of our security scheme in the auto-generated documentation
457
+ """
458
+ documentation_security_name = clearskies.configs.String(default="ApiKey")
459
+
460
+ _secret: str = None # type: ignore
461
+ _alternate_secret: str = None # type: ignore
462
+
463
+ @clearskies.decorators.parameters_to_properties
464
+ def __init__(
465
+ self,
466
+ secret_key: str = "",
467
+ alternate_secret_key: str = "",
468
+ environment_key: str = "",
469
+ alternate_environment_key: str = "",
470
+ header_prefix: str = "",
471
+ documentation_security_name: str = "",
472
+ ):
473
+ if not secret_key and not environment_key:
474
+ raise ValueError("Must set either 'secret_key' or 'environment_key' when configuring the SecretBearer")
475
+ self.header_prefix_length = len(header_prefix)
476
+ self.finalize_and_validate_configuration()
477
+
478
+ @property
479
+ def secret(self):
480
+ if not self._secret:
481
+ self._secret = (
482
+ self.secrets.get(self.secret_key) if self.secret_key else self.environment.get(self.environment_key)
483
+ )
484
+ return self._secret
485
+
486
+ def clear_credential_cache(self):
487
+ if self.secret_key:
488
+ self._secret = None # type: ignore
489
+
490
+ @property
491
+ def alternate_secret(self):
492
+ if not self.alternate_secret_key and not self.alternate_environment_key:
493
+ return ""
494
+
495
+ if not self._alternate_secret:
496
+ self._alternate_secret = (
497
+ self.secrets.get(self.alternate_secret_key)
498
+ if self.alternate_secret_key
499
+ else self.environment.get(self.alternate_environment_key)
500
+ )
501
+ return self._alternate_secret
502
+
503
+ def headers(self, retry_auth=False):
504
+ self._configured_guard()
505
+ if retry_auth:
506
+ self.clear_credential_cache()
507
+ return {"Authorization": f"{self.header_prefix}{self.secret}"}
508
+
509
+ def authenticate(self, input_output):
510
+ self._configured_guard()
511
+ auth_header = input_output.request_headers.authorization
512
+ if not auth_header:
513
+ return False
514
+ if auth_header[: self.header_prefix_length].lower() != self.header_prefix.lower():
515
+ # self._logging.debug(
516
+ # "Authentication failure due to prefix mismatch. Configured prefix: "
517
+ # + self._header_prefix.lower()
518
+ # + ". Found prefix: "
519
+ # + auth_header[: self._header_prefix_length].lower()
520
+ # )
521
+ return False
522
+ provided_secret = auth_header[self.header_prefix_length :]
523
+ if self.secret == provided_secret:
524
+ # self._logging.debug("Authentication success")
525
+ return True
526
+ if self.alternate_secret and provided_secret == self._alternate_secret:
527
+ # self._logging.debug("Authentication success with alternate secret")
528
+ return True
529
+ # self._logging.debug("Authentication failure due to secret mismatch")
530
+ return False
531
+
532
+ def authorize(self, authorization):
533
+ raise ValueError("SecretBearer does not support authorization")
534
+
535
+ def set_headers_for_cors(self, cors):
536
+ cors.add_header("Authorization")
537
+
538
+ def _configured_guard(self):
539
+ if not self.secret:
540
+ raise ValueError("Attempted to use SecretBearer authentication class without providing the configuration")
541
+
542
+ def documentation_request_parameters(self):
543
+ return []
544
+
545
+ def documentation_security_scheme(self):
546
+ return {
547
+ "type": "apiKey",
548
+ "name": "authorization",
549
+ "in": "header",
550
+ }
551
+
552
+ def documentation_security_scheme_name(self):
553
+ return self.documentation_security_name
@@ -0,0 +1,8 @@
1
+ from . import formats, request, response, schema
2
+
3
+ __all__ = [
4
+ "formats",
5
+ "request",
6
+ "response",
7
+ "schema",
8
+ ]
@@ -0,0 +1,5 @@
1
+ from . import oai3_json
2
+
3
+ __all__ = [
4
+ "oai3_json",
5
+ ]
@@ -0,0 +1,7 @@
1
+ from .oai3_json import Oai3Json
2
+ from .oai3_schema_resolver import OAI3SchemaResolver
3
+
4
+ __all__ = [
5
+ "OAI3SchemaResolver",
6
+ "Oai3Json",
7
+ ]
@@ -0,0 +1,87 @@
1
+ import json
2
+ from typing import Any
3
+
4
+ from .request import Request
5
+
6
+
7
+ class Oai3Json:
8
+ requests: Any = None
9
+ formatted: Any = None
10
+ models: Any = None
11
+ security_schemes: Any = None
12
+
13
+ def __init__(self, oai3_schema_resolver):
14
+ self.oai3_schema_resolver = oai3_schema_resolver
15
+ self.requests = []
16
+ self.formatted = []
17
+ self.models = {}
18
+
19
+ def set_requests(self, requests):
20
+ self.requests = requests
21
+ self.formatted = [self.format_request(request) for request in self.requests]
22
+
23
+ def set_components(self, components):
24
+ supported = ["models", "securitySchemes"]
25
+ for key in components.keys():
26
+ if key not in supported:
27
+ raise ValueError(
28
+ f"Attempt to set unsupported OpenAPI3.0 component which is not currently supported: {key}"
29
+ )
30
+ if "models" in components:
31
+ self.set_models(components["models"])
32
+ if "securitySchemes" in components:
33
+ self.set_security_schemes(components["securitySchemes"])
34
+
35
+ def set_models(self, models):
36
+ self.models = models
37
+
38
+ def set_security_schemes(self, security_schemes):
39
+ self.security_schemes = security_schemes
40
+
41
+ def format_request(self, request):
42
+ formatted_request = Request(self.oai3_schema_resolver)
43
+ formatted_request.set_request(request)
44
+ return formatted_request
45
+
46
+ def pretty(self, root_properties=None):
47
+ return self.as_string(pretty=True, root_properties=root_properties)
48
+
49
+ def compact(self, root_properties=None):
50
+ return self.as_string(pretty=False, root_properties=root_properties)
51
+
52
+ def as_string(self, pretty=False, root_properties=None):
53
+ data = self.convert()
54
+ if root_properties is not None:
55
+ data = {**data, **root_properties}
56
+ if pretty:
57
+ return json.dumps(data, indent=2, sort_keys=True)
58
+ return json.dumps(data)
59
+
60
+ def convert(self):
61
+ paths: dict[str, Any] = {}
62
+ for request in self.formatted:
63
+ absolute_path = "/" + request.relative_path.lstrip("/")
64
+ if absolute_path not in paths:
65
+ paths[absolute_path] = {}
66
+
67
+ path_data = request.convert()
68
+ for request_method, path_doc in path_data.items():
69
+ if request_method in paths[absolute_path]:
70
+ continue
71
+ paths[absolute_path][request_method] = path_doc
72
+
73
+ data: dict[str, Any] = {
74
+ "openapi": "3.0.0",
75
+ "paths": paths,
76
+ "components": {},
77
+ }
78
+
79
+ if self.models:
80
+ data["components"]["schemas"] = {
81
+ model_name: self.oai3_schema_resolver(model).convert() for (model_name, model) in self.models.items()
82
+ }
83
+
84
+ if self.security_schemes:
85
+ data["components"]["securitySchemes"] = {name: data for (name, data) in self.security_schemes.items()}
86
+
87
+ return data
@@ -0,0 +1,15 @@
1
+ from ... import schema as raw_schema
2
+ from . import schema as formatted_schema
3
+
4
+
5
+ class OAI3SchemaResolver:
6
+ class_map = {
7
+ raw_schema.Array: formatted_schema.Array,
8
+ raw_schema.Enum: formatted_schema.Enum,
9
+ raw_schema.Object: formatted_schema.Object,
10
+ }
11
+
12
+ def __call__(self, schema_object):
13
+ if schema_object.__class__ in self.class_map:
14
+ return self.class_map[schema_object.__class__](schema_object, self)
15
+ return formatted_schema.Default(schema_object)