volcengine-python-sdk-aicc 0.0.41__tar.gz

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.
Files changed (78) hide show
  1. volcengine_python_sdk_aicc-0.0.41/LICENSE +202 -0
  2. volcengine_python_sdk_aicc-0.0.41/PKG-INFO +79 -0
  3. volcengine_python_sdk_aicc-0.0.41/README.md +35 -0
  4. volcengine_python_sdk_aicc-0.0.41/bytedance/__init__.py +4 -0
  5. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/__init__.py +28 -0
  6. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/client.py +305 -0
  7. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/config.py +171 -0
  8. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/consts.py +5 -0
  9. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/crypto/__init__.py +14 -0
  10. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/crypto/aes.py +174 -0
  11. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/crypto/envelope.py +395 -0
  12. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/crypto/rsa.py +164 -0
  13. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/error.py +131 -0
  14. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/log/__init__.py +23 -0
  15. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/log/config.py +31 -0
  16. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/log/logger.py +88 -0
  17. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/logger_factory.py +134 -0
  18. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/ra.py +772 -0
  19. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/server.py +745 -0
  20. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/service/__init__.py +16 -0
  21. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/service/eps.py +133 -0
  22. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/service/eps_models.py +47 -0
  23. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/service/ras.py +88 -0
  24. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/service/tks.py +51 -0
  25. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/service/tks_models.py +334 -0
  26. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_channel/utils.py +469 -0
  27. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_model/model_automation_tool.py +181 -0
  28. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_model/model_encryption.py +416 -0
  29. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_model/model_hub_admin.py +116 -0
  30. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_model/pcc_utils.py +279 -0
  31. volcengine_python_sdk_aicc-0.0.41/bytedance/jeddak_secure_model/rds_utils.py +63 -0
  32. volcengine_python_sdk_aicc-0.0.41/bytedance/tks/attester.py +41 -0
  33. volcengine_python_sdk_aicc-0.0.41/bytedance/tks/client.py +629 -0
  34. volcengine_python_sdk_aicc-0.0.41/bytedance/tks/consts.py +122 -0
  35. volcengine_python_sdk_aicc-0.0.41/bytedance/tks/crypto/aes.py +47 -0
  36. volcengine_python_sdk_aicc-0.0.41/bytedance/tks/crypto/ec.py +39 -0
  37. volcengine_python_sdk_aicc-0.0.41/bytedance/tks/exceptions.py +22 -0
  38. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/__init__.py +14 -0
  39. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/aicc_client.py +277 -0
  40. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/aicc_inference.py +64 -0
  41. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/ark_inference_client.py +343 -0
  42. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/asr_inference_client.py +158 -0
  43. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/asr_websocket_client.py +705 -0
  44. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/auc_inference_client.py +305 -0
  45. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/__init__.py +0 -0
  46. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/aes.py +136 -0
  47. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/constant.py +4 -0
  48. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/error.py +21 -0
  49. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/log/__init__.py +24 -0
  50. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/log/config.py +31 -0
  51. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/log/logger.py +88 -0
  52. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/tos_utils.py +341 -0
  53. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/common/utils.py +45 -0
  54. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/cu_inference_client.py +292 -0
  55. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/deepseek_inference_client.py +501 -0
  56. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/secure_http_client.py +406 -0
  57. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/seedance_inference_client.py +500 -0
  58. volcengine_python_sdk_aicc-0.0.41/bytedance/volcengine_aicc_sdk/seedream_inference_client.py +213 -0
  59. volcengine_python_sdk_aicc-0.0.41/pyproject.toml +87 -0
  60. volcengine_python_sdk_aicc-0.0.41/setup.cfg +4 -0
  61. volcengine_python_sdk_aicc-0.0.41/setup.py +12 -0
  62. volcengine_python_sdk_aicc-0.0.41/tests/test_aicc_client.py +170 -0
  63. volcengine_python_sdk_aicc-0.0.41/tests/test_aicc_inference.py +98 -0
  64. volcengine_python_sdk_aicc-0.0.41/tests/test_ark_inference_client.py +424 -0
  65. volcengine_python_sdk_aicc-0.0.41/tests/test_asr_inference_client.py +380 -0
  66. volcengine_python_sdk_aicc-0.0.41/tests/test_asr_websocket_client.py +671 -0
  67. volcengine_python_sdk_aicc-0.0.41/tests/test_auc_inference_client.py +595 -0
  68. volcengine_python_sdk_aicc-0.0.41/tests/test_cu_inference_client.py +193 -0
  69. volcengine_python_sdk_aicc-0.0.41/tests/test_deepseek_inference_client.py +311 -0
  70. volcengine_python_sdk_aicc-0.0.41/tests/test_secure_http_client.py +239 -0
  71. volcengine_python_sdk_aicc-0.0.41/tests/test_seedance_inference_client.py +428 -0
  72. volcengine_python_sdk_aicc-0.0.41/tests/test_seedream_inference_client.py +491 -0
  73. volcengine_python_sdk_aicc-0.0.41/tests/test_tos_utils.py +329 -0
  74. volcengine_python_sdk_aicc-0.0.41/volcengine_python_sdk_aicc.egg-info/PKG-INFO +79 -0
  75. volcengine_python_sdk_aicc-0.0.41/volcengine_python_sdk_aicc.egg-info/SOURCES.txt +76 -0
  76. volcengine_python_sdk_aicc-0.0.41/volcengine_python_sdk_aicc.egg-info/dependency_links.txt +1 -0
  77. volcengine_python_sdk_aicc-0.0.41/volcengine_python_sdk_aicc.egg-info/requires.txt +22 -0
  78. volcengine_python_sdk_aicc-0.0.41/volcengine_python_sdk_aicc.egg-info/top_level.txt +1 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: volcengine-python-sdk-aicc
