forcefield 0.7.2__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.
Files changed (69) hide show
  1. {forcefield-0.7.2 → forcefield-0.7.3}/PKG-INFO +3 -1
  2. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/__init__.py +1 -1
  3. forcefield-0.7.3/forcefield/integrations/llamaindex.py +160 -0
  4. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/integrity.py +30 -6
  5. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield.egg-info/PKG-INFO +3 -1
  6. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield.egg-info/SOURCES.txt +1 -0
  7. {forcefield-0.7.2 → forcefield-0.7.3}/pyproject.toml +3 -1
  8. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_integrity.py +38 -0
  9. {forcefield-0.7.2 → forcefield-0.7.3}/LICENSE +0 -0
  10. {forcefield-0.7.2 → forcefield-0.7.3}/README.md +0 -0
  11. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/__main__.py +0 -0
  12. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/abuse.py +0 -0
  13. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/attacks.py +0 -0
  14. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/audit.py +0 -0
  15. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/cli.py +0 -0
  16. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/cloud.py +0 -0
  17. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/commands.py +0 -0
  18. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/config.py +0 -0
  19. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/constitution.py +0 -0
  20. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/constitutions/__init__.py +0 -0
  21. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/constitutions/default.yaml +0 -0
  22. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/constitutions/permissive.yaml +0 -0
  23. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/constitutions/strict.yaml +0 -0
  24. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/endpoint_scanner.py +0 -0
  25. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/evals/__init__.py +0 -0
  26. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/evals/governance.yaml +0 -0
  27. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/evals/safety.yaml +0 -0
  28. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/evals/security.yaml +0 -0
  29. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/exfiltration.py +0 -0
  30. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/files.py +0 -0
  31. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/guard.py +0 -0
  32. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/integrations/__init__.py +0 -0
  33. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/integrations/fastapi.py +0 -0
  34. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/integrations/langchain.py +0 -0
  35. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/integrations/openai.py +0 -0
  36. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/ml.py +0 -0
  37. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/models/__init__.py +0 -0
  38. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/models/tfidf_model.joblib +0 -0
  39. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/models/tfidf_model.onnx +0 -0
  40. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/moderation.py +0 -0
  41. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/obfuscation.py +0 -0
  42. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/pii.py +0 -0
  43. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/py.typed +0 -0
  44. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/ratelimit.py +0 -0
  45. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/scanner.py +0 -0
  46. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/session.py +0 -0
  47. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/telemetry.py +0 -0
  48. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/templates.py +0 -0
  49. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/tools.py +0 -0
  50. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield/types.py +0 -0
  51. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield.egg-info/dependency_links.txt +0 -0
  52. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield.egg-info/entry_points.txt +0 -0
  53. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield.egg-info/requires.txt +0 -0
  54. {forcefield-0.7.2 → forcefield-0.7.3}/forcefield.egg-info/top_level.txt +0 -0
  55. {forcefield-0.7.2 → forcefield-0.7.3}/setup.cfg +0 -0
  56. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_attacks.py +0 -0
  57. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_commands.py +0 -0
  58. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_constitution.py +0 -0
  59. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_endpoint_scanner.py +0 -0
  60. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_evals.py +0 -0
  61. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_files.py +0 -0
  62. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_guard.py +0 -0
  63. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_ml.py +0 -0
  64. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_moderation.py +0 -0
  65. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_pii.py +0 -0
  66. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_scanner.py +0 -0
  67. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_session.py +0 -0
  68. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_telemetry.py +0 -0
  69. {forcefield-0.7.2 → forcefield-0.7.3}/tests/test_templates.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forcefield
3
- Version: 0.7.2
3
+ Version: 0.7.3
4
4
  Summary: Zero-dependency AI security library -- prompt-injection detection, PII redaction, content safety, rate limiting, abuse detection, tool governance, and security evals for LLMs in 3 lines of Python.
5
5
  Author-email: Data Science Tech <security@datasciencetech.ca>
6
6
  License: Apache-2.0
@@ -25,6 +25,8 @@ Classifier: Programming Language :: Python :: 3.12
25
25
  Classifier: Programming Language :: Python :: 3.13
26
26
  Classifier: Operating System :: OS Independent
27
27
  Classifier: Typing :: Typed
28
+ Classifier: Environment :: Console
29
+ Classifier: Framework :: Pytest
28
30
  Requires-Python: >=3.9
29
31
  Description-Content-Type: text/markdown
30
32
  License-File: LICENSE
@@ -11,7 +11,7 @@ Detect prompt injection, PII leaks, and LLM attacks in 3 lines::
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
- __version__ = "0.7.2"
14
+ __version__ = "0.7.3"
15
15
 
