stackone-defender 0.7.1__tar.gz → 0.7.3__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.
- stackone_defender-0.7.3/.release-please-manifest.json +1 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/CHANGELOG.md +21 -0
- stackone_defender-0.7.3/LICENSE +190 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/PKG-INFO +44 -3
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/README.md +41 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/pyproject.toml +26 -3
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/__init__.py +2 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/classifiers/onnx_classifier.py +19 -7
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/core/prompt_defense.py +75 -5
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/core/tool_result_sanitizer.py +0 -1
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sanitizers/__init__.py +7 -1
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sanitizers/encoding_detector.py +4 -1
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sfe/preprocess.py +6 -4
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/types.py +18 -1
- stackone_defender-0.7.3/tests/__init__.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/tests/test_onnx_classifier.py +57 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/tests/test_pattern_detector.py +0 -3
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/tests/test_sanitizers.py +22 -1
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/tests/test_sfe.py +17 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/tests/test_tier2_classifier.py +0 -3
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/tests/test_tier3.py +211 -2
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/tests/test_utils.py +1 -5
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/uv.lock +187 -1
- stackone_defender-0.7.1/.github/workflows/ci.yaml +0 -24
- stackone_defender-0.7.1/.github/workflows/release.yaml +0 -31
- stackone_defender-0.7.1/.release-please-manifest.json +0 -1
- stackone_defender-0.7.1/models/minilm-full-aug/config.json +0 -30
- stackone_defender-0.7.1/models/minilm-full-aug/model_quantized.onnx +0 -0
- stackone_defender-0.7.1/src/stackone_defender/models/minilm-multihead-v5/tokenizer.json +0 -30686
- stackone_defender-0.7.1/src/stackone_defender/models/minilm-multihead-v5/tokenizer_config.json +0 -23
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/.gitignore +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/.python-version +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/.release-please-config.json +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/classifiers/__init__.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/classifiers/pattern_detector.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/classifiers/patterns.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/classifiers/tier2_classifier.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/classifiers/tier3_orchestrator.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/config.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/core/__init__.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/models/minilm-multihead-v5/classifier_config.json +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/models/minilm-multihead-v5/config.json +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/models/minilm-multihead-v5/model_quantized.onnx +0 -0
- {stackone_defender-0.7.1/models/minilm-full-aug → stackone_defender-0.7.3/src/stackone_defender/models/minilm-multihead-v5}/tokenizer.json +0 -0
- {stackone_defender-0.7.1/models/minilm-full-aug → stackone_defender-0.7.3/src/stackone_defender/models/minilm-multihead-v5}/tokenizer_config.json +0 -0
- stackone_defender-0.7.1/tests/__init__.py → stackone_defender-0.7.3/src/stackone_defender/py.typed +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sanitizers/leet_normalizer.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sanitizers/normalizer.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sanitizers/pattern_remover.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sanitizers/role_stripper.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sanitizers/sanitizer.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sfe/__init__.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sfe/model.ftz +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/utils/__init__.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/utils/boundary.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/utils/field_detection.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/utils/structure.py +0 -0
- {stackone_defender-0.7.1 → stackone_defender-0.7.3}/tests/test_integration.py +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{".":"0.7.3"}
|
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.7.3](https://github.com/StackOneHQ/defender-py/compare/stackone-defender-v0.7.2...stackone-defender-v0.7.3) (2026-07-22)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* **ENG-1279:** port Tier 3 score-threshold (decide on score, not the model's word) ([77c8a6a](https://github.com/StackOneHQ/defender-py/commit/77c8a6a38336ddd797f5691cedf4670f15f575fb))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Bug Fixes
|
|
12
|
+
|
|
13
|
+
* **ENG-1279:** Tier 3 score threshold + ENG-1296 Tier 2/base64/SFE fixes ([3f2b9cd](https://github.com/StackOneHQ/defender-py/commit/3f2b9cd1f7dd82f19e468076bcb3196ad22bf83e))
|
|
14
|
+
* **ENG-1296:** port TS parity fixes for Tier 2 truncation, base64, SFE recursion ([4fa8cda](https://github.com/StackOneHQ/defender-py/commit/4fa8cda445d8c08e30e74d6053e2eaf26026fed2))
|
|
15
|
+
|
|
16
|
+
## [0.7.2](https://github.com/StackOneHQ/stackone-defender/compare/stackone-defender-v0.7.1...stackone-defender-v0.7.2) (2026-06-30)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
### Features
|
|
20
|
+
|
|
21
|
+
* add Tier3Verdict.usage for TS 0.7.2 parity ([2e18269](https://github.com/StackOneHQ/stackone-defender/commit/2e182695c20e9b087041e55f7466cca9b659521a))
|
|
22
|
+
* Tier3Verdict.usage parity with @stackone/defender 0.7.2 ([1c9c0c8](https://github.com/StackOneHQ/stackone-defender/commit/1c9c0c8026fd8c4dda2f78c31a1f500c01045d43))
|
|
23
|
+
|
|
3
24
|
## [0.7.1](https://github.com/StackOneHQ/stackone-defender/compare/stackone-defender-v0.7.0...stackone-defender-v0.7.1) (2026-06-16)
|
|
4
25
|
|
|
5
26
|
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but not
|
|
32
|
+
limited to compiled object code, generated documentation, and
|
|
33
|
+
conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding any notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2024 StackOne
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: stackone-defender
|
|
3
|
-
Version: 0.7.
|
|
3
|
+
Version: 0.7.3
|
|
4
4
|
Summary: Indirect prompt injection defense for AI agents using tool calls
|
|
5
5
|
Project-URL: Homepage, https://github.com/StackOneHQ/stackone-defender
|
|
6
6
|
Project-URL: Repository, https://github.com/StackOneHQ/stackone-defender
|
|
7
7
|
Author-email: StackOne <support@stackone.com>
|
|
8
|
-
License: Apache-2.0
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
9
10
|
Classifier: Development Status :: 4 - Beta
|
|
10
11
|
Classifier: Intended Audience :: Developers
|
|
11
|
-
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
12
|
Classifier: Programming Language :: Python :: 3
|
|
13
13
|
Classifier: Programming Language :: Python :: 3.11
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.12
|
|
@@ -146,6 +146,47 @@ Packed-chunk MiniLM classifier (int8 ONNX ~22 MB, bundled):
|
|
|
146
146
|
| jayavibhav (adversarial) | 0.9717 | ~1k |
|
|
147
147
|
| **Average** | **0.9079** | ~25k |
|
|
148
148
|
|
|
149
|
+
### Optional Tier 3 — LLM adjudication (consumer-supplied)
|
|
150
|
+
|
|
151
|
+
Authoritative LLM-based classification for the cases Tier 2 finds ambiguous. The package ships **only** the orchestration and the `Tier3Provider` interface — the actual model endpoint (a hosted LLM, OpenAI, an internal inference service) lives in your code, keeping proprietary models and credentials out of the package.
|
|
152
|
+
|
|
153
|
+
Two modes, selected via `defender_mode`:
|
|
154
|
+
- **`"cascade"`** (default): Tier 1 → Tier 2 → Tier 3, with Tier 3 invoked only when the Tier 2 effective score falls in the gray band (default `[0.3, 0.85)`). The Tier 3 verdict overrides Tier 2 on the escalated chunk — a `block` forces a block, an `allow` rescues it. Outside the band defender skips the round trip.
|
|
155
|
+
- **`"tier3_only"`**: skip Tier 2; the block/allow decision is the Tier 3 verdict alone. Tier 1 still sanitizes the returned `sanitized` payload.
|
|
156
|
+
|
|
157
|
+
Register a provider once at startup, then opt in per instance:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
from typing import Any
|
|
161
|
+
|
|
162
|
+
from stackone_defender import create_prompt_defense, set_default_tier3_provider
|
|
163
|
+
from stackone_defender.types import Tier3Verdict
|
|
164
|
+
|
|
165
|
+
class MyProvider:
|
|
166
|
+
def classify(self, text: str, *, ctx: dict[str, Any] | None = None) -> Tier3Verdict:
|
|
167
|
+
# Call your LLM endpoint here (sync or awaitable). ctx["toolName"] is available.
|
|
168
|
+
verdict = call_my_llm(text, tool_name=(ctx or {}).get("toolName"))
|
|
169
|
+
return Tier3Verdict(decision="block" if verdict.block else "allow", score=verdict.p_block)
|
|
170
|
+
|
|
171
|
+
set_default_tier3_provider(MyProvider())
|
|
172
|
+
|
|
173
|
+
defense = create_prompt_defense(
|
|
174
|
+
block_high_risk=True,
|
|
175
|
+
enable_tier3=True,
|
|
176
|
+
defender_mode="cascade", # or "tier3_only"
|
|
177
|
+
tier3={
|
|
178
|
+
"provider": MyProvider(), # optional: overrides the registry for this instance
|
|
179
|
+
"escalation_band": {"lower": 0.3, "upper": 0.85}, # cascade gray band; [lower, upper), defaults shown
|
|
180
|
+
"max_text_length": 10000, # caps text passed to the provider
|
|
181
|
+
"block_threshold": 0.622, # optional; decide on score, not the model's word
|
|
182
|
+
},
|
|
183
|
+
)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
**Choosing the operating point (`block_threshold`).** By default the model's `decision` word is authoritative — but that word is its argmax, an implicit 0.5 cut that moves on its own whenever the model is retrained. Set `tier3.block_threshold` to decide on `verdict.score` (P(block)) instead: the cut becomes an explicit config value — raise it to trade recall for fewer false positives, lower it for the reverse; `0.5` reproduces argmax. It requires a provider that reports `score` as P(block) (not "confidence in whichever decision I made" — those invert on allows). If `score` is missing or outside `[0, 1]` the verdict's `decision` is used instead and defender warns once, so a provider that cannot report a score degrades to the default rather than failing.
|
|
187
|
+
|
|
188
|
+
**Fail-open semantics.** A provider error or timeout records a `skip_reason` on `result.tier3`; in cascade defender falls back to the Tier 2 decision, in `tier3_only` it allows the request. `enable_tier3=True` with no registered provider falls back to the standard Tier 1 + Tier 2 cascade and logs one warning per instance — Tier 3 misconfiguration never silently disables defense. `result.tier3` carries the verdict (a `Tier3Verdict`, or a `Tier3Skip` when the provider ran but returned nothing usable) when Tier 3 runs, and is `None` when it doesn't.
|
|
189
|
+
|
|
149
190
|
### `allowed` vs `risk_level`
|
|
150
191
|
|
|
151
192
|
- Use **`allowed`** for gating when `block_high_risk=True`: `False` means do not pass `sanitized` to the model as-is.
|
|
@@ -120,6 +120,47 @@ Packed-chunk MiniLM classifier (int8 ONNX ~22 MB, bundled):
|
|
|
120
120
|
| jayavibhav (adversarial) | 0.9717 | ~1k |
|
|
121
121
|
| **Average** | **0.9079** | ~25k |
|
|
122
122
|
|
|
123
|
+
### Optional Tier 3 — LLM adjudication (consumer-supplied)
|
|
124
|
+
|
|
125
|
+
Authoritative LLM-based classification for the cases Tier 2 finds ambiguous. The package ships **only** the orchestration and the `Tier3Provider` interface — the actual model endpoint (a hosted LLM, OpenAI, an internal inference service) lives in your code, keeping proprietary models and credentials out of the package.
|
|
126
|
+
|
|
127
|
+
Two modes, selected via `defender_mode`:
|
|
128
|
+
- **`"cascade"`** (default): Tier 1 → Tier 2 → Tier 3, with Tier 3 invoked only when the Tier 2 effective score falls in the gray band (default `[0.3, 0.85)`). The Tier 3 verdict overrides Tier 2 on the escalated chunk — a `block` forces a block, an `allow` rescues it. Outside the band defender skips the round trip.
|
|
129
|
+
- **`"tier3_only"`**: skip Tier 2; the block/allow decision is the Tier 3 verdict alone. Tier 1 still sanitizes the returned `sanitized` payload.
|
|
130
|
+
|
|
131
|
+
Register a provider once at startup, then opt in per instance:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from typing import Any
|
|
135
|
+
|
|
136
|
+
from stackone_defender import create_prompt_defense, set_default_tier3_provider
|
|
137
|
+
from stackone_defender.types import Tier3Verdict
|
|
138
|
+
|
|
139
|
+
class MyProvider:
|
|
140
|
+
def classify(self, text: str, *, ctx: dict[str, Any] | None = None) -> Tier3Verdict:
|
|
141
|
+
# Call your LLM endpoint here (sync or awaitable). ctx["toolName"] is available.
|
|
142
|
+
verdict = call_my_llm(text, tool_name=(ctx or {}).get("toolName"))
|
|
143
|
+
return Tier3Verdict(decision="block" if verdict.block else "allow", score=verdict.p_block)
|
|
144
|
+
|
|
145
|
+
set_default_tier3_provider(MyProvider())
|
|
146
|
+
|
|
147
|
+
defense = create_prompt_defense(
|
|
148
|
+
block_high_risk=True,
|
|
149
|
+
enable_tier3=True,
|
|
150
|
+
defender_mode="cascade", # or "tier3_only"
|
|
151
|
+
tier3={
|
|
152
|
+
"provider": MyProvider(), # optional: overrides the registry for this instance
|
|
153
|
+
"escalation_band": {"lower": 0.3, "upper": 0.85}, # cascade gray band; [lower, upper), defaults shown
|
|
154
|
+
"max_text_length": 10000, # caps text passed to the provider
|
|
155
|
+
"block_threshold": 0.622, # optional; decide on score, not the model's word
|
|
156
|
+
},
|
|
157
|
+
)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
**Choosing the operating point (`block_threshold`).** By default the model's `decision` word is authoritative — but that word is its argmax, an implicit 0.5 cut that moves on its own whenever the model is retrained. Set `tier3.block_threshold` to decide on `verdict.score` (P(block)) instead: the cut becomes an explicit config value — raise it to trade recall for fewer false positives, lower it for the reverse; `0.5` reproduces argmax. It requires a provider that reports `score` as P(block) (not "confidence in whichever decision I made" — those invert on allows). If `score` is missing or outside `[0, 1]` the verdict's `decision` is used instead and defender warns once, so a provider that cannot report a score degrades to the default rather than failing.
|
|
161
|
+
|
|
162
|
+
**Fail-open semantics.** A provider error or timeout records a `skip_reason` on `result.tier3`; in cascade defender falls back to the Tier 2 decision, in `tier3_only` it allows the request. `enable_tier3=True` with no registered provider falls back to the standard Tier 1 + Tier 2 cascade and logs one warning per instance — Tier 3 misconfiguration never silently disables defense. `result.tier3` carries the verdict (a `Tier3Verdict`, or a `Tier3Skip` when the provider ran but returned nothing usable) when Tier 3 runs, and is `None` when it doesn't.
|
|
163
|
+
|
|
123
164
|
### `allowed` vs `risk_level`
|
|
124
165
|
|
|
125
166
|
- Use **`allowed`** for gating when `block_high_risk=True`: `False` means do not pass `sanitized` to the model as-is.
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "stackone-defender"
|
|
3
|
-
version = "0.7.
|
|
3
|
+
version = "0.7.3"
|
|
4
4
|
description = "Indirect prompt injection defense for AI agents using tool calls"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
7
|
-
license =
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
8
9
|
authors = [{ name = "StackOne", email = "support@stackone.com" }]
|
|
9
10
|
classifiers = [
|
|
10
11
|
"Development Status :: 4 - Beta",
|
|
11
12
|
"Intended Audience :: Developers",
|
|
12
|
-
"License :: OSI Approved :: Apache Software License",
|
|
13
13
|
"Programming Language :: Python :: 3",
|
|
14
14
|
"Programming Language :: Python :: 3.11",
|
|
15
15
|
"Programming Language :: Python :: 3.12",
|
|
@@ -32,6 +32,8 @@ sfe = ["fasttext-ng>=0.9.3"]
|
|
|
32
32
|
[dependency-groups]
|
|
33
33
|
dev = [
|
|
34
34
|
"pytest>=8.0",
|
|
35
|
+
"pytest-cov>=5.0",
|
|
36
|
+
"ruff>=0.9",
|
|
35
37
|
"onnxruntime>=1.16.0",
|
|
36
38
|
"tokenizers>=0.15.0",
|
|
37
39
|
"numpy>=1.24.0",
|
|
@@ -45,5 +47,26 @@ build-backend = "hatchling.build"
|
|
|
45
47
|
[tool.hatch.build.targets.wheel]
|
|
46
48
|
packages = ["src/stackone_defender"]
|
|
47
49
|
|
|
50
|
+
[tool.hatch.build.targets.sdist]
|
|
51
|
+
exclude = ["/models", "/.github"] # legacy model + CI, dev-only
|
|
52
|
+
|
|
53
|
+
[tool.ruff]
|
|
54
|
+
target-version = "py311"
|
|
55
|
+
line-length = 120
|
|
56
|
+
src = ["src", "tests"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = ["E", "W", "F", "I", "N", "UP", "B", "C4", "SIM", "RUF"]
|
|
60
|
+
# E501/RUF003 by design; SIM*/UP007 deferred to cleanup.
|
|
61
|
+
ignore = ["E501", "RUF003", "SIM102", "SIM103", "SIM108", "SIM110", "SIM118", "UP007"]
|
|
62
|
+
|
|
63
|
+
[tool.ruff.lint.per-file-ignores]
|
|
64
|
+
"tests/*" = ["RUF012", "N814", "F841", "F811"]
|
|
65
|
+
|
|
48
66
|
[tool.pytest.ini_options]
|
|
49
67
|
testpaths = ["tests"]
|
|
68
|
+
addopts = "--strict-markers --strict-config -ra"
|
|
69
|
+
markers = [
|
|
70
|
+
"model: requires the bundled ONNX model + onnxruntime extra",
|
|
71
|
+
"sfe: requires the fasttext extra",
|
|
72
|
+
]
|
|
@@ -29,6 +29,7 @@ from .types import (
|
|
|
29
29
|
RiskLevel,
|
|
30
30
|
Tier1Result,
|
|
31
31
|
Tier3Provider,
|
|
32
|
+
Tier3TokenUsage,
|
|
32
33
|
Tier3Verdict,
|
|
33
34
|
)
|
|
34
35
|
from .utils.boundary import contains_boundary_patterns, generate_boundary_instructions
|
|
@@ -44,6 +45,7 @@ __all__ = [
|
|
|
44
45
|
"SfePreprocessResult",
|
|
45
46
|
"Tier1Result",
|
|
46
47
|
"Tier3Provider",
|
|
48
|
+
"Tier3TokenUsage",
|
|
47
49
|
"Tier3Verdict",
|
|
48
50
|
"contains_boundary_patterns",
|
|
49
51
|
"create_prompt_defense",
|
|
@@ -17,7 +17,9 @@ from typing import Literal
|
|
|
17
17
|
_logger = logging.getLogger(__name__)
|
|
18
18
|
|
|
19
19
|
# Shared across all OnnxClassifier instances (keyed by resolved model dir path).
|
|
20
|
-
|
|
20
|
+
# Tuple is (session, tokenizer, count_tokenizer); the count tokenizer is
|
|
21
|
+
# non-truncating so count_tokens reports true length (see _load_model).
|
|
22
|
+
_session_cache: dict[str, tuple[object, object, object]] = {}
|
|
21
23
|
_registry_lock = threading.Lock()
|
|
22
24
|
_load_locks: dict[str, threading.Lock] = {}
|
|
23
25
|
|
|
@@ -64,6 +66,8 @@ class OnnxClassifier:
|
|
|
64
66
|
self._model_path = model_path or get_default_model_path()
|
|
65
67
|
self._session = None
|
|
66
68
|
self._tokenizer = None
|
|
69
|
+
# Non-truncating tokenizer used only by count_tokens (see _load_model).
|
|
70
|
+
self._count_tokenizer = None
|
|
67
71
|
self._max_length = 256
|
|
68
72
|
self._load_failed = False
|
|
69
73
|
# Output mode is detected lazily from the logits shape on the first
|
|
@@ -114,13 +118,13 @@ class OnnxClassifier:
|
|
|
114
118
|
cache_key = str(Path(self._model_path).resolve())
|
|
115
119
|
cached = _session_cache.get(cache_key)
|
|
116
120
|
if cached:
|
|
117
|
-
self._session, self._tokenizer = cached
|
|
121
|
+
self._session, self._tokenizer, self._count_tokenizer = cached
|
|
118
122
|
return
|
|
119
123
|
|
|
120
124
|
with _lock_for_cache_key(cache_key):
|
|
121
125
|
cached = _session_cache.get(cache_key)
|
|
122
126
|
if cached:
|
|
123
|
-
self._session, self._tokenizer = cached
|
|
127
|
+
self._session, self._tokenizer, self._count_tokenizer = cached
|
|
124
128
|
return
|
|
125
129
|
|
|
126
130
|
try:
|
|
@@ -140,13 +144,21 @@ class OnnxClassifier:
|
|
|
140
144
|
self._tokenizer.enable_truncation(max_length=self._max_length)
|
|
141
145
|
self._tokenizer.enable_padding(length=self._max_length)
|
|
142
146
|
|
|
147
|
+
# tokenizer.json bakes in truncation+padding, so disable both
|
|
148
|
+
# here to count true length rather than a value capped at
|
|
149
|
+
# max_length (which would make every long payload look like a
|
|
150
|
+
# single chunk and drop everything past the cap).
|
|
151
|
+
self._count_tokenizer = Tokenizer.from_file(tokenizer_path)
|
|
152
|
+
self._count_tokenizer.no_truncation()
|
|
153
|
+
self._count_tokenizer.no_padding()
|
|
154
|
+
|
|
143
155
|
onnx_path = str(Path(self._model_path) / "model_quantized.onnx")
|
|
144
156
|
self._session = ort.InferenceSession(onnx_path)
|
|
145
157
|
except Exception as e:
|
|
146
158
|
_logger.warning("[defender] ONNX model failed to load: %s", e)
|
|
147
159
|
raise
|
|
148
160
|
|
|
149
|
-
_session_cache[cache_key] = (self._session, self._tokenizer)
|
|
161
|
+
_session_cache[cache_key] = (self._session, self._tokenizer, self._count_tokenizer)
|
|
150
162
|
|
|
151
163
|
# ------------------------------------------------------------------
|
|
152
164
|
# Inference
|
|
@@ -258,9 +270,9 @@ class OnnxClassifier:
|
|
|
258
270
|
|
|
259
271
|
def count_tokens(self, text: str) -> int:
|
|
260
272
|
self._ensure_loaded()
|
|
261
|
-
|
|
262
|
-
#
|
|
263
|
-
return
|
|
273
|
+
# Non-truncating count, including special tokens ([CLS]/[SEP]) to match
|
|
274
|
+
# the TS countTokens; the inference tokenizer would cap this at max_length.
|
|
275
|
+
return len(self._count_tokenizer.encode(text).ids)
|
|
264
276
|
|
|
265
277
|
def get_max_length(self) -> int:
|
|
266
278
|
return self._max_length
|
{stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/core/prompt_defense.py
RENAMED
|
@@ -11,7 +11,7 @@ import inspect
|
|
|
11
11
|
import logging
|
|
12
12
|
import math
|
|
13
13
|
import time
|
|
14
|
-
from dataclasses import dataclass, field
|
|
14
|
+
from dataclasses import dataclass, field, replace
|
|
15
15
|
from typing import Any
|
|
16
16
|
|
|
17
17
|
from ..classifiers.pattern_detector import PatternDetector, create_pattern_detector
|
|
@@ -30,6 +30,7 @@ from ..types import (
|
|
|
30
30
|
Tier3Provider,
|
|
31
31
|
Tier3Result,
|
|
32
32
|
Tier3Skip,
|
|
33
|
+
Tier3TokenUsage,
|
|
33
34
|
Tier3Verdict,
|
|
34
35
|
)
|
|
35
36
|
from .tool_result_sanitizer import ToolResultSanitizer, create_tool_result_sanitizer
|
|
@@ -241,6 +242,8 @@ class PromptDefense:
|
|
|
241
242
|
self._tier3_band = _DEFAULT_TIER3_BAND
|
|
242
243
|
self._tier3_max_text_length = _DEFAULT_TIER3_MAX_TEXT_LENGTH
|
|
243
244
|
self._tier3_missing_provider_warned = False
|
|
245
|
+
self._tier3_block_threshold: float | None = None
|
|
246
|
+
self._tier3_missing_score_warned = False
|
|
244
247
|
tier3_opts = tier3 or {}
|
|
245
248
|
if tier3_opts.get("provider") is not None:
|
|
246
249
|
self._tier3_custom_provider = tier3_opts["provider"]
|
|
@@ -274,6 +277,21 @@ class PromptDefense:
|
|
|
274
277
|
lower,
|
|
275
278
|
upper,
|
|
276
279
|
)
|
|
280
|
+
block_threshold = tier3_opts.get("block_threshold", tier3_opts.get("blockThreshold"))
|
|
281
|
+
if block_threshold is not None:
|
|
282
|
+
if (
|
|
283
|
+
isinstance(block_threshold, (int, float))
|
|
284
|
+
and not isinstance(block_threshold, bool)
|
|
285
|
+
and math.isfinite(block_threshold)
|
|
286
|
+
and 0 <= block_threshold <= 1
|
|
287
|
+
):
|
|
288
|
+
self._tier3_block_threshold = float(block_threshold)
|
|
289
|
+
else:
|
|
290
|
+
_logger.warning(
|
|
291
|
+
"[defender] invalid tier3.block_threshold %s — must be a finite number in [0, 1]. "
|
|
292
|
+
"Falling back to the provider's decision.",
|
|
293
|
+
block_threshold,
|
|
294
|
+
)
|
|
277
295
|
|
|
278
296
|
def warmup_tier2(self) -> None:
|
|
279
297
|
if self._tier2:
|
|
@@ -292,11 +310,37 @@ class PromptDefense:
|
|
|
292
310
|
def _resolve_tier3_provider(self) -> Tier3Provider | None:
|
|
293
311
|
return self._tier3_custom_provider or get_default_tier3_provider()
|
|
294
312
|
|
|
313
|
+
@staticmethod
|
|
314
|
+
def _parse_tier3_usage(usage: Any) -> Tier3TokenUsage | None:
|
|
315
|
+
if usage is None or not isinstance(usage, dict):
|
|
316
|
+
return None
|
|
317
|
+
prompt_tokens = usage.get("prompt_tokens", usage.get("promptTokens"))
|
|
318
|
+
completion_tokens = usage.get("completion_tokens", usage.get("completionTokens"))
|
|
319
|
+
total_tokens = usage.get("total_tokens", usage.get("totalTokens"))
|
|
320
|
+
if not all(isinstance(value, int) for value in (prompt_tokens, completion_tokens, total_tokens)):
|
|
321
|
+
return None
|
|
322
|
+
return Tier3TokenUsage(
|
|
323
|
+
prompt_tokens=prompt_tokens,
|
|
324
|
+
completion_tokens=completion_tokens,
|
|
325
|
+
total_tokens=total_tokens,
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def _normalize_tier3_score(score: Any) -> float | None:
|
|
330
|
+
# Public contract is score in [0, 1]; drop anything else (wrong type,
|
|
331
|
+
# non-finite, out of range) rather than leak it to consumers or the
|
|
332
|
+
# block gate. bool is excluded since it is not a numeric score.
|
|
333
|
+
if isinstance(score, bool) or not isinstance(score, (int, float)):
|
|
334
|
+
return None
|
|
335
|
+
if not math.isfinite(score) or score < 0 or score > 1:
|
|
336
|
+
return None
|
|
337
|
+
return float(score)
|
|
338
|
+
|
|
295
339
|
@staticmethod
|
|
296
340
|
def _validate_tier3_verdict(verdict: Any) -> Tier3Verdict | Tier3Skip:
|
|
297
341
|
if isinstance(verdict, Tier3Verdict):
|
|
298
342
|
if verdict.decision in ("block", "allow"):
|
|
299
|
-
return verdict
|
|
343
|
+
return replace(verdict, score=PromptDefense._normalize_tier3_score(verdict.score))
|
|
300
344
|
return Tier3Skip(
|
|
301
345
|
skip_reason=(
|
|
302
346
|
f'Tier 3 provider returned invalid decision: {verdict.decision!r} '
|
|
@@ -314,11 +358,37 @@ class PromptDefense:
|
|
|
314
358
|
)
|
|
315
359
|
return Tier3Verdict(
|
|
316
360
|
decision=decision,
|
|
317
|
-
score=verdict.get("score"),
|
|
361
|
+
score=PromptDefense._normalize_tier3_score(verdict.get("score")),
|
|
318
362
|
raw=verdict.get("raw"),
|
|
319
363
|
latency_ms=verdict.get("latency_ms", verdict.get("latencyMs")),
|
|
364
|
+
usage=PromptDefense._parse_tier3_usage(verdict.get("usage")),
|
|
320
365
|
)
|
|
321
366
|
|
|
367
|
+
def _is_tier3_block(self, verdict: Tier3Verdict) -> bool:
|
|
368
|
+
"""Resolve a validated verdict to block/allow.
|
|
369
|
+
|
|
370
|
+
With ``block_threshold`` unset this is the model's ``decision`` (its
|
|
371
|
+
argmax, an implicit 0.5 cut). With a threshold set we decide on ``score``
|
|
372
|
+
(P(block)) instead, which is what makes any other operating point
|
|
373
|
+
reachable. A threshold with no usable score falls back to ``decision``
|
|
374
|
+
(warned once) rather than taking the tier offline.
|
|
375
|
+
"""
|
|
376
|
+
if self._tier3_block_threshold is None:
|
|
377
|
+
return verdict.decision == "block"
|
|
378
|
+
# Validation already dropped any score outside [0, 1], so a non-None
|
|
379
|
+
# score here is usable as P(block).
|
|
380
|
+
if verdict.score is not None:
|
|
381
|
+
return verdict.score >= self._tier3_block_threshold
|
|
382
|
+
if not self._tier3_missing_score_warned:
|
|
383
|
+
self._tier3_missing_score_warned = True
|
|
384
|
+
_logger.warning(
|
|
385
|
+
"[defender] tier3.block_threshold=%s is set but the provider did not report a usable "
|
|
386
|
+
"score (missing, or not a number in [0, 1]). Falling back to the provider's decision — "
|
|
387
|
+
"the threshold is not being applied.",
|
|
388
|
+
self._tier3_block_threshold,
|
|
389
|
+
)
|
|
390
|
+
return verdict.decision == "block"
|
|
391
|
+
|
|
322
392
|
@staticmethod
|
|
323
393
|
async def _invoke_tier3_classify(provider: Tier3Provider, text: str, tool_name: str) -> Any:
|
|
324
394
|
ctx = {"toolName": tool_name}
|
|
@@ -374,7 +444,7 @@ class PromptDefense:
|
|
|
374
444
|
validated = self._validate_tier3_verdict(raw)
|
|
375
445
|
if isinstance(validated, Tier3Skip):
|
|
376
446
|
return validated, None
|
|
377
|
-
return validated, validated
|
|
447
|
+
return validated, self._is_tier3_block(validated)
|
|
378
448
|
except Exception as e:
|
|
379
449
|
return Tier3Skip(skip_reason=f"Tier 3 provider error: {e}"), None
|
|
380
450
|
|
|
@@ -440,7 +510,7 @@ class PromptDefense:
|
|
|
440
510
|
sanitized = self._tool_sanitizer.sanitize(value, tool_name=tool_name)
|
|
441
511
|
detections, fields_sanitized, prm = self._tier1_metadata(sanitized)
|
|
442
512
|
|
|
443
|
-
blocked = verdict is not None and verdict
|
|
513
|
+
blocked = verdict is not None and self._is_tier3_block(verdict)
|
|
444
514
|
risk_level: RiskLevel = "high" if blocked else "low"
|
|
445
515
|
allowed = not self._config.block_high_risk or not blocked
|
|
446
516
|
tier3_result: Tier3Result = (
|
{stackone_defender-0.7.1 → stackone_defender-0.7.3}/src/stackone_defender/sanitizers/__init__.py
RENAMED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
"""Sanitizers for prompt injection mitigation."""
|
|
2
2
|
|
|
3
|
-
from .encoding_detector import
|
|
3
|
+
from .encoding_detector import (
|
|
4
|
+
contains_encoded_content,
|
|
5
|
+
contains_suspicious_encoding,
|
|
6
|
+
decode_all_encoding,
|
|
7
|
+
detect_encoding,
|
|
8
|
+
redact_all_encoding,
|
|
9
|
+
)
|
|
4
10
|
from .normalizer import analyze_suspicious_unicode, contains_suspicious_unicode, normalize_unicode
|
|
5
11
|
from .pattern_remover import remove_patterns
|
|
6
12
|
from .role_stripper import contains_role_markers, strip_role_markers
|
|
@@ -105,7 +105,10 @@ def _detect_base64(text: str, min_length: int) -> list[EncodingDetection]:
|
|
|
105
105
|
if len(candidate) < min_length:
|
|
106
106
|
continue
|
|
107
107
|
try:
|
|
108
|
-
|
|
108
|
+
# Pad to a multiple of 4; b64decode rejects unpadded input, which
|
|
109
|
+
# the except below would silently drop (JS atob tolerates it).
|
|
110
|
+
padded = candidate + "=" * (-len(candidate) % 4)
|
|
111
|
+
decoded_bytes = base64.b64decode(padded, validate=False)
|
|
109
112
|
try:
|
|
110
113
|
decoded = decoded_bytes.decode("ascii")
|
|
111
114
|
except UnicodeDecodeError:
|