3
+ Version: 0.0.41
4
+ Summary: Volcengine AICC Python SDK for confidential and secure AI inference
5
+ Author-email: Volcengine AICC SDK Team <volcengine@bytedance.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://pypi.org/project/volcengine-python-sdk-aicc/
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Topic :: Security
18
+ Classifier: Topic :: Security :: Cryptography
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: cryptography<100,>=38.0.0
23
+ Requires-Dist: httpx<1,>=0.28
24
+ Requires-Dist: requests<100,>=2.22
25
+ Requires-Dist: typing_extensions~=4.12
26
+ Requires-Dist: tos~=2.8.1
27
+ Requires-Dist: msgpack~=1.0.8
28
+ Requires-Dist: huggingface_hub<1,>=0.23
29
+ Requires-Dist: loguru~=0.7.3
30
+ Requires-Dist: volcengine-python-sdk<=100,>=4.0.4
31
+ Requires-Dist: jwcrypto~=1.5.6
32
+ Requires-Dist: PyJWT>=2.9.0
33
+ Requires-Dist: pymerkle~=6.1.0
34
+ Requires-Dist: openai<=100,>=2.0.0
35
+ Requires-Dist: wget~=3.2
36
+ Requires-Dist: websocket-client<=100,>=1.8.0
37
+ Requires-Dist: anthropic<=100,>=0.100.0
38
+ Provides-Extra: test
39
+ Requires-Dist: coverage~=7.6; extra == "test"
40
+ Requires-Dist: pytest~=8.3; extra == "test"
41
+ Requires-Dist: pytest-mock~=3.14; extra == "test"
42
+ Requires-Dist: responses~=0.25; extra == "test"
43
+ Dynamic: license-file
44
+
45
+ # Volcengine AICC SDK for Python
46
+
47
+ The official Python SDK for Volcengine AICC, providing confidential and secure
48
+ AI inference clients (chat, vision, video generation, ASR, etc.) with remote
49
+ attestation verification.
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install volcengine-python-sdk-aicc
55
+ ```
56
+
57
+ The distribution name is `volcengine-python-sdk-aicc`; the Python import
58
+ package is `bytedance.volcengine_aicc_sdk`.
59
+
60
+ ## Quick start
61
+
62
+ ```python
63
+ from bytedance.volcengine_aicc_sdk import AICCClient
64
+ from bytedance.volcengine_aicc_sdk.secure_http_client import AICCConfig
65
+
66
+ client = AICCClient(config=AICCConfig(base_url="<YOUR_BASE_URL>", api_key="<YOUR_API_KEY>"))
67
+ ```
68
+
69
+ ## Project layout
70
+
71
+ - `bytedance.volcengine_aicc_sdk`: AICC inference clients.
72
+ - `bytedance.jeddak_secure_channel`: confidential-computing secure channel and
73
+ remote attestation report verification.
74
+ - `bytedance.jeddak_secure_model`: secure model helpers.
75
+ - `bytedance.tks`: trusted key service helpers.
76
+
77
+ ## License
78
+
79
+ Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,35 @@
1
+ # Volcengine AICC SDK for Python
2
+
3
+ The official Python SDK for Volcengine AICC, providing confidential and secure
4
+ AI inference clients (chat, vision, video generation, ASR, etc.) with remote
5
+ attestation verification.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install volcengine-python-sdk-aicc
11
+ ```
12
+
13
+ The distribution name is `volcengine-python-sdk-aicc`; the Python import
14
+ package is `bytedance.volcengine_aicc_sdk`.
15
+
16
+ ## Quick start
17
+
18
+ ```python
19
+ from bytedance.volcengine_aicc_sdk import AICCClient
20
+ from bytedance.volcengine_aicc_sdk.secure_http_client import AICCConfig
21
+
22
+ client = AICCClient(config=AICCConfig(base_url="<YOUR_BASE_URL>", api_key="<YOUR_API_KEY>"))
23
+ ```
24
+
25
+ ## Project layout
26
+
27
+ - `bytedance.volcengine_aicc_sdk`: AICC inference clients.
28
+ - `bytedance.jeddak_secure_channel`: confidential-computing secure channel and
29
+ remote attestation report verification.
30
+ - `bytedance.jeddak_secure_model`: secure model helpers.
31
+ - `bytedance.tks`: trusted key service helpers.
32
+
33
+ ## License
34
+
35
+ Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,4 @@
1
+ from pkgutil import extend_path
2
+
3
+ # Make "bytedance" a namespace package
4
+ __path__ = extend_path(__path__, __name__)
@@ -0,0 +1,28 @@
1
+ __all__ = [
2
+ "Client",
3
+ "ClientConfig",
4
+ "FileMode",
5
+ "RaRequest",
6
+ "RaResponse",
7
+ "ResponseKey",
8
+ "Server",
9
+ "ServerConfig",
10
+ "TksAppOptions",
11
+ "__version__",
12
+ ]
13
+
14
+ __version__ = "0.1.7.78"
15
+
16
+ from .client import Client
17
+ from .config import ClientConfig, ServerConfig
18
+ from .crypto import FileMode, ResponseKey
19
+ from .ra import RaRequest, RaResponse
20
+ # from .server import Server
21
+ from .service import TksAppOptions
22
+
23
+
24
+ def __getattr__(name: str) -> object:
25
+ if name == "Server":
26
+ from .server import Server
27
+ return Server
28
+ raise AttributeError(f"module {__name__} has no attribute {name}")
@@ -0,0 +1,305 @@
1
+ """
2
+ 数据发送方接口.
3
+ """
4
+
5
+ __all__ = ["Client"]
6
+
7
+ import base64
8
+ import json
9
+ import time
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from typing_extensions import TYPE_CHECKING, Dict, Optional, Tuple, Union
14
+
15
+ if TYPE_CHECKING:
16
+ from _typeshed import GenericPath
17
+ else:
18
+ GenericPath = str
19
+
20
+ from . import error
21
+ from .config import ClientConfig
22
+ from .crypto import ClientSessionKey, FileMode, PrivateKey, ResponseKey, AesKey
23
+ from .log import LogConfig, logger
24
+ from .ra import attest_server, generate_nonce
25
+ from .utils import RepeatTimer
26
+
27
+
28
+ @dataclass(eq=False)
29
+ class Client:
30
+ """
31
+ 数据发送方接口.
32
+
33
+ 本类的所有方法是线程安全的.
34
+ """
35
+
36
+ config: ClientConfig
37
+
38
+ session_key: Optional[ClientSessionKey] = field(init=False, default=None)
39
+
40
+ attest_timer: Optional[RepeatTimer] = field(init=False, default=None)
41
+
42
+ root_key_info: Dict[str, PrivateKey] = field(init=False, default_factory=dict)
43
+
44
+ last_ra_time: float = 0.0
45
+
46
+ def __post_init__(self):
47
+ try:
48
+ self._init_log()
49
+
50
+ if self.config.root_key_config:
51
+ self._root_key_parse()
52
+
53
+ # if self.config.attest_interval is not None:
54
+ # # 初始化客户端时,以当前时间作为最近活跃时间
55
+ # self.last_active_time = time.time()
56
+ # # 内置最小定时间隔配置,避免因用户的不当配置造成的高负荷
57
+ # self.attest_timer = timer = weak_repeat_timer(
58
+ # max(self.config.attest_interval, ClientConst.MIN_ATTEST_INTERVAL),
59
+ # self._attest_server_no_raise,
60
+ # )
61
+ # timer.start()
62
+
63
+ self._attest_server_no_raise()
64
+ except Exception as e:
65
+ logger.critical(f"__post_init__ failed, e={e}")
66
+
67
+ def _attest_server_no_raise(self):
68
+ logger.info("attest_server active")
69
+ try:
70
+ if not self.attest_server(None):
71
+ logger.error("ra attest failed, Please check your config !")
72
+ else:
73
+ self.last_ra_time = time.time()
74
+ logger.info("attest_server success")
75
+ except Exception as e:
76
+ logger.critical(f"Failed to attest server, {e}")
77
+
78
+ def attest_server(self, token: Optional[str] = None) -> bool:
79
+ """
80
+ 对数据接收方进行远程证明.
81
+ """
82
+ if self.config.pub_key_path:
83
+ with open(self.config.pub_key_path) as f:
84
+ public_pem = f.read()
85
+ logger.debug(f"read pub key success, pub_key={public_pem}")
86
+ self.session_key = ClientSessionKey.load(public_pem)
87
+ return True
88
+ else:
89
+ max_try_count = 3
90
+ count = 0
91
+
92
+ nonce = generate_nonce()
93
+ while count < max_try_count:
94
+ count += 1
95
+ ret, pub_key = attest_server(token, self.config, nonce)
96
+ if ret:
97
+ logger.info("ra attest success")
98
+ if pub_key:
99
+ logger.debug(f"get pub key success, pub_key={pub_key}")
100
+ self.session_key = ClientSessionKey.load(pub_key)
101
+ return True
102
+ else:
103
+ if pub_key and not self.config.attest_must:
104
+ logger.warning(f"ra attest failed, but get pub key success, pub_key={pub_key}")
105
+ self.session_key = ClientSessionKey.load(pub_key)
106
+ return True
107
+ else:
108
+ time.sleep(2)
109
+ logger.info("ra attest failed, try again...")
110
+
111
+ return False
112
+
113
+ def _get_key(self) -> ClientSessionKey:
114
+ # 线程安全: 将 session_key 字段保存为本地变量, 避免访问两次
115
+ key = self.session_key
116
+ if key is None:
117
+ raise error.KeyMissingError()
118
+ return key
119
+
120
+ def encrypt(self, plaintext: Union[str, bytes]) -> str:
121
+ """
122
+ 加密字符串或二进制数据.
123
+
124
+ Returns:
125
+ 信封加密数据.
126
+
127
+ Raises:
128
+ KeyMissingError: 没有可用的密钥. 应通过 `attest_server` 验证数据接收方, 并获取密钥.
129
+ """
130
+ message, _ = self.encrypt_with_response(plaintext)
131
+ return message
132
+
133
+ def encrypt_with_response(
134
+ self, plaintext: Union[str, bytes], aes_key: AesKey = None
135
+ ) -> Tuple[str, ResponseKey]:
136
+ """
137
+ 加密字符串或二进制数据, 并获取用于解密响应的密钥.
138
+
139
+ Returns:
140
+ 信封加密数据, 及用于解密响应的密钥.
141
+
142
+ Raises:
143
+ KeyMissingError: 没有可用的密钥. 应通过 `attest_server` 验证数据接收方, 并获取密钥.
144
+ """
145
+ try:
146
+ if (
147
+ self.config.attest_interval is not None
148
+ and time.time() - self.last_ra_time > self.config.attest_interval
149
+ ):
150
+ self._attest_server_no_raise()
151
+
152
+ message, response_key = self._get_key().encrypt_with_response(plaintext, aes_key)
153
+ return message.serialize(), response_key
154
+ except error.KeyMissingError as e:
155
+ raise e
156
+ except Exception as e:
157
+ raise error.EncryptionError(
158
+ "Encrypt failed, Please check your config"
159
+ ) from e
160
+
161
+ def encrypt_file(
162
+ self,
163
+ source_path: GenericPath,
164
+ dest_path: GenericPath,
165
+ mode: FileMode,
166
+ ) -> str:
167
+ """
168
+ 加密文件数据.
169
+
170
+ Returns:
171
+ 信封加密元数据. 可伴随加密文件发送给数据接收方.
172
+ """
173
+ metadata, _ = self.encrypt_file_with_response(source_path, dest_path, mode)
174
+ return metadata
175
+
176
+ def encrypt_file_with_response(
177
+ self,
178
+ source_path: GenericPath,
179
+ dest_path: GenericPath,
180
+ mode: FileMode,
181
+ ) -> Tuple[str, ResponseKey]:
182
+ """
183
+ 加密文件数据, 并获取用于解密响应的密钥.
184
+
185
+ Returns:
186
+ 信封加密元数据, 及用于解密响应的密钥. 其中元数据可伴随加密文件发送给数据接收方.
187
+ """
188
+ if (
189
+ self.config.attest_interval is not None
190
+ and time.time() - self.last_ra_time > self.config.attest_interval
191
+ ):
192
+ self._attest_server_no_raise()
193
+
194
+ if mode not in ["b", "t"]:
195
+ raise error.ParamError("mode", "Mode should be 'b' or 't'")
196
+
197
+ try:
198
+ key = self._get_key()
199
+ with open(source_path, f"r{mode}") as source, open(
200
+ dest_path, f"w{mode}"
201
+ ) as dest:
202
+ metadata, response_key = key.encrypt_stream_with_response(
203
+ source, dest, mode
204
+ )
205
+
206
+ return metadata.serialize(), response_key
207
+ except error.KeyMissingError as e:
208
+ raise e
209
+ except Exception as e:
210
+ raise error.EncryptionError(
211
+ "Encrypt file failed, Please check your config"
212
+ ) from e
213
+
214
+ def _root_key_parse(self):
215
+ try:
216
+ root_key_config = self.config.root_key_config
217
+ if not root_key_config:
218
+ return
219
+
220
+ if isinstance(root_key_config, str):
221
+ root_key_config = json.loads(root_key_config)
222
+
223
+ for app_info, pri_key_path in root_key_config.items():
224
+ with open(pri_key_path) as f:
225
+ private_pem = f.read()
226
+ self.root_key_info[app_info] = PrivateKey.from_private_pem(private_pem)
227
+
228
+ logger.info("root_key_parse success")
229
+ except Exception as e:
230
+ logger.critical("root_key_parse exception={}".format(e))
231
+ raise error.ConfigError("RootKey conf", "RootPriKey conf error")
232
+
233
+ def gen_sign(self, app_info: str, msg: Union[str, bytes]) -> str:
234
+ """
235
+ 生成签名
236
+ :param app_info: app_id+app_name
237
+ :param msg: app_id+app_name
238
+ :return:
239
+ """
240
+ try:
241
+ if not app_info or not msg:
242
+ logger.error("gen_sign error, app_info is NULL")
243
+ raise error.SignatureError("RSA signing failed") from None
244
+
245
+ if app_info not in self.root_key_info:
246
+ logger.info(
247
+ f"gen_sign error, can not find app_info in root key conf, app_info={app_info}"
248
+ )
249
+ raise error.SignatureError(
250
+ f"can not find app_info={app_info}"
251
+ ) from None
252
+
253
+ return base64.b64encode(self.root_key_info[app_info].sign(msg)).decode()
254
+
255
+ except Exception as e:
256
+ logger.critical("gen_sign exception={}".format(e))
257
+ raise error.SignatureError("can not find app_info") from e
258
+
259
+ # def dynamic_update_interval(self):
260
+ # """
261
+ # 动态更新定时逻辑的时间间隔。对不活跃的客户端,增大其定时逻辑的时间间隔
262
+ # """
263
+ # try:
264
+ # # 对于非定时RA的客户端,不做动态更新
265
+ # if self.config.attest_interval is None or self.attest_timer is None:
266
+ # return
267
+ #
268
+ # # 如果超过一定时间没有活跃,就增大定时逻辑的时间间隔
269
+ # if time.time() - self.last_active_time > ClientConst.INACTIVE_THRESHOLD:
270
+ # self.attest_timer.interval = max(
271
+ # self.config.attest_interval, ClientConst.INACTIVE_ATTEST_INTERVAL
272
+ # )
273
+ # else:
274
+ # # 如果活跃时间在阈值内,就恢复初始的时间间隔
275
+ # self.attest_timer.interval = max(
276
+ # self.config.attest_interval, ClientConst.MIN_ATTEST_INTERVAL
277
+ # )
278
+ # except Exception as e:
279
+ # logger.error("dynamic_update_interval exception={}".format(e))
280
+
281
+ def _init_log(self):
282
+ config = LogConfig()
283
+
284
+ log_config: Dict[str, Any] = {}
285
+ if self.config.log_config:
286
+ log_config = json.loads(self.config.log_config)
287
+
288
+ if dir := log_config.get("dir"):
289
+ config.dir = dir
290
+
291
+ if filename := log_config.get("filename"):
292
+ config.filename = filename
293
+ # else:
294
+ # config.filename = "client.log"
295
+
296
+ if rotation := log_config.get("rotation"):
297
+ config.rotation = rotation
298
+
299
+ if retention := log_config.get("retention"):
300
+ config.retention = retention
301
+
302
+ if level := log_config.get("level"):
303
+ config.level = level
304
+
305
+ logger.init_log_config(config)