forked from Unstructured-IO/unstructured-python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.py
More file actions
587 lines (519 loc) · 23.8 KB
/
users.py
File metadata and controls
587 lines (519 loc) · 23.8 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
# """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
# from .basesdk import BaseSDK
# from typing import Any, Mapping, Optional, Union, cast
# from unstructured_client import utils
# from unstructured_client._hooks import HookContext
# from unstructured_client.models import errors, operations, shared
# from unstructured_client.types import BaseModel, OptionalNullable, UNSET
# from unstructured_client.utils.unmarshal_json_response import unmarshal_json_response
# # region imports
# from cryptography import x509
# from cryptography.hazmat.primitives import serialization, hashes
# from cryptography.hazmat.primitives.asymmetric import padding, rsa
# from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
# from cryptography.hazmat.backends import default_backend
# import os
# import base64
# # endregion imports
# class Users(BaseSDK):
# # region sdk-class-body
# def _encrypt_rsa_aes(
# self,
# public_key: rsa.RSAPublicKey,
# plaintext: str,
# ) -> dict:
# # Generate a random AES key
# aes_key = os.urandom(32) # 256-bit AES key
# # Generate a random IV
# iv = os.urandom(16)
# # Encrypt using AES-CFB
# cipher = Cipher(
# algorithms.AES(aes_key),
# modes.CFB(iv),
# )
# encryptor = cipher.encryptor()
# ciphertext = encryptor.update(plaintext.encode("utf-8")) + encryptor.finalize()
# # Encrypt the AES key using the RSA public key
# encrypted_key = public_key.encrypt(
# aes_key,
# padding.OAEP(
# mgf=padding.MGF1(algorithm=hashes.SHA256()),
# algorithm=hashes.SHA256(),
# label=None,
# ),
# )
# return {
# "encrypted_aes_key": base64.b64encode(encrypted_key).decode("utf-8"),
# "aes_iv": base64.b64encode(iv).decode("utf-8"),
# "encrypted_value": base64.b64encode(ciphertext).decode("utf-8"),
# "type": "rsa_aes",
# }
# def _encrypt_rsa(
# self,
# public_key: rsa.RSAPublicKey,
# plaintext: str,
# ) -> dict:
# # Load public RSA key
# ciphertext = public_key.encrypt(
# plaintext.encode(),
# padding.OAEP(
# mgf=padding.MGF1(algorithm=hashes.SHA256()),
# algorithm=hashes.SHA256(),
# label=None,
# ),
# )
# return {
# "encrypted_value": base64.b64encode(ciphertext).decode("utf-8"),
# "type": "rsa",
# "encrypted_aes_key": "",
# "aes_iv": "",
# }
# def decrypt_secret(
# self,
# private_key_pem: str,
# encrypted_value: str,
# secret_type: str,
# encrypted_aes_key: str,
# aes_iv: str,
# ) -> str:
# private_key = serialization.load_pem_private_key(
# private_key_pem.encode("utf-8"), password=None, backend=default_backend()
# )
# if not isinstance(private_key, rsa.RSAPrivateKey):
# raise TypeError("Private key must be a RSA private key for decryption.")
# if secret_type == "rsa":
# ciphertext = base64.b64decode(encrypted_value)
# plaintext = private_key.decrypt(
# ciphertext,
# padding.OAEP(
# mgf=padding.MGF1(algorithm=hashes.SHA256()),
# algorithm=hashes.SHA256(),
# label=None,
# ),
# )
# return plaintext.decode("utf-8")
# # aes_rsa
# encrypted_aes_key_decoded = base64.b64decode(encrypted_aes_key)
# iv = base64.b64decode(aes_iv)
# ciphertext = base64.b64decode(encrypted_value)
# aes_key = private_key.decrypt(
# encrypted_aes_key_decoded,
# padding.OAEP(
# mgf=padding.MGF1(algorithm=hashes.SHA256()),
# algorithm=hashes.SHA256(),
# label=None,
# ),
# )
# cipher = Cipher(
# algorithms.AES(aes_key),
# modes.CFB(iv),
# )
# decryptor = cipher.decryptor()
# plaintext = decryptor.update(ciphertext) + decryptor.finalize()
# return plaintext.decode("utf-8")
# def encrypt_secret(
# self,
# encryption_cert_or_key_pem: str,
# plaintext: str,
# encryption_type: Optional[str] = None,
# ) -> dict:
# """
# Encrypts a plaintext string for securely sending to the Unstructured API.
# Args:
# encryption_cert_or_key_pem (str): A PEM-encoded RSA public key or certificate.
# plaintext (str): The string to encrypt.
# type (str, optional): Encryption type, either "rsa" or "rsa_aes".
# Returns:
# dict: A dictionary with encrypted AES key, iv, and ciphertext (all base64-encoded).
# """
# # If a cert is provided, extract the public key
# if "BEGIN CERTIFICATE" in encryption_cert_or_key_pem:
# cert = x509.load_pem_x509_certificate(
# encryption_cert_or_key_pem.encode("utf-8"),
# )
# public_key = cert.public_key() # type: ignore[assignment]
# else:
# public_key = serialization.load_pem_public_key(
# encryption_cert_or_key_pem.encode("utf-8"), backend=default_backend()
# ) # type: ignore[assignment]
# if not isinstance(public_key, rsa.RSAPublicKey):
# raise TypeError("Public key must be a RSA public key for encryption.")
# # If the plaintext is short, use RSA directly
# # Otherwise, use a RSA_AES envelope hybrid
# # Use the length of the public key to determine the encryption type
# key_size_bytes = public_key.key_size // 8
# max_rsa_length = key_size_bytes - 66 # OAEP SHA256 overhead
# if not encryption_type:
# encryption_type = "rsa" if len(plaintext) <= max_rsa_length else "rsa_aes"
# if encryption_type == "rsa":
# return self._encrypt_rsa(public_key, plaintext)
# return self._encrypt_rsa_aes(public_key, plaintext)
# # endregion sdk-class-body
# def get_encryption_certificate(
# self,
# *,
# request: Union[
# operations.GetEncryptionCertificateRequest,
# operations.GetEncryptionCertificateRequestTypedDict,
# ],
# retries: OptionalNullable[utils.RetryConfig] = UNSET,
# server_url: Optional[str] = None,
# timeout_ms: Optional[int] = None,
# http_headers: Optional[Mapping[str, str]] = None,
# ) -> operations.GetEncryptionCertificateResponse:
# r"""Retrieve the user's public key for encryption.
# Retrieve a short lived certificate with the public key for encrypting secrets.
# :param request: The request object to send.
# :param retries: Override the default retry configuration for this method
# :param server_url: Override the default server URL for this method
# :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
# :param http_headers: Additional headers to set or replace on requests.
# """
# base_url = None
# url_variables = None
# if timeout_ms is None:
# timeout_ms = self.sdk_configuration.timeout_ms
# if server_url is not None:
# base_url = server_url
# else:
# base_url = self._get_url(base_url, url_variables)
# if not isinstance(request, BaseModel):
# request = utils.unmarshal(
# request, operations.GetEncryptionCertificateRequest
# )
# request = cast(operations.GetEncryptionCertificateRequest, request)
# req = self._build_request(
# method="GET",
# path="/api/v1/users/secrets/encryption-certificate",
# base_url=base_url,
# url_variables=url_variables,
# request=request,
# request_body_required=False,
# request_has_path_params=False,
# request_has_query_params=True,
# user_agent_header="user-agent",
# accept_header_value="application/json",
# http_headers=http_headers,
# security=self.sdk_configuration.security,
# timeout_ms=timeout_ms,
# )
# if retries == UNSET:
# if self.sdk_configuration.retry_config is not UNSET:
# retries = self.sdk_configuration.retry_config
# else:
# retries = utils.RetryConfig(
# "backoff", utils.BackoffStrategy(3000, 720000, 1.88, 1800000), True
# )
# retry_config = None
# if isinstance(retries, utils.RetryConfig):
# retry_config = (retries, ["5xx"])
# http_res = self.do_request(
# hook_ctx=HookContext(
# config=self.sdk_configuration,
# base_url=base_url or "",
# operation_id="get_encryption_certificate",
# oauth2_scopes=[],
# security_source=self.sdk_configuration.security,
# ),
# request=req,
# error_status_codes=["422", "4XX", "5XX"],
# retry_config=retry_config,
# )
# response_data: Any = None
# if utils.match_response(http_res, "200", "application/json"):
# return operations.GetEncryptionCertificateResponse(
# encryption_certificate_response=unmarshal_json_response(
# Optional[shared.EncryptionCertificateResponse], http_res
# ),
# status_code=http_res.status_code,
# content_type=http_res.headers.get("Content-Type") or "",
# raw_response=http_res,
# )
# if utils.match_response(http_res, "422", "application/json"):
# response_data = unmarshal_json_response(
# errors.HTTPValidationErrorData, http_res
# )
# raise errors.HTTPValidationError(response_data, http_res)
# if utils.match_response(http_res, "4XX", "*"):
# http_res_text = utils.stream_to_text(http_res)
# raise errors.SDKError("API error occurred", http_res, http_res_text)
# if utils.match_response(http_res, "5XX", "*"):
# http_res_text = utils.stream_to_text(http_res)
# raise errors.SDKError("API error occurred", http_res, http_res_text)
# raise errors.SDKError("Unexpected response received", http_res)
# async def get_encryption_certificate_async(
# self,
# *,
# request: Union[
# operations.GetEncryptionCertificateRequest,
# operations.GetEncryptionCertificateRequestTypedDict,
# ],
# retries: OptionalNullable[utils.RetryConfig] = UNSET,
# server_url: Optional[str] = None,
# timeout_ms: Optional[int] = None,
# http_headers: Optional[Mapping[str, str]] = None,
# ) -> operations.GetEncryptionCertificateResponse:
# r"""Retrieve the user's public key for encryption.
# Retrieve a short lived certificate with the public key for encrypting secrets.
# :param request: The request object to send.
# :param retries: Override the default retry configuration for this method
# :param server_url: Override the default server URL for this method
# :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
# :param http_headers: Additional headers to set or replace on requests.
# """
# base_url = None
# url_variables = None
# if timeout_ms is None:
# timeout_ms = self.sdk_configuration.timeout_ms
# if server_url is not None:
# base_url = server_url
# else:
# base_url = self._get_url(base_url, url_variables)
# if not isinstance(request, BaseModel):
# request = utils.unmarshal(
# request, operations.GetEncryptionCertificateRequest
# )
# request = cast(operations.GetEncryptionCertificateRequest, request)
# req = self._build_request_async(
# method="GET",
# path="/api/v1/users/secrets/encryption-certificate",
# base_url=base_url,
# url_variables=url_variables,
# request=request,
# request_body_required=False,
# request_has_path_params=False,
# request_has_query_params=True,
# user_agent_header="user-agent",
# accept_header_value="application/json",
# http_headers=http_headers,
# security=self.sdk_configuration.security,
# timeout_ms=timeout_ms,
# )
# if retries == UNSET:
# if self.sdk_configuration.retry_config is not UNSET:
# retries = self.sdk_configuration.retry_config
# else:
# retries = utils.RetryConfig(
# "backoff", utils.BackoffStrategy(3000, 720000, 1.88, 1800000), True
# )
# retry_config = None
# if isinstance(retries, utils.RetryConfig):
# retry_config = (retries, ["5xx"])
# http_res = await self.do_request_async(
# hook_ctx=HookContext(
# config=self.sdk_configuration,
# base_url=base_url or "",
# operation_id="get_encryption_certificate",
# oauth2_scopes=[],
# security_source=self.sdk_configuration.security,
# ),
# request=req,
# error_status_codes=["422", "4XX", "5XX"],
# retry_config=retry_config,
# )
# response_data: Any = None
# if utils.match_response(http_res, "200", "application/json"):
# return operations.GetEncryptionCertificateResponse(
# encryption_certificate_response=unmarshal_json_response(
# Optional[shared.EncryptionCertificateResponse], http_res
# ),
# status_code=http_res.status_code,
# content_type=http_res.headers.get("Content-Type") or "",
# raw_response=http_res,
# )
# if utils.match_response(http_res, "422", "application/json"):
# response_data = unmarshal_json_response(
# errors.HTTPValidationErrorData, http_res
# )
# raise errors.HTTPValidationError(response_data, http_res)
# if utils.match_response(http_res, "4XX", "*"):
# http_res_text = await utils.stream_to_text_async(http_res)
# raise errors.SDKError("API error occurred", http_res, http_res_text)
# if utils.match_response(http_res, "5XX", "*"):
# http_res_text = await utils.stream_to_text_async(http_res)
# raise errors.SDKError("API error occurred", http_res, http_res_text)
# raise errors.SDKError("Unexpected response received", http_res)
# def store_secret(
# self,
# *,
# request: Union[
# operations.StoreSecretRequest, operations.StoreSecretRequestTypedDict
# ],
# retries: OptionalNullable[utils.RetryConfig] = UNSET,
# server_url: Optional[str] = None,
# timeout_ms: Optional[int] = None,
# http_headers: Optional[Mapping[str, str]] = None,
# ) -> operations.StoreSecretResponse:
# r"""Store an encrypted secret
# After encrypting a secret locally, store it and get back a reference id.
# :param request: The request object to send.
# :param retries: Override the default retry configuration for this method
# :param server_url: Override the default server URL for this method
# :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
# :param http_headers: Additional headers to set or replace on requests.
# """
# base_url = None
# url_variables = None
# if timeout_ms is None:
# timeout_ms = self.sdk_configuration.timeout_ms
# if server_url is not None:
# base_url = server_url
# else:
# base_url = self._get_url(base_url, url_variables)
# if not isinstance(request, BaseModel):
# request = utils.unmarshal(request, operations.StoreSecretRequest)
# request = cast(operations.StoreSecretRequest, request)
# req = self._build_request(
# method="POST",
# path="/api/v1/users/secrets",
# base_url=base_url,
# url_variables=url_variables,
# request=request,
# request_body_required=True,
# request_has_path_params=False,
# request_has_query_params=True,
# user_agent_header="user-agent",
# accept_header_value="application/json",
# http_headers=http_headers,
# security=self.sdk_configuration.security,
# get_serialized_body=lambda: utils.serialize_request_body(
# request.encrypted_secret, False, False, "json", shared.EncryptedSecret
# ),
# timeout_ms=timeout_ms,
# )
# if retries == UNSET:
# if self.sdk_configuration.retry_config is not UNSET:
# retries = self.sdk_configuration.retry_config
# else:
# retries = utils.RetryConfig(
# "backoff", utils.BackoffStrategy(3000, 720000, 1.88, 1800000), True
# )
# retry_config = None
# if isinstance(retries, utils.RetryConfig):
# retry_config = (retries, ["5xx"])
# http_res = self.do_request(
# hook_ctx=HookContext(
# config=self.sdk_configuration,
# base_url=base_url or "",
# operation_id="store_secret",
# oauth2_scopes=[],
# security_source=self.sdk_configuration.security,
# ),
# request=req,
# error_status_codes=["422", "4XX", "5XX"],
# retry_config=retry_config,
# )
# response_data: Any = None
# if utils.match_response(http_res, "200", "application/json"):
# return operations.StoreSecretResponse(
# secret_reference=unmarshal_json_response(
# Optional[shared.SecretReference], http_res
# ),
# status_code=http_res.status_code,
# content_type=http_res.headers.get("Content-Type") or "",
# raw_response=http_res,
# )
# if utils.match_response(http_res, "422", "application/json"):
# response_data = unmarshal_json_response(
# errors.HTTPValidationErrorData, http_res
# )
# raise errors.HTTPValidationError(response_data, http_res)
# if utils.match_response(http_res, "4XX", "*"):
# http_res_text = utils.stream_to_text(http_res)
# raise errors.SDKError("API error occurred", http_res, http_res_text)
# if utils.match_response(http_res, "5XX", "*"):
# http_res_text = utils.stream_to_text(http_res)
# raise errors.SDKError("API error occurred", http_res, http_res_text)
# raise errors.SDKError("Unexpected response received", http_res)
# async def store_secret_async(
# self,
# *,
# request: Union[
# operations.StoreSecretRequest, operations.StoreSecretRequestTypedDict
# ],
# retries: OptionalNullable[utils.RetryConfig] = UNSET,
# server_url: Optional[str] = None,
# timeout_ms: Optional[int] = None,
# http_headers: Optional[Mapping[str, str]] = None,
# ) -> operations.StoreSecretResponse:
# r"""Store an encrypted secret
# After encrypting a secret locally, store it and get back a reference id.
# :param request: The request object to send.
# :param retries: Override the default retry configuration for this method
# :param server_url: Override the default server URL for this method
# :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
# :param http_headers: Additional headers to set or replace on requests.
# """
# base_url = None
# url_variables = None
# if timeout_ms is None:
# timeout_ms = self.sdk_configuration.timeout_ms
# if server_url is not None:
# base_url = server_url
# else:
# base_url = self._get_url(base_url, url_variables)
# if not isinstance(request, BaseModel):
# request = utils.unmarshal(request, operations.StoreSecretRequest)
# request = cast(operations.StoreSecretRequest, request)
# req = self._build_request_async(
# method="POST",
# path="/api/v1/users/secrets",
# base_url=base_url,
# url_variables=url_variables,
# request=request,
# request_body_required=True,
# request_has_path_params=False,
# request_has_query_params=True,
# user_agent_header="user-agent",
# accept_header_value="application/json",
# http_headers=http_headers,
# security=self.sdk_configuration.security,
# get_serialized_body=lambda: utils.serialize_request_body(
# request.encrypted_secret, False, False, "json", shared.EncryptedSecret
# ),
# timeout_ms=timeout_ms,
# )
# if retries == UNSET:
# if self.sdk_configuration.retry_config is not UNSET:
# retries = self.sdk_configuration.retry_config
# else:
# retries = utils.RetryConfig(
# "backoff", utils.BackoffStrategy(3000, 720000, 1.88, 1800000), True
# )
# retry_config = None
# if isinstance(retries, utils.RetryConfig):
# retry_config = (retries, ["5xx"])
# http_res = await self.do_request_async(
# hook_ctx=HookContext(
# config=self.sdk_configuration,
# base_url=base_url or "",
# operation_id="store_secret",
# oauth2_scopes=[],
# security_source=self.sdk_configuration.security,
# ),
# request=req,
# error_status_codes=["422", "4XX", "5XX"],
# retry_config=retry_config,
# )
# response_data: Any = None
# if utils.match_response(http_res, "200", "application/json"):
# return operations.StoreSecretResponse(
# secret_reference=unmarshal_json_response(
# Optional[shared.SecretReference], http_res
# ),
# status_code=http_res.status_code,
# content_type=http_res.headers.get("Content-Type") or "",
# raw_response=http_res,
# )
# if utils.match_response(http_res, "422", "application/json"):
# response_data = unmarshal_json_response(
# errors.HTTPValidationErrorData, http_res
# )
# raise errors.HTTPValidationError(response_data, http_res)
# if utils.match_response(http_res, "4XX", "*"):
# http_res_text = await utils.stream_to_text_async(http_res)
# raise errors.SDKError("API error occurred", http_res, http_res_text)
# if utils.match_response(http_res, "5XX", "*"):
# http_res_text = await utils.stream_to_text_async(http_res)
# raise errors.SDKError("API error occurred", http_res, http_res_text)
# raise errors.SDKError("Unexpected response received", http_res)