chitin-engine-lib 0.1.0__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.
- chitin_engine_lib-0.1.0/LICENSE +202 -0
- chitin_engine_lib-0.1.0/PKG-INFO +9 -0
- chitin_engine_lib-0.1.0/README.md +1 -0
- chitin_engine_lib-0.1.0/chitin/__init__.py +6 -0
- chitin_engine_lib-0.1.0/chitin/_engine.py +132 -0
- chitin_engine_lib-0.1.0/chitin/_ffi.py +320 -0
- chitin_engine_lib-0.1.0/chitin/_http.py +135 -0
- chitin_engine_lib-0.1.0/chitin/_resolve.py +66 -0
- chitin_engine_lib-0.1.0/chitin/_types.py +41 -0
- chitin_engine_lib-0.1.0/chitin/py.typed +1 -0
- chitin_engine_lib-0.1.0/chitin_engine_lib.egg-info/PKG-INFO +9 -0
- chitin_engine_lib-0.1.0/chitin_engine_lib.egg-info/SOURCES.txt +18 -0
- chitin_engine_lib-0.1.0/chitin_engine_lib.egg-info/dependency_links.txt +1 -0
- chitin_engine_lib-0.1.0/chitin_engine_lib.egg-info/top_level.txt +1 -0
- chitin_engine_lib-0.1.0/pyproject.toml +17 -0
- chitin_engine_lib-0.1.0/setup.cfg +4 -0
- chitin_engine_lib-0.1.0/setup_platform.py +24 -0
- chitin_engine_lib-0.1.0/tests/test_engine_fallback.py +27 -0
- chitin_engine_lib-0.1.0/tests/test_engine_http.py +27 -0
- chitin_engine_lib-0.1.0/tests/test_types.py +39 -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 2026, Andrew Long (datagoboom)
|
|
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,9 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: chitin-engine-lib
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python bindings for the Chitin security engine
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Project-URL: Repository, https://github.com/datagoboom/chitin-engine-lib
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Chitin Engine Library
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Chitin security engine – Python bindings (FFI + HTTP sidecar fallback)."""
|
|
2
|
+
|
|
3
|
+
from chitin._engine import Engine
|
|
4
|
+
from chitin._types import ChitinError, Decision, ExplainResult, TrustLevel
|
|
5
|
+
|
|
6
|
+
__all__ = ["Engine", "Decision", "ExplainResult", "TrustLevel", "ChitinError"]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Engine class: dispatches to FFI or HTTP backend."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from chitin._types import ChitinError, Decision, ExplainResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Engine:
|
|
10
|
+
"""
|
|
11
|
+
Chitin security engine. Uses the native library if available,
|
|
12
|
+
otherwise the sidecar at CHITIN_SIDECAR_URL.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, config_path: str | None = None) -> None:
|
|
16
|
+
"""Create engine. None = default config (embedded policies only)."""
|
|
17
|
+
self._backend: str = "none"
|
|
18
|
+
self._ffi: Any = None
|
|
19
|
+
self._handle: Any = None
|
|
20
|
+
self._http: Any = None
|
|
21
|
+
|
|
22
|
+
# 1. Try FFI
|
|
23
|
+
try:
|
|
24
|
+
from chitin import _ffi
|
|
25
|
+
ffi = _ffi.load_ffi()
|
|
26
|
+
handle = ffi.engine_new(config_path)
|
|
27
|
+
self._ffi = ffi
|
|
28
|
+
self._handle = handle
|
|
29
|
+
self._backend = "ffi"
|
|
30
|
+
return
|
|
31
|
+
except (ChitinError, OSError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
# 2. Fall back to HTTP sidecar
|
|
35
|
+
url = os.environ.get("CHITIN_SIDECAR_URL")
|
|
36
|
+
if url:
|
|
37
|
+
from chitin import _http
|
|
38
|
+
self._http = _http._ChitinHTTP(url)
|
|
39
|
+
self._backend = "http"
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
raise ChitinError(
|
|
43
|
+
-1,
|
|
44
|
+
"Chitin engine unavailable: native library failed to load and CHITIN_SIDECAR_URL is not set.",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def _ensure_open(self) -> None:
|
|
48
|
+
if self._backend == "none":
|
|
49
|
+
raise ChitinError(-1, "Engine is closed")
|
|
50
|
+
|
|
51
|
+
def ingest(
|
|
52
|
+
self,
|
|
53
|
+
content: str,
|
|
54
|
+
trust_level: int,
|
|
55
|
+
metadata: dict | None = None,
|
|
56
|
+
) -> int:
|
|
57
|
+
"""Record a message. Returns event_id."""
|
|
58
|
+
self._ensure_open()
|
|
59
|
+
if self._backend == "ffi":
|
|
60
|
+
return self._ffi.ingest(self._handle, content, trust_level, metadata)
|
|
61
|
+
return self._http.ingest(content, trust_level, metadata)
|
|
62
|
+
|
|
63
|
+
def propose(
|
|
64
|
+
self,
|
|
65
|
+
tool: str,
|
|
66
|
+
params: str,
|
|
67
|
+
agent_id: str | None = None,
|
|
68
|
+
input_sources: list[int] | None = None,
|
|
69
|
+
) -> Decision:
|
|
70
|
+
"""Propose a tool call. Returns Decision (never raises for deny/escalate)."""
|
|
71
|
+
self._ensure_open()
|
|
72
|
+
if self._backend == "ffi":
|
|
73
|
+
return self._ffi.propose(
|
|
74
|
+
self._handle, tool, params, agent_id, input_sources
|
|
75
|
+
)
|
|
76
|
+
return self._http.propose(tool, params, agent_id, input_sources)
|
|
77
|
+
|
|
78
|
+
def record_result(
|
|
79
|
+
self,
|
|
80
|
+
tool_call_id: int,
|
|
81
|
+
output: str,
|
|
82
|
+
exit_code: int = 0,
|
|
83
|
+
) -> int:
|
|
84
|
+
"""Record tool result. Returns event_id."""
|
|
85
|
+
self._ensure_open()
|
|
86
|
+
if self._backend == "ffi":
|
|
87
|
+
return self._ffi.record_result(
|
|
88
|
+
self._handle, tool_call_id, output, exit_code
|
|
89
|
+
)
|
|
90
|
+
return self._http.record_result(tool_call_id, output, exit_code)
|
|
91
|
+
|
|
92
|
+
def is_traced(self, event_id: int, label: str) -> bool:
|
|
93
|
+
"""Check if event traces to a label."""
|
|
94
|
+
self._ensure_open()
|
|
95
|
+
if self._backend == "ffi":
|
|
96
|
+
return self._ffi.is_traced(self._handle, event_id, label)
|
|
97
|
+
return self._http.is_traced(event_id, label)
|
|
98
|
+
|
|
99
|
+
def explain(self, event_id: int) -> ExplainResult:
|
|
100
|
+
"""Get trace chain and explanation for an event."""
|
|
101
|
+
self._ensure_open()
|
|
102
|
+
if self._backend == "ffi":
|
|
103
|
+
return self._ffi.explain(self._handle, event_id)
|
|
104
|
+
return self._http.explain(event_id)
|
|
105
|
+
|
|
106
|
+
def register_tool(
|
|
107
|
+
self,
|
|
108
|
+
name: str,
|
|
109
|
+
risk: str = "medium",
|
|
110
|
+
category: str | None = None,
|
|
111
|
+
) -> None:
|
|
112
|
+
"""Register a tool with risk level and optional category."""
|
|
113
|
+
self._ensure_open()
|
|
114
|
+
if self._backend == "ffi":
|
|
115
|
+
self._ffi.register_tool(self._handle, name, risk, category)
|
|
116
|
+
else:
|
|
117
|
+
self._http.register_tool(name, risk, category)
|
|
118
|
+
|
|
119
|
+
def close(self) -> None:
|
|
120
|
+
"""Destroy engine. Do not use after calling this."""
|
|
121
|
+
if self._backend == "ffi" and self._handle is not None:
|
|
122
|
+
self._ffi.engine_free(self._handle)
|
|
123
|
+
self._handle = None
|
|
124
|
+
self._backend = "none"
|
|
125
|
+
self._ffi = None
|
|
126
|
+
self._http = None
|
|
127
|
+
|
|
128
|
+
def __enter__(self) -> "Engine":
|
|
129
|
+
return self
|
|
130
|
+
|
|
131
|
+
def __exit__(self, *args: Any) -> None:
|
|
132
|
+
self.close()
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""ctypes bindings to the chitin C ABI (chitin.h)."""
|
|
2
|
+
|
|
3
|
+
import ctypes
|
|
4
|
+
from ctypes import POINTER, c_char_p, c_int32, c_uint64, c_void_p, c_size_t
|
|
5
|
+
|
|
6
|
+
from chitin._resolve import resolve_chitin_lib, _load_lib_error_message
|
|
7
|
+
from chitin._types import ChitinError, Decision, ExplainResult
|
|
8
|
+
|
|
9
|
+
# Status codes from chitin.h
|
|
10
|
+
CHITIN_OK = 0
|
|
11
|
+
CHITIN_ERR_INVALID = -1
|
|
12
|
+
CHITIN_ERR_DENIED = -2
|
|
13
|
+
CHITIN_ERR_ESCALATED = -3
|
|
14
|
+
CHITIN_ERR_INTERNAL = -4
|
|
15
|
+
CHITIN_ERR_NOT_FOUND = -5
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _to_buf(s: str | None) -> tuple[bytes | None, int]:
|
|
19
|
+
if s is None:
|
|
20
|
+
return None, 0
|
|
21
|
+
b = s.encode("utf-8")
|
|
22
|
+
return b, len(b)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _load_lib() -> ctypes.CDLL:
|
|
26
|
+
path = resolve_chitin_lib()
|
|
27
|
+
try:
|
|
28
|
+
return ctypes.CDLL(path)
|
|
29
|
+
except OSError as e:
|
|
30
|
+
raise OSError(_load_lib_error_message()) from e
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _ChitinFFI:
|
|
34
|
+
"""Holds the loaded library and wraps C ABI calls."""
|
|
35
|
+
|
|
36
|
+
def __init__(self) -> None:
|
|
37
|
+
self._lib = _load_lib()
|
|
38
|
+
self._setup_signatures()
|
|
39
|
+
|
|
40
|
+
def _setup_signatures(self) -> None:
|
|
41
|
+
lib = self._lib
|
|
42
|
+
|
|
43
|
+
# chitin_engine_t chitin_engine_new(const char* config_path, size_t config_path_len);
|
|
44
|
+
lib.chitin_engine_new.argtypes = [c_char_p, c_size_t]
|
|
45
|
+
lib.chitin_engine_new.restype = c_void_p
|
|
46
|
+
|
|
47
|
+
# void chitin_engine_free(chitin_engine_t engine);
|
|
48
|
+
lib.chitin_engine_free.argtypes = [c_void_p]
|
|
49
|
+
lib.chitin_engine_free.restype = None
|
|
50
|
+
|
|
51
|
+
# chitin_status_t chitin_ingest(...);
|
|
52
|
+
lib.chitin_ingest.argtypes = [
|
|
53
|
+
c_void_p,
|
|
54
|
+
c_char_p,
|
|
55
|
+
c_size_t,
|
|
56
|
+
c_int32,
|
|
57
|
+
c_char_p,
|
|
58
|
+
c_size_t,
|
|
59
|
+
POINTER(c_uint64),
|
|
60
|
+
]
|
|
61
|
+
lib.chitin_ingest.restype = c_int32
|
|
62
|
+
|
|
63
|
+
# chitin_status_t chitin_propose(...);
|
|
64
|
+
lib.chitin_propose.argtypes = [
|
|
65
|
+
c_void_p,
|
|
66
|
+
c_char_p,
|
|
67
|
+
c_size_t,
|
|
68
|
+
c_char_p,
|
|
69
|
+
c_size_t,
|
|
70
|
+
c_char_p,
|
|
71
|
+
c_size_t,
|
|
72
|
+
POINTER(c_uint64),
|
|
73
|
+
c_size_t,
|
|
74
|
+
POINTER(c_uint64),
|
|
75
|
+
]
|
|
76
|
+
lib.chitin_propose.restype = c_int32
|
|
77
|
+
|
|
78
|
+
# chitin_status_t chitin_record_result(...);
|
|
79
|
+
lib.chitin_record_result.argtypes = [
|
|
80
|
+
c_void_p,
|
|
81
|
+
c_uint64,
|
|
82
|
+
c_char_p,
|
|
83
|
+
c_size_t,
|
|
84
|
+
c_int32,
|
|
85
|
+
POINTER(c_uint64),
|
|
86
|
+
]
|
|
87
|
+
lib.chitin_record_result.restype = c_int32
|
|
88
|
+
|
|
89
|
+
# chitin_status_t chitin_is_traced(...);
|
|
90
|
+
lib.chitin_is_traced.argtypes = [
|
|
91
|
+
c_void_p,
|
|
92
|
+
c_uint64,
|
|
93
|
+
c_char_p,
|
|
94
|
+
c_size_t,
|
|
95
|
+
POINTER(c_int32),
|
|
96
|
+
]
|
|
97
|
+
lib.chitin_is_traced.restype = c_int32
|
|
98
|
+
|
|
99
|
+
# chitin_status_t chitin_explain(...);
|
|
100
|
+
lib.chitin_explain.argtypes = [
|
|
101
|
+
c_void_p,
|
|
102
|
+
c_uint64,
|
|
103
|
+
POINTER(c_char_p),
|
|
104
|
+
POINTER(c_size_t),
|
|
105
|
+
]
|
|
106
|
+
lib.chitin_explain.restype = c_int32
|
|
107
|
+
|
|
108
|
+
# chitin_status_t chitin_last_error(char** out_json, size_t* out_json_len);
|
|
109
|
+
lib.chitin_last_error.argtypes = [POINTER(c_char_p), POINTER(c_size_t)]
|
|
110
|
+
lib.chitin_last_error.restype = c_int32
|
|
111
|
+
|
|
112
|
+
# void chitin_free_string(char* ptr, size_t len);
|
|
113
|
+
lib.chitin_free_string.argtypes = [c_char_p, c_size_t]
|
|
114
|
+
lib.chitin_free_string.restype = None
|
|
115
|
+
|
|
116
|
+
# chitin_status_t chitin_register_tool(...);
|
|
117
|
+
lib.chitin_register_tool.argtypes = [
|
|
118
|
+
c_void_p,
|
|
119
|
+
c_char_p,
|
|
120
|
+
c_size_t,
|
|
121
|
+
c_char_p,
|
|
122
|
+
c_size_t,
|
|
123
|
+
]
|
|
124
|
+
lib.chitin_register_tool.restype = c_int32
|
|
125
|
+
|
|
126
|
+
def _last_error(self) -> str:
|
|
127
|
+
out_json = c_char_p()
|
|
128
|
+
out_len = c_size_t(0)
|
|
129
|
+
st = self._lib.chitin_last_error(ctypes.byref(out_json), ctypes.byref(out_len))
|
|
130
|
+
if st == CHITIN_ERR_NOT_FOUND or out_json.value is None:
|
|
131
|
+
return "unknown error"
|
|
132
|
+
try:
|
|
133
|
+
raw = ctypes.string_at(out_json.value, out_len.value)
|
|
134
|
+
return raw.decode("utf-8")
|
|
135
|
+
finally:
|
|
136
|
+
self._lib.chitin_free_string(out_json.value, out_len.value)
|
|
137
|
+
|
|
138
|
+
def engine_new(self, config_path: str | None) -> c_void_p:
|
|
139
|
+
path_buf, path_len = _to_buf(config_path)
|
|
140
|
+
engine = self._lib.chitin_engine_new(path_buf, path_len or 0)
|
|
141
|
+
if engine is None:
|
|
142
|
+
raise ChitinError(CHITIN_ERR_INTERNAL, self._last_error())
|
|
143
|
+
return engine
|
|
144
|
+
|
|
145
|
+
def engine_free(self, engine: c_void_p) -> None:
|
|
146
|
+
self._lib.chitin_engine_free(engine)
|
|
147
|
+
|
|
148
|
+
def ingest(
|
|
149
|
+
self,
|
|
150
|
+
engine: c_void_p,
|
|
151
|
+
content: str,
|
|
152
|
+
trust_level: int,
|
|
153
|
+
metadata: dict | None,
|
|
154
|
+
) -> int:
|
|
155
|
+
content_buf, content_len = _to_buf(content)
|
|
156
|
+
meta_str = None
|
|
157
|
+
meta_len = 0
|
|
158
|
+
if metadata is not None:
|
|
159
|
+
import json
|
|
160
|
+
meta_str = json.dumps(metadata)
|
|
161
|
+
meta_buf, meta_len = _to_buf(meta_str)
|
|
162
|
+
else:
|
|
163
|
+
meta_buf = None
|
|
164
|
+
out_id = c_uint64(0)
|
|
165
|
+
st = self._lib.chitin_ingest(
|
|
166
|
+
engine,
|
|
167
|
+
content_buf,
|
|
168
|
+
content_len,
|
|
169
|
+
c_int32(trust_level),
|
|
170
|
+
meta_buf,
|
|
171
|
+
meta_len,
|
|
172
|
+
ctypes.byref(out_id),
|
|
173
|
+
)
|
|
174
|
+
if st != CHITIN_OK:
|
|
175
|
+
raise ChitinError(st, self._last_error())
|
|
176
|
+
return out_id.value
|
|
177
|
+
|
|
178
|
+
def propose(
|
|
179
|
+
self,
|
|
180
|
+
engine: c_void_p,
|
|
181
|
+
tool: str,
|
|
182
|
+
params: str,
|
|
183
|
+
agent_id: str | None,
|
|
184
|
+
input_sources: list[int] | None,
|
|
185
|
+
) -> Decision:
|
|
186
|
+
tool_buf, tool_len = _to_buf(tool)
|
|
187
|
+
params_buf, params_len = _to_buf(params)
|
|
188
|
+
agent_buf, agent_len = _to_buf(agent_id)
|
|
189
|
+
sources_arr = None
|
|
190
|
+
sources_len = 0
|
|
191
|
+
if input_sources:
|
|
192
|
+
arr_type = c_uint64 * len(input_sources)
|
|
193
|
+
sources_arr = arr_type(*input_sources)
|
|
194
|
+
sources_len = len(input_sources)
|
|
195
|
+
out_id = c_uint64(0)
|
|
196
|
+
st = self._lib.chitin_propose(
|
|
197
|
+
engine,
|
|
198
|
+
tool_buf,
|
|
199
|
+
tool_len,
|
|
200
|
+
params_buf,
|
|
201
|
+
params_len,
|
|
202
|
+
agent_buf,
|
|
203
|
+
agent_len,
|
|
204
|
+
sources_arr,
|
|
205
|
+
sources_len,
|
|
206
|
+
ctypes.byref(out_id),
|
|
207
|
+
)
|
|
208
|
+
if st == CHITIN_OK:
|
|
209
|
+
return Decision(allowed=True, outcome="allow", event_id=out_id.value, rule_id=None, reason=None)
|
|
210
|
+
if st in (CHITIN_ERR_DENIED, CHITIN_ERR_ESCALATED):
|
|
211
|
+
err_json = self._last_error()
|
|
212
|
+
import json
|
|
213
|
+
try:
|
|
214
|
+
obj = json.loads(err_json)
|
|
215
|
+
rule_id = obj.get("rule_id")
|
|
216
|
+
reason = obj.get("reason", "")
|
|
217
|
+
except Exception:
|
|
218
|
+
rule_id = None
|
|
219
|
+
reason = err_json
|
|
220
|
+
outcome = "deny" if st == CHITIN_ERR_DENIED else "escalate"
|
|
221
|
+
return Decision(
|
|
222
|
+
allowed=False,
|
|
223
|
+
outcome=outcome,
|
|
224
|
+
event_id=out_id.value,
|
|
225
|
+
rule_id=rule_id,
|
|
226
|
+
reason=reason,
|
|
227
|
+
)
|
|
228
|
+
raise ChitinError(st, self._last_error())
|
|
229
|
+
|
|
230
|
+
def record_result(
|
|
231
|
+
self,
|
|
232
|
+
engine: c_void_p,
|
|
233
|
+
tool_call_id: int,
|
|
234
|
+
output: str,
|
|
235
|
+
exit_code: int,
|
|
236
|
+
) -> int:
|
|
237
|
+
out_buf, out_len = _to_buf(output)
|
|
238
|
+
out_id = c_uint64(0)
|
|
239
|
+
st = self._lib.chitin_record_result(
|
|
240
|
+
engine,
|
|
241
|
+
c_uint64(tool_call_id),
|
|
242
|
+
out_buf,
|
|
243
|
+
out_len,
|
|
244
|
+
c_int32(exit_code),
|
|
245
|
+
ctypes.byref(out_id),
|
|
246
|
+
)
|
|
247
|
+
if st != CHITIN_OK:
|
|
248
|
+
raise ChitinError(st, self._last_error())
|
|
249
|
+
return out_id.value
|
|
250
|
+
|
|
251
|
+
def is_traced(self, engine: c_void_p, event_id: int, label: str) -> bool:
|
|
252
|
+
label_buf, label_len = _to_buf(label)
|
|
253
|
+
out_result = c_int32(0)
|
|
254
|
+
st = self._lib.chitin_is_traced(
|
|
255
|
+
engine,
|
|
256
|
+
c_uint64(event_id),
|
|
257
|
+
label_buf,
|
|
258
|
+
label_len,
|
|
259
|
+
ctypes.byref(out_result),
|
|
260
|
+
)
|
|
261
|
+
if st != CHITIN_OK:
|
|
262
|
+
raise ChitinError(st, self._last_error())
|
|
263
|
+
return out_result.value != 0
|
|
264
|
+
|
|
265
|
+
def explain(self, engine: c_void_p, event_id: int) -> ExplainResult:
|
|
266
|
+
out_json = c_char_p()
|
|
267
|
+
out_len = c_size_t(0)
|
|
268
|
+
st = self._lib.chitin_explain(
|
|
269
|
+
engine,
|
|
270
|
+
c_uint64(event_id),
|
|
271
|
+
ctypes.byref(out_json),
|
|
272
|
+
ctypes.byref(out_len),
|
|
273
|
+
)
|
|
274
|
+
if st != CHITIN_OK:
|
|
275
|
+
raise ChitinError(st, self._last_error())
|
|
276
|
+
if out_json.value is None or out_len.value == 0:
|
|
277
|
+
return ExplainResult(text="", trace_chain=[])
|
|
278
|
+
try:
|
|
279
|
+
raw = ctypes.string_at(out_json.value, out_len.value)
|
|
280
|
+
text = raw.decode("utf-8")
|
|
281
|
+
finally:
|
|
282
|
+
self._lib.chitin_free_string(out_json.value, out_len.value)
|
|
283
|
+
import json
|
|
284
|
+
try:
|
|
285
|
+
obj = json.loads(text)
|
|
286
|
+
return ExplainResult(
|
|
287
|
+
text=obj.get("text", ""),
|
|
288
|
+
trace_chain=obj.get("trace_chain", []),
|
|
289
|
+
)
|
|
290
|
+
except Exception:
|
|
291
|
+
return ExplainResult(text=text, trace_chain=[])
|
|
292
|
+
|
|
293
|
+
def register_tool(
|
|
294
|
+
self,
|
|
295
|
+
engine: c_void_p,
|
|
296
|
+
name: str,
|
|
297
|
+
risk: str,
|
|
298
|
+
category: str | None,
|
|
299
|
+
) -> None:
|
|
300
|
+
import json
|
|
301
|
+
config = {"risk": risk}
|
|
302
|
+
if category is not None:
|
|
303
|
+
config["category"] = category
|
|
304
|
+
config_json = json.dumps(config)
|
|
305
|
+
name_buf, name_len = _to_buf(name)
|
|
306
|
+
config_buf, config_len = _to_buf(config_json)
|
|
307
|
+
st = self._lib.chitin_register_tool(
|
|
308
|
+
engine,
|
|
309
|
+
name_buf,
|
|
310
|
+
name_len,
|
|
311
|
+
config_buf,
|
|
312
|
+
config_len,
|
|
313
|
+
)
|
|
314
|
+
if st != CHITIN_OK:
|
|
315
|
+
raise ChitinError(st, self._last_error())
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def load_ffi() -> _ChitinFFI:
|
|
319
|
+
"""Load the chitin library and return the FFI wrapper. Raises ChitinError if load fails."""
|
|
320
|
+
return _ChitinFFI()
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""HTTP client for the chitin-sidecar. Same semantics as the C ABI."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import urllib.error
|
|
5
|
+
import urllib.request
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from chitin._types import ChitinError, Decision, ExplainResult
|
|
9
|
+
|
|
10
|
+
# Status codes (match C ABI)
|
|
11
|
+
CHITIN_OK = 0
|
|
12
|
+
CHITIN_ERR_INVALID = -1
|
|
13
|
+
CHITIN_ERR_DENIED = -2
|
|
14
|
+
CHITIN_ERR_ESCALATED = -3
|
|
15
|
+
CHITIN_ERR_INTERNAL = -4
|
|
16
|
+
CHITIN_ERR_NOT_FOUND = -5
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _ChitinHTTP:
|
|
20
|
+
"""HTTP backend that talks to chitin-sidecar. Uses CHITIN_SIDECAR_URL."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, base_url: str) -> None:
|
|
23
|
+
self._base = base_url.rstrip("/")
|
|
24
|
+
|
|
25
|
+
def _post(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
|
|
26
|
+
url = f"{self._base}{path}"
|
|
27
|
+
data = json.dumps(body).encode("utf-8")
|
|
28
|
+
req = urllib.request.Request(
|
|
29
|
+
url,
|
|
30
|
+
data=data,
|
|
31
|
+
headers={"Content-Type": "application/json"},
|
|
32
|
+
method="POST",
|
|
33
|
+
)
|
|
34
|
+
try:
|
|
35
|
+
with urllib.request.urlopen(req) as resp:
|
|
36
|
+
raw = resp.read()
|
|
37
|
+
if resp.status == 204 or not raw:
|
|
38
|
+
return {}
|
|
39
|
+
return json.loads(raw.decode("utf-8"))
|
|
40
|
+
except urllib.error.HTTPError as e:
|
|
41
|
+
try:
|
|
42
|
+
payload = json.loads(e.read().decode("utf-8"))
|
|
43
|
+
except Exception:
|
|
44
|
+
payload = {}
|
|
45
|
+
status = payload.get("status", CHITIN_ERR_INTERNAL)
|
|
46
|
+
msg = payload.get("error", str(e))
|
|
47
|
+
raise ChitinError(status, msg) from e
|
|
48
|
+
except urllib.error.URLError as e:
|
|
49
|
+
raise ChitinError(CHITIN_ERR_INTERNAL, str(e.reason)) from e
|
|
50
|
+
|
|
51
|
+
def ingest(
|
|
52
|
+
self,
|
|
53
|
+
content: str,
|
|
54
|
+
trust_level: int,
|
|
55
|
+
metadata: dict | None,
|
|
56
|
+
) -> int:
|
|
57
|
+
body: dict[str, Any] = {
|
|
58
|
+
"content": content,
|
|
59
|
+
"trust": trust_level,
|
|
60
|
+
}
|
|
61
|
+
if metadata is not None:
|
|
62
|
+
body["metadata"] = metadata
|
|
63
|
+
out = self._post("/ingest", body)
|
|
64
|
+
status = out.get("status", CHITIN_OK)
|
|
65
|
+
if status != CHITIN_OK:
|
|
66
|
+
raise ChitinError(status, out.get("error", "ingest failed"))
|
|
67
|
+
return int(out["event_id"])
|
|
68
|
+
|
|
69
|
+
def propose(
|
|
70
|
+
self,
|
|
71
|
+
tool: str,
|
|
72
|
+
params: str,
|
|
73
|
+
agent_id: str | None,
|
|
74
|
+
input_sources: list[int] | None,
|
|
75
|
+
) -> Decision:
|
|
76
|
+
body: dict[str, Any] = {"tool": tool, "params": params}
|
|
77
|
+
if agent_id is not None:
|
|
78
|
+
body["agent_id"] = agent_id
|
|
79
|
+
if input_sources is not None:
|
|
80
|
+
body["input_sources"] = input_sources
|
|
81
|
+
out = self._post("/propose", body)
|
|
82
|
+
# Sidecar always returns 200 with status in body
|
|
83
|
+
return Decision(
|
|
84
|
+
allowed=bool(out.get("allowed", False)),
|
|
85
|
+
outcome=out.get("outcome", "deny"),
|
|
86
|
+
event_id=int(out["event_id"]),
|
|
87
|
+
rule_id=out.get("rule_id"),
|
|
88
|
+
reason=out.get("reason"),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def record_result(
|
|
92
|
+
self,
|
|
93
|
+
tool_call_id: int,
|
|
94
|
+
output: str,
|
|
95
|
+
exit_code: int,
|
|
96
|
+
) -> int:
|
|
97
|
+
out = self._post(
|
|
98
|
+
"/record_result",
|
|
99
|
+
{"tool_call_id": tool_call_id, "output": output, "exit_code": exit_code},
|
|
100
|
+
)
|
|
101
|
+
status = out.get("status", CHITIN_OK)
|
|
102
|
+
if status != CHITIN_OK:
|
|
103
|
+
raise ChitinError(status, out.get("error", "record_result failed"))
|
|
104
|
+
return int(out["event_id"])
|
|
105
|
+
|
|
106
|
+
def is_traced(self, event_id: int, label: str) -> bool:
|
|
107
|
+
out = self._post("/is_traced", {"event_id": event_id, "label": label})
|
|
108
|
+
if out.get("status") != CHITIN_OK:
|
|
109
|
+
raise ChitinError(
|
|
110
|
+
out.get("status", CHITIN_ERR_INTERNAL),
|
|
111
|
+
out.get("error", "is_traced failed"),
|
|
112
|
+
)
|
|
113
|
+
return bool(out.get("traced", False))
|
|
114
|
+
|
|
115
|
+
def explain(self, event_id: int) -> ExplainResult:
|
|
116
|
+
out = self._post("/explain", {"event_id": event_id})
|
|
117
|
+
status = out.get("status", CHITIN_OK)
|
|
118
|
+
if status != CHITIN_OK:
|
|
119
|
+
raise ChitinError(status, out.get("error", "explain failed"))
|
|
120
|
+
return ExplainResult(
|
|
121
|
+
text=out.get("text") or "",
|
|
122
|
+
trace_chain=out.get("trace_chain") or [],
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def register_tool(
|
|
126
|
+
self,
|
|
127
|
+
name: str,
|
|
128
|
+
risk: str,
|
|
129
|
+
category: str | None,
|
|
130
|
+
) -> None:
|
|
131
|
+
body: dict[str, Any] = {"tool_name": name, "risk": risk}
|
|
132
|
+
if category is not None:
|
|
133
|
+
body["category"] = category
|
|
134
|
+
self._post("/register_tool", body)
|
|
135
|
+
# 204 No Content → _post returns {}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Resolve path to the chitin shared library."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import platform
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
# Library filename for current platform
|
|
8
|
+
_LIB_NAMES = {
|
|
9
|
+
"Linux": "libchitin.so",
|
|
10
|
+
"Darwin": "libchitin.dylib",
|
|
11
|
+
"Windows": "chitin.dll",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _lib_name() -> str:
|
|
16
|
+
return _LIB_NAMES.get(platform.system(), "libchitin.so")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def resolve_chitin_lib() -> str:
|
|
20
|
+
"""
|
|
21
|
+
Resolve path to the chitin shared library.
|
|
22
|
+
|
|
23
|
+
Order:
|
|
24
|
+
1. CHITIN_LIB_PATH environment variable (explicit path)
|
|
25
|
+
2. chitin/_lib/ inside the installed package (bundled in platform wheel)
|
|
26
|
+
3. ./target/release/{lib_name} (dev: building engine locally)
|
|
27
|
+
4. ../chitin-engine/target/release/{lib_name} (dev: sibling repo)
|
|
28
|
+
5. System library search path (return lib name only)
|
|
29
|
+
|
|
30
|
+
Returns a path string or the library name for CDLL. Caller must try
|
|
31
|
+
ctypes.CDLL(result); on OSError, raise with a helpful message.
|
|
32
|
+
"""
|
|
33
|
+
lib_name = _lib_name()
|
|
34
|
+
|
|
35
|
+
# 1. Explicit path
|
|
36
|
+
env_path = os.environ.get("CHITIN_LIB_PATH")
|
|
37
|
+
if env_path and os.path.isfile(env_path):
|
|
38
|
+
return os.path.abspath(env_path)
|
|
39
|
+
|
|
40
|
+
# 2. Bundled in platform wheel (chitin/_lib/ next to this file)
|
|
41
|
+
bundled = Path(__file__).resolve().parent / "_lib" / lib_name
|
|
42
|
+
if bundled.exists():
|
|
43
|
+
return str(bundled)
|
|
44
|
+
|
|
45
|
+
# 3. Dev: local target/release
|
|
46
|
+
dev_cwd = Path.cwd() / "target" / "release" / lib_name
|
|
47
|
+
if dev_cwd.is_file():
|
|
48
|
+
return str(dev_cwd)
|
|
49
|
+
|
|
50
|
+
# 4. Dev: sibling chitin-engine repo (chitin-engine-lib/../chitin-engine/target/release/)
|
|
51
|
+
_repo_root = Path(__file__).resolve().parent.parent
|
|
52
|
+
sibling = _repo_root.parent / "chitin-engine" / "target" / "release" / lib_name
|
|
53
|
+
if sibling.is_file():
|
|
54
|
+
return str(sibling)
|
|
55
|
+
|
|
56
|
+
# 5. System search (LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PATH)
|
|
57
|
+
return lib_name
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _load_lib_error_message() -> str:
|
|
61
|
+
return (
|
|
62
|
+
"Could not load the Chitin shared library. Either set CHITIN_LIB_PATH to the full path "
|
|
63
|
+
"to libchitin.so / libchitin.dylib / chitin.dll, install a platform-specific wheel "
|
|
64
|
+
"(chitin_engine_lib-*-manylinux_*.whl, etc.) that bundles the library, or set "
|
|
65
|
+
"CHITIN_SIDECAR_URL to use the HTTP sidecar instead."
|
|
66
|
+
)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Public types for the Chitin Python API."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TrustLevel:
|
|
7
|
+
"""Trust level for ingested content."""
|
|
8
|
+
|
|
9
|
+
SYSTEM = 0
|
|
10
|
+
OPERATOR = 1
|
|
11
|
+
USER = 2
|
|
12
|
+
EXTERNAL = 3
|
|
13
|
+
UNKNOWN = 4
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Decision:
|
|
18
|
+
"""Result of proposing a tool call."""
|
|
19
|
+
|
|
20
|
+
allowed: bool
|
|
21
|
+
outcome: str # "allow" | "deny" | "escalate"
|
|
22
|
+
event_id: int
|
|
23
|
+
rule_id: str | None # which policy rule fired
|
|
24
|
+
reason: str | None # human-readable reason
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class ExplainResult:
|
|
29
|
+
"""Result of explaining an event's trace."""
|
|
30
|
+
|
|
31
|
+
text: str # human-readable explanation
|
|
32
|
+
trace_chain: list # structured trace data (parsed from JSON)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ChitinError(Exception):
|
|
36
|
+
"""Raised when an engine call fails (other than deny/escalate from propose)."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, status: int, message: str) -> None:
|
|
39
|
+
self.status = status
|
|
40
|
+
self.message = message
|
|
41
|
+
super().__init__(f"[{status}] {message}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# PEP 561: this package supports type checking
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: chitin-engine-lib
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python bindings for the Chitin security engine
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Project-URL: Repository, https://github.com/datagoboom/chitin-engine-lib
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
setup_platform.py
|
|
5
|
+
chitin/__init__.py
|
|
6
|
+
chitin/_engine.py
|
|
7
|
+
chitin/_ffi.py
|
|
8
|
+
chitin/_http.py
|
|
9
|
+
chitin/_resolve.py
|
|
10
|
+
chitin/_types.py
|
|
11
|
+
chitin/py.typed
|
|
12
|
+
chitin_engine_lib.egg-info/PKG-INFO
|
|
13
|
+
chitin_engine_lib.egg-info/SOURCES.txt
|
|
14
|
+
chitin_engine_lib.egg-info/dependency_links.txt
|
|
15
|
+
chitin_engine_lib.egg-info/top_level.txt
|
|
16
|
+
tests/test_engine_fallback.py
|
|
17
|
+
tests/test_engine_http.py
|
|
18
|
+
tests/test_types.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
chitin
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "chitin-engine-lib"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python bindings for the Chitin security engine"
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
license = {text = "Apache-2.0"}
|
|
11
|
+
dependencies = []
|
|
12
|
+
|
|
13
|
+
[project.urls]
|
|
14
|
+
Repository = "https://github.com/datagoboom/chitin-engine-lib"
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.packages.find]
|
|
17
|
+
include = ["chitin*"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Setup script for platform-specific wheels that bundle the shared library.
|
|
2
|
+
Used only by CI; do not use for the pure wheel (use pyproject.toml + build).
|
|
3
|
+
"""
|
|
4
|
+
from setuptools import Distribution, setup
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class PlatformDistribution(Distribution):
|
|
8
|
+
"""Forces setuptools to tag the wheel as platform-specific (not py3-none-any)."""
|
|
9
|
+
|
|
10
|
+
def has_ext_modules(self) -> bool:
|
|
11
|
+
return True
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
setup(
|
|
15
|
+
name="chitin-engine-lib",
|
|
16
|
+
version="0.1.0",
|
|
17
|
+
description="Python bindings for the Chitin security engine",
|
|
18
|
+
license="Apache-2.0",
|
|
19
|
+
python_requires=">=3.11",
|
|
20
|
+
packages=["chitin"],
|
|
21
|
+
package_data={"chitin": ["_lib/*", "py.typed"]},
|
|
22
|
+
distclass=PlatformDistribution,
|
|
23
|
+
url="https://github.com/datagoboom/chitin-engine-lib",
|
|
24
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Tests for Engine backend selection and error when unavailable."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from chitin import ChitinError, Engine
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_engine_raises_when_both_backends_unavailable() -> None:
|
|
11
|
+
"""When lib cannot be loaded and CHITIN_SIDECAR_URL is unset, ChitinError is raised."""
|
|
12
|
+
sidecar = os.environ.pop("CHITIN_SIDECAR_URL", None)
|
|
13
|
+
lib_path = os.environ.pop("CHITIN_LIB_PATH", None)
|
|
14
|
+
try:
|
|
15
|
+
# Point at an existing non-library file so resolve returns it but CDLL fails
|
|
16
|
+
fake_lib = os.path.abspath(__file__)
|
|
17
|
+
os.environ["CHITIN_LIB_PATH"] = fake_lib
|
|
18
|
+
with pytest.raises(ChitinError) as exc_info:
|
|
19
|
+
Engine()
|
|
20
|
+
assert "CHITIN_SIDECAR_URL" in str(exc_info.value)
|
|
21
|
+
finally:
|
|
22
|
+
if sidecar is not None:
|
|
23
|
+
os.environ["CHITIN_SIDECAR_URL"] = sidecar
|
|
24
|
+
if lib_path is not None:
|
|
25
|
+
os.environ["CHITIN_LIB_PATH"] = lib_path
|
|
26
|
+
else:
|
|
27
|
+
os.environ.pop("CHITIN_LIB_PATH", None)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Tests for Engine with HTTP backend (requires CHITIN_SIDECAR_URL and running sidecar)."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from chitin import Engine, TrustLevel
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.mark.skipif(
|
|
11
|
+
not os.environ.get("CHITIN_SIDECAR_URL"),
|
|
12
|
+
reason="CHITIN_SIDECAR_URL not set",
|
|
13
|
+
)
|
|
14
|
+
def test_engine_http_ingest_propose_record() -> None:
|
|
15
|
+
"""Round-trip ingest → propose → record_result via HTTP."""
|
|
16
|
+
with Engine() as engine:
|
|
17
|
+
event_id = engine.ingest("user said hi", trust_level=TrustLevel.USER)
|
|
18
|
+
assert isinstance(event_id, int)
|
|
19
|
+
decision = engine.propose(
|
|
20
|
+
tool="noop",
|
|
21
|
+
params="{}",
|
|
22
|
+
input_sources=[event_id],
|
|
23
|
+
)
|
|
24
|
+
assert decision.event_id >= 0
|
|
25
|
+
if decision.allowed:
|
|
26
|
+
event_id2 = engine.record_result(decision.event_id, "ok", exit_code=0)
|
|
27
|
+
assert isinstance(event_id2, int)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Tests for public types."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from chitin import ChitinError, Decision, ExplainResult, TrustLevel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_trust_level_constants() -> None:
|
|
9
|
+
assert TrustLevel.SYSTEM == 0
|
|
10
|
+
assert TrustLevel.OPERATOR == 1
|
|
11
|
+
assert TrustLevel.USER == 2
|
|
12
|
+
assert TrustLevel.EXTERNAL == 3
|
|
13
|
+
assert TrustLevel.UNKNOWN == 4
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_decision_dataclass() -> None:
|
|
17
|
+
d = Decision(
|
|
18
|
+
allowed=True,
|
|
19
|
+
outcome="allow",
|
|
20
|
+
event_id=1,
|
|
21
|
+
rule_id=None,
|
|
22
|
+
reason=None,
|
|
23
|
+
)
|
|
24
|
+
assert d.allowed is True
|
|
25
|
+
assert d.outcome == "allow"
|
|
26
|
+
assert d.event_id == 1
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_explain_result_dataclass() -> None:
|
|
30
|
+
e = ExplainResult(text="foo", trace_chain=[1, 2, 3])
|
|
31
|
+
assert e.text == "foo"
|
|
32
|
+
assert e.trace_chain == [1, 2, 3]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_chitin_error() -> None:
|
|
36
|
+
err = ChitinError(-1, "invalid")
|
|
37
|
+
assert err.status == -1
|
|
38
|
+
assert err.message == "invalid"
|
|
39
|
+
assert "[-1]" in str(err)
|