forcefield 0.7.3__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.3 → forcefield-0.7.4}/PKG-INFO +1 -1
  2. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/__init__.py +4 -1
  3. {forcefield-0.7.3 → 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/ssrf.py +191 -0
  9. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield.egg-info/PKG-INFO +1 -1
  10. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield.egg-info/SOURCES.txt +5 -0
  11. {forcefield-0.7.3 → forcefield-0.7.4}/pyproject.toml +2 -2
  12. {forcefield-0.7.3 → forcefield-0.7.4}/LICENSE +0 -0
  13. {forcefield-0.7.3 → forcefield-0.7.4}/README.md +0 -0
  14. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/__main__.py +0 -0
  15. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/abuse.py +0 -0
  16. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/attacks.py +0 -0
  17. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/audit.py +0 -0
  18. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/cli.py +0 -0
  19. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/cloud.py +0 -0
  20. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/commands.py +0 -0
  21. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/config.py +0 -0
  22. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/constitutions/__init__.py +0 -0
  23. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/constitutions/default.yaml +0 -0
  24. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/constitutions/permissive.yaml +0 -0
  25. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/constitutions/strict.yaml +0 -0
  26. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/endpoint_scanner.py +0 -0
  27. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/evals/__init__.py +0 -0
  28. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/evals/governance.yaml +0 -0
  29. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/evals/safety.yaml +0 -0
  30. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/evals/security.yaml +0 -0
  31. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/exfiltration.py +0 -0
  32. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/files.py +0 -0
  33. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/guard.py +0 -0
  34. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/integrations/__init__.py +0 -0
  35. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/integrations/fastapi.py +0 -0
  36. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/integrations/langchain.py +0 -0
  37. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/integrations/llamaindex.py +0 -0
  38. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/integrations/openai.py +0 -0
  39. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/integrity.py +0 -0
  40. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/ml.py +0 -0
  41. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/models/__init__.py +0 -0
  42. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/models/tfidf_model.joblib +0 -0
  43. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/models/tfidf_model.onnx +0 -0
  44. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/moderation.py +0 -0
  45. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/obfuscation.py +0 -0
  46. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/pii.py +0 -0
  47. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/py.typed +0 -0
  48. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/ratelimit.py +0 -0
  49. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/scanner.py +0 -0
  50. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/session.py +0 -0
  51. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/telemetry.py +0 -0
  52. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/templates.py +0 -0
  53. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/tools.py +0 -0
  54. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield/types.py +0 -0
  55. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield.egg-info/dependency_links.txt +0 -0
  56. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield.egg-info/entry_points.txt +0 -0
  57. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield.egg-info/requires.txt +0 -0
  58. {forcefield-0.7.3 → forcefield-0.7.4}/forcefield.egg-info/top_level.txt +0 -0
  59. {forcefield-0.7.3 → forcefield-0.7.4}/setup.cfg +0 -0
  60. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_attacks.py +0 -0
  61. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_commands.py +0 -0
  62. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_constitution.py +0 -0
  63. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_endpoint_scanner.py +0 -0
  64. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_evals.py +0 -0
  65. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_files.py +0 -0
  66. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_guard.py +0 -0
  67. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_integrity.py +0 -0
  68. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_ml.py +0 -0
  69. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_moderation.py +0 -0
  70. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_pii.py +0 -0
  71. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_scanner.py +0 -0
  72. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_session.py +0 -0
  73. {forcefield-0.7.3 → forcefield-0.7.4}/tests/test_telemetry.py +0 -0
  74. {forcefield-0.7.3 → 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.3
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
@@ -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.3"
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,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.3
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
@@ -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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "forcefield"
7
- version = "0.7.3"
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"}
@@ -87,7 +87,7 @@ where = ["."]
87
87
  include = ["forcefield*"]
88
88
 
89
89
  [tool.setuptools.package-data]
90
- 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"]
91
91
 
92
92
  [tool.pytest.ini_options]
93
93
  testpaths = ["tests"]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes