forcefield 0.7.2__tar.gz → 0.7.4__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 (74) hide show
  1. {forcefield-0.7.2 → forcefield-0.7.4}/PKG-INFO +3 -1
  2. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/__init__.py +4 -1
  3. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/constitution.py +144 -0
  4. forcefield-0.7.4/forcefield/constitutions/presets/database.yaml +35 -0
  5. forcefield-0.7.4/forcefield/constitutions/presets/docker.yaml +43 -0
  6. forcefield-0.7.4/forcefield/constitutions/presets/github.yaml +37 -0
  7. forcefield-0.7.4/forcefield/constitutions/presets/slack.yaml +26 -0
  8. forcefield-0.7.4/forcefield/integrations/llamaindex.py +160 -0
  9. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/integrity.py +30 -6
  10. forcefield-0.7.4/forcefield/ssrf.py +191 -0
  11. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield.egg-info/PKG-INFO +3 -1
  12. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield.egg-info/SOURCES.txt +6 -0
  13. {forcefield-0.7.2 → forcefield-0.7.4}/pyproject.toml +4 -2
  14. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_integrity.py +38 -0
  15. {forcefield-0.7.2 → forcefield-0.7.4}/LICENSE +0 -0
  16. {forcefield-0.7.2 → forcefield-0.7.4}/README.md +0 -0
  17. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/__main__.py +0 -0
  18. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/abuse.py +0 -0
  19. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/attacks.py +0 -0
  20. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/audit.py +0 -0
  21. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/cli.py +0 -0
  22. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/cloud.py +0 -0
  23. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/commands.py +0 -0
  24. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/config.py +0 -0
  25. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/constitutions/__init__.py +0 -0
  26. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/constitutions/default.yaml +0 -0
  27. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/constitutions/permissive.yaml +0 -0
  28. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/constitutions/strict.yaml +0 -0
  29. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/endpoint_scanner.py +0 -0
  30. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/evals/__init__.py +0 -0
  31. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/evals/governance.yaml +0 -0
  32. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/evals/safety.yaml +0 -0
  33. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/evals/security.yaml +0 -0
  34. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/exfiltration.py +0 -0
  35. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/files.py +0 -0
  36. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/guard.py +0 -0
  37. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/integrations/__init__.py +0 -0
  38. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/integrations/fastapi.py +0 -0
  39. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/integrations/langchain.py +0 -0
  40. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/integrations/openai.py +0 -0
  41. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/ml.py +0 -0
  42. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/models/__init__.py +0 -0
  43. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/models/tfidf_model.joblib +0 -0
  44. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/models/tfidf_model.onnx +0 -0
  45. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/moderation.py +0 -0
  46. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/obfuscation.py +0 -0
  47. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/pii.py +0 -0
  48. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/py.typed +0 -0
  49. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/ratelimit.py +0 -0
  50. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/scanner.py +0 -0
  51. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/session.py +0 -0
  52. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/telemetry.py +0 -0
  53. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/templates.py +0 -0
  54. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/tools.py +0 -0
  55. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield/types.py +0 -0
  56. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield.egg-info/dependency_links.txt +0 -0
  57. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield.egg-info/entry_points.txt +0 -0
  58. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield.egg-info/requires.txt +0 -0
  59. {forcefield-0.7.2 → forcefield-0.7.4}/forcefield.egg-info/top_level.txt +0 -0
  60. {forcefield-0.7.2 → forcefield-0.7.4}/setup.cfg +0 -0
  61. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_attacks.py +0 -0
  62. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_commands.py +0 -0
  63. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_constitution.py +0 -0
  64. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_endpoint_scanner.py +0 -0
  65. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_evals.py +0 -0
  66. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_files.py +0 -0
  67. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_guard.py +0 -0
  68. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_ml.py +0 -0
  69. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_moderation.py +0 -0
  70. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_pii.py +0 -0
  71. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_scanner.py +0 -0
  72. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_session.py +0 -0
  73. {forcefield-0.7.2 → forcefield-0.7.4}/tests/test_telemetry.py +0 -0
  74. {forcefield-0.7.2 → forcefield-0.7.4}/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.4
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.4"
15
15
 
16
16
  from .guard import Guard
17
17
  from .types import (
@@ -46,6 +46,7 @@ from .constitution import Constitution, PolicyEngine, ConstitutionRule
46
46
  from .types import PolicyAction, PolicyVerdict
47
47
  from .evals import EvalSuite, EvalCase, EvalReport, EvalCaseResult, PassCriteria, run_eval
48
48
  from .audit import AuditReport, AuditEvent
49
+ from .ssrf import validate_endpoint_url, is_private_ip
49
50
 
50
51
  __all__ = [
51
52
  "Guard",
@@ -96,5 +97,7 @@ __all__ = [
96
97
  "run_eval",
97
98
  "AuditReport",
98
99
  "AuditEvent",
100
+ "validate_endpoint_url",
101
+ "is_private_ip",
99
102
  "__version__",
100
103
  ]
@@ -23,6 +23,8 @@ existing Sentinel behaviour is fully preserved.
23
23
  from __future__ import annotations
24
24
 
25
25
  import fnmatch
26
+ import hashlib
27
+ import json
26
28
  import os
27
29
  import re
28
30
  from dataclasses import dataclass, field
@@ -165,6 +167,103 @@ class Constitution:
165
167
  def from_dict(cls, data: Dict[str, Any]) -> "Constitution":
166
168
  return cls(data)
167
169
 
170
+ @classmethod
171
+ def _presets_dir(cls) -> str:
172
+ return os.path.join(os.path.dirname(__file__), "constitutions", "presets")
173
+
174
+ @classmethod
175
+ def list_presets(cls) -> List[Dict[str, str]]:
176
+ """List available policy presets.
177
+
178
+ Returns a list of ``{"name": ..., "description": ...}`` dicts.
179
+ """
180
+ presets_dir = cls._presets_dir()
181
+ if not os.path.isdir(presets_dir):
182
+ return []
183
+ results: List[Dict[str, str]] = []
184
+ for fname in sorted(os.listdir(presets_dir)):
185
+ if not fname.endswith((".yaml", ".yml")):
186
+ continue
187
+ fpath = os.path.join(presets_dir, fname)
188
+ try:
189
+ import yaml # type: ignore
190
+ with open(fpath, "r", encoding="utf-8") as fh:
191
+ data = yaml.safe_load(fh.read())
192
+ except Exception:
193
+ continue
194
+ if not isinstance(data, dict):
195
+ continue
196
+ preset_meta = data.get("preset", {})
197
+ results.append({
198
+ "name": preset_meta.get("name", fname.replace(".yaml", "")),
199
+ "description": preset_meta.get("description", ""),
200
+ "file": fname,
201
+ })
202
+ return results
203
+
204
+ @classmethod
205
+ def load_preset(cls, name: str) -> Dict[str, Any]:
206
+ """Load a preset YAML file by name and return its data dict.
207
+
208
+ Raises ``FileNotFoundError`` if the preset does not exist.
209
+ """
210
+ presets_dir = cls._presets_dir()
211
+ # Prevent path traversal
212
+ safe_name = os.path.basename(name)
213
+ candidates = [
214
+ os.path.join(presets_dir, f"{safe_name}.yaml"),
215
+ os.path.join(presets_dir, f"{safe_name}.yml"),
216
+ ]
217
+ for fpath in candidates:
218
+ if os.path.isfile(fpath):
219
+ try:
220
+ import yaml # type: ignore
221
+ with open(fpath, "r", encoding="utf-8") as fh:
222
+ data = yaml.safe_load(fh.read())
223
+ except ImportError:
224
+ with open(fpath, "r", encoding="utf-8") as fh:
225
+ data = json.loads(fh.read())
226
+ if isinstance(data, dict):
227
+ return data
228
+ raise FileNotFoundError(f"Preset '{name}' not found in {presets_dir}")
229
+
230
+ def apply_preset(self, preset_name: str) -> "Constitution":
231
+ """Merge a named preset into this constitution and return a new one.
232
+
233
+ Preset rules are appended to existing rules (preset overrides on
234
+ tool name collision). Other sections (defaults, scope, content)
235
+ are not modified by presets.
236
+ """
237
+ preset_data = self.load_preset(preset_name)
238
+
239
+ merged = dict(self._raw)
240
+
241
+ # Merge files rules (append)
242
+ if "files" in preset_data:
243
+ merged["files"] = list(merged.get("files", [])) + list(preset_data["files"])
244
+
245
+ # Merge command rules (append)
246
+ if "commands" in preset_data:
247
+ merged["commands"] = list(merged.get("commands", [])) + list(preset_data["commands"])
248
+
249
+ # Merge tool rules (preset overrides existing by name)
250
+ if "tools" in preset_data:
251
+ existing_tools = {
252
+ t.get("name", ""): t for t in merged.get("tools", [])
253
+ }
254
+ for tool in preset_data["tools"]:
255
+ existing_tools[tool.get("name", "")] = tool
256
+ merged["tools"] = list(existing_tools.values())
257
+
258
+ return Constitution(merged)
259
+
260
+ def apply_presets(self, preset_names: Sequence[str]) -> "Constitution":
261
+ """Apply multiple presets in order and return a new Constitution."""
262
+ result = self
263
+ for name in preset_names:
264
+ result = result.apply_preset(name)
265
+ return result
266
+
168
267
  # -- Validation ----------------------------------------------------------
169
268
 
170
269
  def validate(self) -> List[str]:
@@ -191,6 +290,31 @@ class Constitution:
191
290
  def to_dict(self) -> Dict[str, Any]:
192
291
  return self._raw
193
292
 
293
+ # -- Integrity ---------------------------------------------------------
294
+
295
+ def integrity_hash(self) -> str:
296
+ """Compute a SHA-256 hash of the canonical constitution data.
297
+
298
+ The hash covers the raw dictionary serialised as sorted JSON so that
299
+ semantically identical constitutions produce identical hashes
300
+ regardless of key ordering or whitespace.
301
+ """
302
+ canonical = json.dumps(self._raw, sort_keys=True, separators=(",", ":"))
303
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
304
+ return f"sha256:{digest}"
305
+
306
+ def verify_integrity(self, expected_hash: str) -> bool:
307
+ """Verify that the constitution has not been tampered with.
308
+
309
+ Args:
310
+ expected_hash: A hash string previously returned by
311
+ :meth:`integrity_hash` (format ``sha256:<hex>``).
312
+
313
+ Returns:
314
+ ``True`` if the current constitution matches the expected hash.
315
+ """
316
+ return self.integrity_hash() == expected_hash
317
+
194
318
  def __repr__(self) -> str:
195
319
  return (
196
320
  f"Constitution(name={self.name!r}, version={self.version!r}, "
@@ -214,6 +338,9 @@ class PolicyEngine:
214
338
 
215
339
  def __init__(self, constitution: Optional[Constitution] = None) -> None:
216
340
  self._constitution = constitution
341
+ self._pinned_hash: Optional[str] = (
342
+ constitution.integrity_hash() if constitution is not None else None
343
+ )
217
344
 
218
345
  @property
219
346
  def constitution(self) -> Optional[Constitution]:
@@ -227,6 +354,23 @@ class PolicyEngine:
227
354
  def has_constitution(self) -> bool:
228
355
  return self._constitution is not None
229
356
 
357
+ @property
358
+ def constitution_hash(self) -> Optional[str]:
359
+ """The integrity hash computed when the constitution was loaded."""
360
+ if self._constitution is None:
361
+ return None
362
+ return self._constitution.integrity_hash()
363
+
364
+ def verify_constitution_integrity(self, expected_hash: str) -> bool:
365
+ """Verify the current constitution against an expected hash.
366
+
367
+ Returns ``False`` if no constitution is loaded or the hash
368
+ does not match.
369
+ """
370
+ if self._constitution is None:
371
+ return False
372
+ return self._constitution.verify_integrity(expected_hash)
373
+
230
374
  # -- File evaluation -----------------------------------------------------
231
375
 
232
376
  def evaluate_file(
@@ -0,0 +1,35 @@
1
+ preset:
2
+ name: database
3
+ description: "Database access and operations policy"
4
+
5
+ commands:
6
+ - pattern: "DROP\\s+(TABLE|DATABASE|INDEX)"
7
+ action: block
8
+ reason: "Destructive SQL DDL"
9
+ - pattern: "TRUNCATE\\s+TABLE"
10
+ action: block
11
+ reason: "Table truncation"
12
+ - pattern: "DELETE\\s+FROM\\s+\\S+\\s*$"
13
+ action: block
14
+ reason: "DELETE without WHERE clause"
15
+ - pattern: "ALTER\\s+TABLE.*DROP"
16
+ action: confirm
17
+ reason: "Dropping columns requires approval"
18
+ - pattern: "GRANT\\s+ALL"
19
+ action: block
20
+ reason: "Granting all privileges"
21
+
22
+ tools:
23
+ - name: sql_execute
24
+ action: confirm
25
+ reason: "SQL execution requires approval"
26
+ - name: db_drop_table
27
+ action: block
28
+ - name: db_drop_database
29
+ action: block
30
+ - name: db_create_table
31
+ action: confirm
32
+ - name: db_query
33
+ action: allow
34
+ - name: db_read
35
+ action: allow
@@ -0,0 +1,43 @@
1
+ preset:
2
+ name: docker
3
+ description: "Docker and container operations policy"
4
+
5
+ files:
6
+ - pattern: "Dockerfile*"
7
+ action: confirm
8
+ reason: "Container image definition"
9
+ - pattern: "docker-compose*.yaml"
10
+ action: confirm
11
+ reason: "Container orchestration config"
12
+ - pattern: "docker-compose*.yml"
13
+ action: confirm
14
+ reason: "Container orchestration config"
15
+
16
+ commands:
17
+ - pattern: "docker\\s+rm\\s+-f"
18
+ action: confirm
19
+ reason: "Force container removal"
20
+ - pattern: "docker\\s+system\\s+prune"
21
+ action: confirm
22
+ reason: "Docker system prune"
23
+ - pattern: "docker\\s+run.*--privileged"
24
+ action: block
25
+ reason: "Privileged container execution"
26
+ - pattern: "docker\\s+run.*--cap-add"
27
+ action: confirm
28
+ reason: "Adding container capabilities"
29
+ - pattern: "docker\\s+push"
30
+ action: confirm
31
+ reason: "Publishing container image"
32
+
33
+ tools:
34
+ - name: docker_exec
35
+ action: confirm
36
+ - name: docker_run
37
+ action: confirm
38
+ - name: docker_build
39
+ action: allow
40
+ - name: docker_push
41
+ action: confirm
42
+ - name: docker_rm
43
+ action: confirm
@@ -0,0 +1,37 @@
1
+ preset:
2
+ name: github
3
+ description: "GitHub API and Git operations policy"
4
+
5
+ files:
6
+ - pattern: ".github/**"
7
+ action: confirm
8
+ reason: "GitHub Actions workflow modification"
9
+ - pattern: "*.github-actions-*"
10
+ action: confirm
11
+ reason: "GitHub Actions artifact"
12
+
13
+ commands:
14
+ - pattern: "git push.*--force"
15
+ action: block
16
+ reason: "Force push to remote"
17
+ - pattern: "git\\s+remote\\s+set-url"
18
+ action: confirm
19
+ reason: "Changing git remote URL"
20
+ - pattern: "gh\\s+repo\\s+delete"
21
+ action: block
22
+ reason: "Repository deletion via GitHub CLI"
23
+ - pattern: "gh\\s+secret\\s+set"
24
+ action: confirm
25
+ reason: "Setting GitHub repository secrets"
26
+
27
+ tools:
28
+ - name: github_create_issue
29
+ action: allow
30
+ - name: github_create_pr
31
+ action: allow
32
+ - name: github_merge_pr
33
+ action: confirm
34
+ - name: github_delete_branch
35
+ action: confirm
36
+ - name: github_delete_repo
37
+ action: block
@@ -0,0 +1,26 @@
1
+ preset:
2
+ name: slack
3
+ description: "Slack API and bot operations policy"
4
+
5
+ commands:
6
+ - pattern: "slack-cli.*delete"
7
+ action: block
8
+ reason: "Slack channel/message deletion"
9
+
10
+ tools:
11
+ - name: slack_post_message
12
+ action: confirm
13
+ reason: "Sending Slack messages requires approval"
14
+ - name: slack_upload_file
15
+ action: confirm
16
+ reason: "File uploads to Slack require approval"
17
+ - name: slack_delete_message
18
+ action: block
19
+ reason: "Message deletion blocked"
20
+ - name: slack_invite_user
21
+ action: confirm
22
+ reason: "User invitations require approval"
23
+ - name: slack_read_messages
24
+ action: allow
25
+ - name: slack_list_channels
26
+ action: allow
@@ -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)
@@ -0,0 +1,191 @@
1
+ """SSRF (Server-Side Request Forgery) validation for user-supplied URLs.
2
+
3
+ Validates that endpoint URLs do not resolve to private/internal IP addresses.
4
+ Ported from NVIDIA NemoClaw's ssrf.ts with additions for Python ecosystem.
5
+
6
+ Usage::
7
+
8
+ from forcefield.ssrf import validate_endpoint_url, is_private_ip
9
+
10
+ # Raises ValueError if URL resolves to private IP
11
+ validate_endpoint_url("https://api.openai.com/v1/chat/completions")
12
+
13
+ # Direct IP check
14
+ is_private_ip("10.0.0.1") # True
15
+ is_private_ip("8.8.8.8") # False
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import ipaddress
21
+ import socket
22
+ from typing import List, Optional, Tuple
23
+ from urllib.parse import urlparse
24
+
25
+ # Private/internal network ranges that must never be reachable via user-supplied URLs.
26
+ # Covers RFC 1918, RFC 6598 (CGNAT), link-local, loopback, IPv6 ULA, and
27
+ # cloud metadata endpoints.
28
+ _PRIVATE_NETWORKS = [
29
+ ipaddress.ip_network("127.0.0.0/8"), # Loopback
30
+ ipaddress.ip_network("10.0.0.0/8"), # RFC 1918
31
+ ipaddress.ip_network("172.16.0.0/12"), # RFC 1918
32
+ ipaddress.ip_network("192.168.0.0/16"), # RFC 1918
33
+ ipaddress.ip_network("169.254.0.0/16"), # Link-local
34
+ ipaddress.ip_network("100.64.0.0/10"), # RFC 6598 CGNAT
35
+ ipaddress.ip_network("0.0.0.0/8"), # "This" network
36
+ ipaddress.ip_network("192.0.0.0/24"), # IETF Protocol Assignments
37
+ ipaddress.ip_network("192.0.2.0/24"), # TEST-NET-1
38
+ ipaddress.ip_network("198.51.100.0/24"), # TEST-NET-2
39
+ ipaddress.ip_network("203.0.113.0/24"), # TEST-NET-3
40
+ ipaddress.ip_network("224.0.0.0/4"), # Multicast
41
+ ipaddress.ip_network("240.0.0.0/4"), # Reserved
42
+ ipaddress.ip_network("::1/128"), # IPv6 loopback
43
+ ipaddress.ip_network("fd00::/8"), # IPv6 ULA
44
+ ipaddress.ip_network("fe80::/10"), # IPv6 link-local
45
+ ipaddress.ip_network("::ffff:0:0/96"), # IPv4-mapped IPv6
46
+ ipaddress.ip_network("fc00::/7"), # IPv6 unique local
47
+ ]
48
+
49
+ _ALLOWED_SCHEMES = frozenset({"https", "http"})
50
+
51
+ # Cloud metadata IPs that must always be blocked even if they appear public.
52
+ _CLOUD_METADATA_IPS = frozenset({
53
+ "169.254.169.254", # AWS, GCP, Azure metadata
54
+ "169.254.170.2", # AWS ECS task metadata
55
+ "fd00:ec2::254", # AWS IPv6 metadata
56
+ })
57
+
58
+
59
+ def is_private_ip(addr: str) -> bool:
60
+ """Check if an IP address is in a private/internal range.
61
+
62
+ Also catches cloud metadata IPs and IPv4-mapped IPv6 addresses.
63
+ """
64
+ if addr in _CLOUD_METADATA_IPS:
65
+ return True
66
+
67
+ try:
68
+ ip = ipaddress.ip_address(addr)
69
+ except ValueError:
70
+ return False
71
+
72
+ # IPv4-mapped IPv6 (::ffff:x.x.x.x) -- extract the embedded IPv4
73
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped:
74
+ ip = ip.ipv4_mapped
75
+
76
+ for network in _PRIVATE_NETWORKS:
77
+ try:
78
+ if ip in network:
79
+ return True
80
+ except TypeError:
81
+ continue
82
+
83
+ return False
84
+
85
+
86
+ def _resolve_hostname(hostname: str) -> List[Tuple[str, int]]:
87
+ """Resolve a hostname to all IP addresses via DNS.
88
+
89
+ Returns list of (address, family) tuples.
90
+ Raises ValueError on resolution failure.
91
+ """
92
+ try:
93
+ results = socket.getaddrinfo(
94
+ hostname, None,
95
+ socket.AF_UNSPEC,
96
+ socket.SOCK_STREAM,
97
+ )
98
+ except socket.gaierror as exc:
99
+ raise ValueError(f"Cannot resolve hostname '{hostname}': {exc}") from exc
100
+
101
+ addresses = []
102
+ seen = set()
103
+ for family, _type, _proto, _canonname, sockaddr in results:
104
+ addr = sockaddr[0]
105
+ if addr not in seen:
106
+ seen.add(addr)
107
+ addresses.append((addr, family))
108
+
109
+ if not addresses:
110
+ raise ValueError(f"Hostname '{hostname}' resolved to zero addresses")
111
+
112
+ return addresses
113
+
114
+
115
+ def validate_endpoint_url(
116
+ url: str,
117
+ *,
118
+ allowed_schemes: Optional[frozenset] = None,
119
+ allow_private: bool = False,
120
+ skip_dns: bool = False,
121
+ ) -> str:
122
+ """Validate that an endpoint URL is safe to connect to.
123
+
124
+ Checks:
125
+ 1. URL is well-formed with an allowed scheme (https/http).
126
+ 2. Hostname is not an IP literal in a private range.
127
+ 3. DNS resolution does not return any private/internal addresses.
128
+
129
+ Args:
130
+ url: The URL to validate.
131
+ allowed_schemes: Override the default allowed schemes.
132
+ allow_private: If True, skip private IP checks (for testing).
133
+ skip_dns: If True, skip DNS resolution (for unit tests).
134
+
135
+ Returns:
136
+ The validated URL (unchanged).
137
+
138
+ Raises:
139
+ ValueError: If the URL is invalid, uses a disallowed scheme,
140
+ or resolves to a private/internal address.
141
+ """
142
+ schemes = allowed_schemes or _ALLOWED_SCHEMES
143
+
144
+ try:
145
+ parsed = urlparse(url)
146
+ except Exception as exc:
147
+ raise ValueError(f"Malformed URL: {url}") from exc
148
+
149
+ if not parsed.scheme:
150
+ raise ValueError(f"No scheme in URL: {url}")
151
+
152
+ if parsed.scheme.lower() not in schemes:
153
+ allowed = ", ".join(f"{s}://" for s in sorted(schemes))
154
+ raise ValueError(
155
+ f"Unsupported URL scheme '{parsed.scheme}://'. Only {allowed} are allowed."
156
+ )
157
+
158
+ hostname = parsed.hostname
159
+ if not hostname:
160
+ raise ValueError(f"No hostname found in URL: {url}")
161
+
162
+ if allow_private:
163
+ return url
164
+
165
+ # Check if hostname is already an IP literal
166
+ try:
167
+ ip = ipaddress.ip_address(hostname)
168
+ if is_private_ip(str(ip)):
169
+ raise ValueError(
170
+ f"Endpoint URL contains private/internal IP address {ip}. "
171
+ "Connections to internal networks are not allowed."
172
+ )
173
+ return url
174
+ except ValueError as exc:
175
+ if "private/internal" in str(exc) or "Connections to internal" in str(exc):
176
+ raise
177
+ # Not an IP literal, continue to DNS resolution
178
+
179
+ if skip_dns:
180
+ return url
181
+
182
+ # DNS resolution -- check ALL resolved addresses
183
+ addresses = _resolve_hostname(hostname)
184
+ for addr, _family in addresses:
185
+ if is_private_ip(addr):
186
+ raise ValueError(
187
+ f"Endpoint URL resolves to private/internal address {addr}. "
188
+ "Connections to internal networks are not allowed."
189
+ )
190
+
191
+ return url
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forcefield
3
- Version: 0.7.2
3
+ Version: 0.7.4
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
@@ -24,6 +24,7 @@ forcefield/py.typed
24
24
  forcefield/ratelimit.py
25
25
  forcefield/scanner.py
26
26
  forcefield/session.py
27
+ forcefield/ssrf.py
27
28
  forcefield/telemetry.py
28
29
  forcefield/templates.py
29
30
  forcefield/tools.py
@@ -38,6 +39,10 @@ forcefield/constitutions/__init__.py
38
39
  forcefield/constitutions/default.yaml
39
40
  forcefield/constitutions/permissive.yaml
40
41
  forcefield/constitutions/strict.yaml
42
+ forcefield/constitutions/presets/database.yaml
43
+ forcefield/constitutions/presets/docker.yaml
44
+ forcefield/constitutions/presets/github.yaml
45
+ forcefield/constitutions/presets/slack.yaml
41
46
  forcefield/evals/__init__.py
42
47
  forcefield/evals/governance.yaml
43
48
  forcefield/evals/safety.yaml
@@ -45,6 +50,7 @@ forcefield/evals/security.yaml
45
50
  forcefield/integrations/__init__.py
46
51
  forcefield/integrations/fastapi.py
47
52
  forcefield/integrations/langchain.py
53
+ forcefield/integrations/llamaindex.py
48
54
  forcefield/integrations/openai.py
49
55
  forcefield/models/__init__.py
50
56
  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.4"
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]
@@ -85,7 +87,7 @@ where = ["."]
85
87
  include = ["forcefield*"]
86
88
 
87
89
  [tool.setuptools.package-data]
88
- forcefield = ["models/*.joblib", "models/*.onnx", "py.typed", "constitutions/*.yaml", "evals/*.yaml"]
90
+ forcefield = ["models/*.joblib", "models/*.onnx", "py.typed", "constitutions/*.yaml", "constitutions/presets/*.yaml", "evals/*.yaml"]
89
91
 
90
92
  [tool.pytest.ini_options]
91
93
  testpaths = ["tests"]
@@ -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