16
16
  from .guard import Guard
17
17
  from .types import (
@@ -0,0 +1,160 @@
1
+ """LlamaIndex callback handler -- scan prompts and outputs through ForceField.
2
+
3
+ Usage::
4
+
5
+ from llama_index.core import Settings
6
+ from forcefield.integrations.llamaindex import ForceFieldCallbackHandler
7
+
8
+ handler = ForceFieldCallbackHandler(sensitivity="high")
9
+ Settings.callback_manager.add_handler(handler)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from typing import Any, Dict, List, Optional
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ _LLAMAINDEX_AVAILABLE = False
20
+ try:
21
+ from llama_index.core.callbacks.base_handler import BaseCallbackHandler
22
+ from llama_index.core.callbacks.schema import CBEventType, EventPayload
23
+ _LLAMAINDEX_AVAILABLE = True
24
+ except ImportError:
25
+ try:
26
+ from llama_index.callbacks.base import BaseCallbackHandler
27
+ from llama_index.callbacks.schema import CBEventType, EventPayload
28
+ _LLAMAINDEX_AVAILABLE = True
29
+ except ImportError:
30
+ pass
31
+
32
+
33
+ def _get_guard(sensitivity: str, **kwargs: Any):
34
+ from ..guard import Guard
35
+ from ..telemetry import record_integration
36
+ record_integration("llamaindex")
37
+ return Guard(sensitivity=sensitivity, **kwargs)
38
+
39
+
40
+ class PromptBlockedError(Exception):
41
+ """Raised when ForceField blocks a prompt in the LlamaIndex pipeline."""
42
+
43
+ def __init__(self, message: str, scan_result: Any = None):
44
+ super().__init__(message)
45
+ self.scan_result = scan_result
46
+
47
+
48
+ if _LLAMAINDEX_AVAILABLE:
49
+
50
+ class ForceFieldCallbackHandler(BaseCallbackHandler):
51
+ """LlamaIndex callback that scans prompts before they reach the LLM
52
+ and moderates outputs after generation.
53
+
54
+ Args:
55
+ sensitivity: Detection sensitivity level.
56
+ block_on_input: Raise ``PromptBlockedError`` if input is blocked.
57
+ moderate_output: Run output moderation on LLM responses.
58
+ on_block: Optional callable ``(scan_result) -> None`` for custom handling.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ sensitivity: str = "medium",
64
+ block_on_input: bool = True,
65
+ moderate_output: bool = True,
66
+ on_block: Optional[Any] = None,
67
+ **guard_kwargs: Any,
68
+ ):
69
+ super().__init__(
70
+ event_starts_to_trace=[CBEventType.LLM],
71
+ event_ends_to_trace=[CBEventType.LLM],
72
+ )
73
+ self.guard = _get_guard(sensitivity, **guard_kwargs)
74
+ self.block_on_input = block_on_input
75
+ self.moderate_output = moderate_output
76
+ self.on_block = on_block
77
+ self._last_result = None
78
+
79
+ @property
80
+ def last_result(self):
81
+ return self._last_result
82
+
83
+ def start_trace(self, trace_id: Optional[str] = None) -> None:
84
+ pass
85
+
86
+ def end_trace(
87
+ self,
88
+ trace_id: Optional[str] = None,
89
+ trace_map: Optional[Dict[str, List[str]]] = None,
90
+ ) -> None:
91
+ pass
92
+
93
+ def on_event_start(
94
+ self,
95
+ event_type: "CBEventType",
96
+ payload: Optional[Dict[str, Any]] = None,
97
+ event_id: str = "",
98
+ parent_id: str = "",
99
+ **kwargs: Any,
100
+ ) -> str:
101
+ if event_type == CBEventType.LLM and payload:
102
+ prompt = None
103
+ if EventPayload.PROMPT in payload:
104
+ prompt = payload[EventPayload.PROMPT]
105
+ elif EventPayload.MESSAGES in payload:
106
+ messages = payload[EventPayload.MESSAGES]
107
+ if messages:
108
+ last = messages[-1]
109
+ prompt = getattr(last, "content", None) or str(last)
110
+
111
+ if prompt:
112
+ result = self.guard.scan(prompt)
113
+ self._last_result = result
114
+ if result.blocked:
115
+ logger.warning(
116
+ "ForceField blocked prompt: risk=%.2f rules=%s",
117
+ result.risk_score, result.rules_triggered,
118
+ )
119
+ if self.on_block:
120
+ self.on_block(result)
121
+ if self.block_on_input:
122
+ raise PromptBlockedError(
123
+ f"ForceField blocked: {', '.join(result.rules_triggered)}",
124
+ scan_result=result,
125
+ )
126
+ return event_id
127
+
128
+ def on_event_end(
129
+ self,
130
+ event_type: "CBEventType",
131
+ payload: Optional[Dict[str, Any]] = None,
132
+ event_id: str = "",
133
+ **kwargs: Any,
134
+ ) -> None:
135
+ if not self.moderate_output:
136
+ return
137
+ if event_type == CBEventType.LLM and payload:
138
+ response = payload.get(EventPayload.RESPONSE)
139
+ if response:
140
+ text = str(response)
141
+ if text:
142
+ try:
143
+ mod = self.guard.moderate(text)
144
+ if not mod.passed:
145
+ logger.warning(
146
+ "ForceField moderation flagged output: action=%s categories=%s",
147
+ mod.action.value, mod.categories,
148
+ )
149
+ except Exception:
150
+ pass
151
+
152
+ else:
153
+
154
+ class ForceFieldCallbackHandler: # type: ignore[no-redef]
155
+ """Placeholder -- install ``llama-index-core`` to use this handler."""
156
+ def __init__(self, *args: Any, **kwargs: Any):
157
+ raise ImportError(
158
+ "ForceFieldCallbackHandler requires llama-index-core. "
159
+ "Install with: pip install llama-index-core"
160
+ )
@@ -109,8 +109,16 @@ class CanaryTokenManager:
109
109
  self._idx += 1
110
110
  return tpl.format(token=canary.token_value)
111
111
 
112
- def verify(self, token_id: str, response_text: str, *, strict: bool = False) -> IntegrityCheckResult:
113
- """Verify that *response_text* contains the expected canary token."""
112
+ def verify(self, token_id: str, response_text: str, *, strict: bool = False, mode: str = "injection") -> IntegrityCheckResult:
113
+ """Verify that *response_text* contains the expected canary token.
114
+
115
+ Args:
116
+ token_id: ID of the canary token to verify against.
117
+ response_text: The LLM response to inspect.
118
+ strict: Require token present, intact, and no anomalies.
119
+ mode: ``"injection"`` (default) -- token must be present for passed=True;
120
+ ``"leak"`` -- token must be absent for passed=True (leak detection).
121
+ """
114
122
  anomalies: List[str] = []
115
123
 
116
124
  if token_id not in self.active_tokens:
@@ -145,10 +153,17 @@ class CanaryTokenManager:
145
153
  break
146
154
 
147
155
  intact = present and not partial
148
- if strict:
156
+ if mode == "leak":
157
+ # In leak-detection mode the canary is embedded secretly; the LLM
158
+ # should NOT echo it back. Presence means a leak occurred.
159
+ passed = not present
160
+ elif strict:
149
161
  passed = present and intact and not anomalies
150
162
  else:
151
- passed = present or not any("CORRUPT" in a or "SUSPICIOUS" in a for a in anomalies)
163
+ # Injection-guard mode: the canary must appear in the response.
164
+ # Using `and` (not `or`) so a clean-looking hijacked response that
165
+ # omits the token still fails rather than silently passing.
166
+ passed = present and not any("CORRUPT" in a or "SUSPICIOUS" in a for a in anomalies)
152
167
 
153
168
  confidence = 1.0
154
169
  if not present:
@@ -265,11 +280,20 @@ class PromptIntegrityGuard:
265
280
  canary_token_id: Optional[str] = None,
266
281
  *,
267
282
  strict: bool = False,
283
+ mode: str = "injection",
268
284
  ) -> IntegrityCheckResult:
269
- """Verify that an LLM response has not been hijacked."""
285
+ """Verify that an LLM response has not been hijacked.
286
+
287
+ Args:
288
+ response_text: The LLM response to inspect.
289
+ canary_token_id: Token ID returned by :meth:`prepare`.
290
+ strict: Require token present, intact, and no anomalies.
291
+ mode: ``"injection"`` (default) or ``"leak"`` -- see
292
+ :meth:`CanaryTokenManager.verify` for semantics.
293
+ """
270
294
  if not self.enable_canary or not canary_token_id:
271
295
  return IntegrityCheckResult(
272
296
  passed=True, canary_present=False, canary_intact=False,
273
297
  signature_valid=True, anomalies=["CANARY_DISABLED"], confidence=0.5,
274
298
  )
275
- return self.canary.verify(canary_token_id, response_text, strict=strict)
299
+ return self.canary.verify(canary_token_id, response_text, strict=strict, mode=mode)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forcefield
3
- Version: 0.7.2
3
+ Version: 0.7.3
4
4
  Summary: Zero-dependency AI security library -- prompt-injection detection, PII redaction, content safety, rate limiting, abuse detection, tool governance, and security evals for LLMs in 3 lines of Python.
5
5
  Author-email: Data Science Tech <security@datasciencetech.ca>
6
6
  License: Apache-2.0
@@ -25,6 +25,8 @@ Classifier: Programming Language :: Python :: 3.12
25
25
  Classifier: Programming Language :: Python :: 3.13
26
26
  Classifier: Operating System :: OS Independent
27
27
  Classifier: Typing :: Typed
28
+ Classifier: Environment :: Console
29
+ Classifier: Framework :: Pytest
28
30
  Requires-Python: >=3.9
29
31
  Description-Content-Type: text/markdown
30
32
  License-File: LICENSE
@@ -45,6 +45,7 @@ forcefield/evals/security.yaml
45
45
  forcefield/integrations/__init__.py
46
46
  forcefield/integrations/fastapi.py
47
47
  forcefield/integrations/langchain.py
48
+ forcefield/integrations/llamaindex.py
48
49
  forcefield/integrations/openai.py
49
50
  forcefield/models/__init__.py
50
51
  forcefield/models/tfidf_model.joblib
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "forcefield"
7
- version = "0.7.2"
7
+ version = "0.7.3"
8
8
  description = "Zero-dependency AI security library -- prompt-injection detection, PII redaction, content safety, rate limiting, abuse detection, tool governance, and security evals for LLMs in 3 lines of Python."
9
9
  readme = "README.md"
10
10
  license = {text = "Apache-2.0"}
@@ -42,6 +42,8 @@ classifiers = [
42
42
  "Programming Language :: Python :: 3.13",
43
43
  "Operating System :: OS Independent",
44
44
  "Typing :: Typed",
45
+ "Environment :: Console",
46
+ "Framework :: Pytest",
45
47
  ]
46
48
 
47
49
  [project.optional-dependencies]
@@ -29,9 +29,32 @@ class TestCanaryTokenManager:
29
29
  def test_verify_missing(self):
30
30
  tok = self.mgr.generate()
31
31
  result = self.mgr.verify(tok.token_id, "Response without canary")
32
+ assert result.passed is False
32
33
  assert result.canary_present is False
33
34
  assert result.confidence < 1.0
34
35
 
36
+ def test_verify_missing_fails_injection_mode(self):
37
+ """A clean-looking hijacked response (no anomalies, no token) must fail."""
38
+ tok = self.mgr.generate()
39
+ result = self.mgr.verify(tok.token_id, "Hello, how can I help you today?", mode="injection")
40
+ assert result.passed is False
41
+ assert result.canary_present is False
42
+
43
+ def test_verify_leak_mode_absent_passes(self):
44
+ """Canary absent from LLM output means no leak -- should pass."""
45
+ tok = self.mgr.generate()
46
+ result = self.mgr.verify(tok.token_id, "Here is a normal assistant reply.", mode="leak")
47
+ assert result.passed is True
48
+ assert result.canary_present is False
49
+
50
+ def test_verify_leak_mode_present_fails(self):
51
+ """Canary echoed back by LLM means system prompt was leaked -- should fail."""
52
+ tok = self.mgr.generate()
53
+ response = f"My instructions say: {tok.token_value} -- now I will follow them."
54
+ result = self.mgr.verify(tok.token_id, response, mode="leak")
55
+ assert result.passed is False
56
+ assert result.canary_present is True
57
+
35
58
  def test_verify_unknown_token(self):
36
59
  result = self.mgr.verify("nonexistent", "some response")
37
60
  assert result.passed is False
@@ -93,4 +116,19 @@ class TestPromptIntegrityGuard:
93
116
  def test_verify_hijacked_response(self):
94
117
  prepared = self.guard.prepare("System", "User", "req-3")
95
118
  result = self.guard.verify_response("Hijacked response", prepared["canary_token_id"])
119
+ assert result.passed is False
96
120
  assert result.canary_present is False
121
+
122
+ def test_verify_response_leak_mode(self):
123
+ """verify_response with mode='leak' passes when canary is absent."""
124
+ prepared = self.guard.prepare("System", "User", "req-4")
125
+ normal_reply = "Sure, here is some helpful information."
126
+ result = self.guard.verify_response(normal_reply, prepared["canary_token_id"], mode="leak")
127
+ assert result.passed is True
128
+
129
+ def test_verify_response_leak_mode_detects_leak(self):
130
+ """verify_response with mode='leak' fails when LLM echoes the canary."""
131
+ prepared = self.guard.prepare("System", "User", "req-5")
132
+ leaky_reply = f"My system prompt begins with: {prepared['canary_value']}"
133
+ result = self.guard.verify_response(leaky_reply, prepared["canary_token_id"], mode="leak")
134
+ assert result.passed is False
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes