cpex-lasso 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ dist/
@@ -0,0 +1,6 @@
1
+ Copyright (c) 2026 Lasso Security. All rights reserved.
2
+
3
+ This software is proprietary to Lasso Security. It may be used only by Lasso
4
+ Security customers, with Lasso Security's services, under their agreement with
5
+ Lasso Security. No other right to use, copy, modify, distribute or sublicense
6
+ it is granted.
@@ -0,0 +1,193 @@
1
+ Metadata-Version: 2.5
2
+ Name: cpex-lasso
3
+ Version: 0.1.0
4
+ Summary: Lasso Security guardrail plugin for ContextForge
5
+ Project-URL: Homepage, https://lasso.security
6
+ Project-URL: Documentation, https://lasso-security.gitbook.io/lasso-security/
7
+ Author-email: Lasso Security <support@lasso.security>
8
+ License-Expression: LicenseRef-Proprietary
9
+ License-File: LICENSE
10
+ Keywords: agents,ai,contextforge,guardrails,llm,mcp,security
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Security
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: cpex<0.2,>=0.1.4
19
+ Requires-Dist: httpx>=0.27
20
+ Requires-Dist: pydantic>=2
21
+ Provides-Extra: conformance
22
+ Requires-Dist: mcp-contextforge-gateway==1.1.1; extra == 'conformance'
23
+ Requires-Dist: pyyaml>=6; extra == 'conformance'
24
+ Provides-Extra: lint
25
+ Requires-Dist: mypy>=1.13; extra == 'lint'
26
+ Requires-Dist: ruff>=0.8; extra == 'lint'
27
+ Provides-Extra: test
28
+ Requires-Dist: pytest>=8; extra == 'test'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # cpex-lasso
32
+
33
+ Lasso Security guardrail plugin for [ContextForge](https://github.com/IBM/mcp-context-forge), IBM's MCP gateway. It sends tool calls, tool results, prompts and resources to Lasso and blocks or masks them inline, before they reach the tool or the agent.
34
+
35
+ Tested with ContextForge 1.1.1 (plugin framework `cpex` 0.1.4).
36
+
37
+ ## How it works
38
+
39
+ ContextForge runs cpex-lasso inside its plugin pipeline. At each check the plugin sends the content to Lasso and acts on Lasso's answer before ContextForge goes on. A tool call is checked twice, once on the way in and once on the way out:
40
+
41
+ ```text
42
+ MCP client ContextForge + cpex-lasso Lasso MCP server
43
+ | | | |
44
+ |--- tools/call ------------>| | |
45
+ | |--- tool name + arguments ---->| |
46
+ | |<-- allow / block / mask ------| |
47
+ | |--- call the tool (if allowed) --------------->|
48
+ | |<-- tool result -------------------------------|
49
+ | |--- tool result -------------->| |
50
+ | |<-- allow / block / mask ------| |
51
+ |<-- result, or tool error --| | |
52
+ ```
53
+
54
+ - **Allow**: the content goes on unchanged. Findings that do not block are logged.
55
+ - **Block**: ContextForge refuses the call. A call blocked on the way in never reaches the tool; a result blocked on the way out never reaches the agent.
56
+ - **Mask** (only with `mask: true`): Lasso returns the content with the sensitive parts replaced, the plugin writes it back in place, and the call goes on with the masked content.
57
+
58
+ Prompts and resources get one check each, after ContextForge renders the prompt or reads the resource. If Lasso cannot be reached, ContextForge's `on_error` setting decides whether the call passes or is refused (see "Fail-open or fail-closed" below).
59
+
60
+ ## What it checks
61
+
62
+ | ContextForge hook | What is sent to Lasso | What Lasso can do |
63
+ |---|---|---|
64
+ | `tool_pre_invoke` | the tool's name and arguments | block the call, or mask the arguments before the tool runs |
65
+ | `tool_post_invoke` | the tool's result | block the result, or mask it before the agent sees it |
66
+ | `prompt_post_fetch` | the rendered prompt text | block or mask |
67
+ | `resource_post_fetch` | the resource text | block or mask |
68
+
69
+ Not covered: agent-to-agent (A2A) traffic, tool descriptions at registration or listing, and ContextForge's LLM proxy.
70
+
71
+ ## Install
72
+
73
+ Install the package into the Python environment ContextForge runs in. For a container deployment that means building it into the gateway image.
74
+
75
+ ```bash
76
+ pip install cpex-lasso
77
+ ```
78
+
79
+ Requires Python 3.12 or newer.
80
+
81
+ ## Configure
82
+
83
+ ### 1. Environment
84
+
85
+ | Variable | Value | Why |
86
+ |---|---|---|
87
+ | `PLUGINS_ENABLED` | `true` | turns on ContextForge's plugin framework |
88
+ | `PLUGINS_CONFIG_FILE` | path to your plugins YAML | where the block below lives |
89
+ | `PLUGINS_FAIL_ON_PLUGIN_ERROR` | `true` | without it, ContextForge silently skips a plugin that fails to load and runs unprotected |
90
+ | `LASSO_API_KEY` | your Lasso application API key | the plugin refuses to load without it |
91
+
92
+ ### 2. Plugin block
93
+
94
+ <!-- x-release-please-start-version -->
95
+ ```yaml
96
+ plugins:
97
+ - name: "LassoGuardrail"
98
+ kind: "cpex_lasso.LassoPlugin"
99
+ version: "0.1.0"
100
+ hooks: ["tool_pre_invoke", "tool_post_invoke", "prompt_post_fetch", "resource_post_fetch"]
101
+ mode: "sequential"
102
+ on_error: "ignore" # default: fail-open. "fail" = fail-closed
103
+ priority: 10
104
+ config:
105
+ mask: false
106
+ timeout_seconds: 5
107
+ ```
108
+ <!-- x-release-please-end -->
109
+
110
+ ContextForge reads the plugin list at startup, so restart it after changing this file.
111
+
112
+ ### 3. Settings
113
+
114
+ Everything under `config` is optional.
115
+
116
+ | Setting | Default | Meaning |
117
+ |---|---|---|
118
+ | `base_url` | `https://server.lasso.security/gateway/v3` | your Lasso gateway URL |
119
+ | `api_key_env` | `LASSO_API_KEY` | name of the environment variable that holds the API key |
120
+ | `mask` | `false` | when `true`, content Lasso marks for masking is rewritten instead of passed through |
121
+ | `timeout_seconds` | `5` | how long to wait for Lasso on each check |
122
+
123
+ A misspelled setting stops the plugin from loading.
124
+
125
+ ### 4. Fail-open or fail-closed
126
+
127
+ This is ContextForge's own `on_error` setting on the plugin block. It decides what happens when Lasso cannot be reached, times out, or answers with an error.
128
+
129
+ | `on_error` | When Lasso is unavailable |
130
+ |---|---|
131
+ | `ignore` (default) | the call passes unscanned (fail-open) |
132
+ | `fail` | the call is refused (fail-closed) |
133
+
134
+ `ignore` is the default for cpex-lasso, as in the config block above. Keep the line in your config: without it, ContextForge falls back to `fail`.
135
+
136
+ Keep `mode: "sequential"`. It is the only mode in which a plugin can both block and modify.
137
+
138
+ ### 5. Turn on tool policies in Lasso
139
+
140
+ Lasso classifies tool traffic only when a policy or rule covers it. In the Lasso dashboard, enable the detections you want for **Tool call** and **Tool output**. Until you do, tool calls and results pass with no findings.
141
+
142
+ ## What the MCP client sees
143
+
144
+ MCP clients connect to a ContextForge virtual server over Streamable HTTP (`/servers/<id>/mcp`). There, a call the plugin refuses comes back as a failed tool call: HTTP 200, `isError: true`, and one text block with the hook and the code, for example:
145
+
146
+ ```text
147
+ tool_pre_invoke blocked by plugin LassoGuardrail: LASSO_BLOCK - Blocked by Lasso (Lasso policy blocked this content)
148
+ ```
149
+
150
+ | Situation | Tool call result |
151
+ |---|---|
152
+ | Lasso blocks the content | `isError: true`, code `LASSO_BLOCK` |
153
+ | Lasso masks the content and `mask` is `true` | the call succeeds with the masked content |
154
+ | Lasso only alerts | the call succeeds; the finding is logged |
155
+ | Lasso is unavailable, `on_error: ignore` | the call succeeds unscanned; an error is logged |
156
+ | Lasso is unavailable, `on_error: fail` | JSON-RPC error `-32603` |
157
+ | Lasso rejects the API key (HTTP 401) | `isError: true`, code `LASSO_AUTH_FAILED`, **whatever `on_error` says** |
158
+ | Lasso asks to mask content that cannot be rewritten safely | `isError: true`, code `LASSO_MASKING_FAILED` |
159
+
160
+ A blocked prompt or resource comes back as a JSON-RPC error with the same text, for example `prompt_post_fetch blocked by plugin LassoGuardrail: LASSO_BLOCK - ...`.
161
+
162
+ A rejected API key refuses every call on purpose. Under `on_error: ignore` it would otherwise switch scanning off without anyone noticing.
163
+
164
+ ContextForge's own JSON-RPC endpoint, `/rpc`, which the admin UI's tool test uses, returns a refusal as an HTTP error instead: HTTP 403 and JSON-RPC error `-32602` for a block or a masking failure, HTTP 503 for a rejected key. The code and the block's details are under `error.data`.
165
+
166
+ A block's details in the `/rpc` response hold two lists:
167
+
168
+ - `findings`: each detection once, as `name`, `category`, `action` and `severity`. The category is the one the Lasso rule editor shows, for example `PERSONAL_IDENTIFIABLE_INFORMATION`.
169
+ - `intent_findings`: violations of the application's intent, as `violations`, `action` and `monitor_only`. A block caused by intent alone has an empty `findings` list.
170
+
171
+ ## What Lasso receives
172
+
173
+ - The tool's name, description and input schema, its arguments and its result.
174
+ - Prompt and resource text.
175
+ - The ContextForge user's email, the MCP session id, the team id and the id of the upstream MCP server.
176
+
177
+ The credentials ContextForge stores for upstream MCP servers are never sent.
178
+
179
+ ## Things to know
180
+
181
+ - **Do not enable Code detection for tool calls.** Lasso classifies a tool call's arguments as their JSON text, and code detection treats that JSON as code, so every tool call is blocked.
182
+ - **Auto mask does not stop prompt injection.** An injection has nothing to mask, so under an Auto mask action it passes with a finding. Use Block for those detections.
183
+ - **Findings that do not block are logged at INFO.** ContextForge's default `LOG_LEVEL` is `ERROR`, which hides them.
184
+ - **The first check is slower.** Each team or tool context creates its own plugin instance on first use.
185
+
186
+ ## Development
187
+
188
+ ```bash
189
+ pip install -e ".[test]"
190
+ pytest -q
191
+ ```
192
+
193
+ The conformance run against a real ContextForge is described in [conformance/README.md](https://github.com/lasso-security/cpex-lasso/blob/main/conformance/README.md). Releases are described in [RELEASING.md](https://github.com/lasso-security/cpex-lasso/blob/main/RELEASING.md).
@@ -0,0 +1,163 @@
1
+ # cpex-lasso
2
+
3
+ Lasso Security guardrail plugin for [ContextForge](https://github.com/IBM/mcp-context-forge), IBM's MCP gateway. It sends tool calls, tool results, prompts and resources to Lasso and blocks or masks them inline, before they reach the tool or the agent.
4
+
5
+ Tested with ContextForge 1.1.1 (plugin framework `cpex` 0.1.4).
6
+
7
+ ## How it works
8
+
9
+ ContextForge runs cpex-lasso inside its plugin pipeline. At each check the plugin sends the content to Lasso and acts on Lasso's answer before ContextForge goes on. A tool call is checked twice, once on the way in and once on the way out:
10
+
11
+ ```text
12
+ MCP client ContextForge + cpex-lasso Lasso MCP server
13
+ | | | |
14
+ |--- tools/call ------------>| | |
15
+ | |--- tool name + arguments ---->| |
16
+ | |<-- allow / block / mask ------| |
17
+ | |--- call the tool (if allowed) --------------->|
18
+ | |<-- tool result -------------------------------|
19
+ | |--- tool result -------------->| |
20
+ | |<-- allow / block / mask ------| |
21
+ |<-- result, or tool error --| | |
22
+ ```
23
+
24
+ - **Allow**: the content goes on unchanged. Findings that do not block are logged.
25
+ - **Block**: ContextForge refuses the call. A call blocked on the way in never reaches the tool; a result blocked on the way out never reaches the agent.
26
+ - **Mask** (only with `mask: true`): Lasso returns the content with the sensitive parts replaced, the plugin writes it back in place, and the call goes on with the masked content.
27
+
28
+ Prompts and resources get one check each, after ContextForge renders the prompt or reads the resource. If Lasso cannot be reached, ContextForge's `on_error` setting decides whether the call passes or is refused (see "Fail-open or fail-closed" below).
29
+
30
+ ## What it checks
31
+
32
+ | ContextForge hook | What is sent to Lasso | What Lasso can do |
33
+ |---|---|---|
34
+ | `tool_pre_invoke` | the tool's name and arguments | block the call, or mask the arguments before the tool runs |
35
+ | `tool_post_invoke` | the tool's result | block the result, or mask it before the agent sees it |
36
+ | `prompt_post_fetch` | the rendered prompt text | block or mask |
37
+ | `resource_post_fetch` | the resource text | block or mask |
38
+
39
+ Not covered: agent-to-agent (A2A) traffic, tool descriptions at registration or listing, and ContextForge's LLM proxy.
40
+
41
+ ## Install
42
+
43
+ Install the package into the Python environment ContextForge runs in. For a container deployment that means building it into the gateway image.
44
+
45
+ ```bash
46
+ pip install cpex-lasso
47
+ ```
48
+
49
+ Requires Python 3.12 or newer.
50
+
51
+ ## Configure
52
+
53
+ ### 1. Environment
54
+
55
+ | Variable | Value | Why |
56
+ |---|---|---|
57
+ | `PLUGINS_ENABLED` | `true` | turns on ContextForge's plugin framework |
58
+ | `PLUGINS_CONFIG_FILE` | path to your plugins YAML | where the block below lives |
59
+ | `PLUGINS_FAIL_ON_PLUGIN_ERROR` | `true` | without it, ContextForge silently skips a plugin that fails to load and runs unprotected |
60
+ | `LASSO_API_KEY` | your Lasso application API key | the plugin refuses to load without it |
61
+
62
+ ### 2. Plugin block
63
+
64
+ <!-- x-release-please-start-version -->
65
+ ```yaml
66
+ plugins:
67
+ - name: "LassoGuardrail"
68
+ kind: "cpex_lasso.LassoPlugin"
69
+ version: "0.1.0"
70
+ hooks: ["tool_pre_invoke", "tool_post_invoke", "prompt_post_fetch", "resource_post_fetch"]
71
+ mode: "sequential"
72
+ on_error: "ignore" # default: fail-open. "fail" = fail-closed
73
+ priority: 10
74
+ config:
75
+ mask: false
76
+ timeout_seconds: 5
77
+ ```
78
+ <!-- x-release-please-end -->
79
+
80
+ ContextForge reads the plugin list at startup, so restart it after changing this file.
81
+
82
+ ### 3. Settings
83
+
84
+ Everything under `config` is optional.
85
+
86
+ | Setting | Default | Meaning |
87
+ |---|---|---|
88
+ | `base_url` | `https://server.lasso.security/gateway/v3` | your Lasso gateway URL |
89
+ | `api_key_env` | `LASSO_API_KEY` | name of the environment variable that holds the API key |
90
+ | `mask` | `false` | when `true`, content Lasso marks for masking is rewritten instead of passed through |
91
+ | `timeout_seconds` | `5` | how long to wait for Lasso on each check |
92
+
93
+ A misspelled setting stops the plugin from loading.
94
+
95
+ ### 4. Fail-open or fail-closed
96
+
97
+ This is ContextForge's own `on_error` setting on the plugin block. It decides what happens when Lasso cannot be reached, times out, or answers with an error.
98
+
99
+ | `on_error` | When Lasso is unavailable |
100
+ |---|---|
101
+ | `ignore` (default) | the call passes unscanned (fail-open) |
102
+ | `fail` | the call is refused (fail-closed) |
103
+
104
+ `ignore` is the default for cpex-lasso, as in the config block above. Keep the line in your config: without it, ContextForge falls back to `fail`.
105
+
106
+ Keep `mode: "sequential"`. It is the only mode in which a plugin can both block and modify.
107
+
108
+ ### 5. Turn on tool policies in Lasso
109
+
110
+ Lasso classifies tool traffic only when a policy or rule covers it. In the Lasso dashboard, enable the detections you want for **Tool call** and **Tool output**. Until you do, tool calls and results pass with no findings.
111
+
112
+ ## What the MCP client sees
113
+
114
+ MCP clients connect to a ContextForge virtual server over Streamable HTTP (`/servers/<id>/mcp`). There, a call the plugin refuses comes back as a failed tool call: HTTP 200, `isError: true`, and one text block with the hook and the code, for example:
115
+
116
+ ```text
117
+ tool_pre_invoke blocked by plugin LassoGuardrail: LASSO_BLOCK - Blocked by Lasso (Lasso policy blocked this content)
118
+ ```
119
+
120
+ | Situation | Tool call result |
121
+ |---|---|
122
+ | Lasso blocks the content | `isError: true`, code `LASSO_BLOCK` |
123
+ | Lasso masks the content and `mask` is `true` | the call succeeds with the masked content |
124
+ | Lasso only alerts | the call succeeds; the finding is logged |
125
+ | Lasso is unavailable, `on_error: ignore` | the call succeeds unscanned; an error is logged |
126
+ | Lasso is unavailable, `on_error: fail` | JSON-RPC error `-32603` |
127
+ | Lasso rejects the API key (HTTP 401) | `isError: true`, code `LASSO_AUTH_FAILED`, **whatever `on_error` says** |
128
+ | Lasso asks to mask content that cannot be rewritten safely | `isError: true`, code `LASSO_MASKING_FAILED` |
129
+
130
+ A blocked prompt or resource comes back as a JSON-RPC error with the same text, for example `prompt_post_fetch blocked by plugin LassoGuardrail: LASSO_BLOCK - ...`.
131
+
132
+ A rejected API key refuses every call on purpose. Under `on_error: ignore` it would otherwise switch scanning off without anyone noticing.
133
+
134
+ ContextForge's own JSON-RPC endpoint, `/rpc`, which the admin UI's tool test uses, returns a refusal as an HTTP error instead: HTTP 403 and JSON-RPC error `-32602` for a block or a masking failure, HTTP 503 for a rejected key. The code and the block's details are under `error.data`.
135
+
136
+ A block's details in the `/rpc` response hold two lists:
137
+
138
+ - `findings`: each detection once, as `name`, `category`, `action` and `severity`. The category is the one the Lasso rule editor shows, for example `PERSONAL_IDENTIFIABLE_INFORMATION`.
139
+ - `intent_findings`: violations of the application's intent, as `violations`, `action` and `monitor_only`. A block caused by intent alone has an empty `findings` list.
140
+
141
+ ## What Lasso receives
142
+
143
+ - The tool's name, description and input schema, its arguments and its result.
144
+ - Prompt and resource text.
145
+ - The ContextForge user's email, the MCP session id, the team id and the id of the upstream MCP server.
146
+
147
+ The credentials ContextForge stores for upstream MCP servers are never sent.
148
+
149
+ ## Things to know
150
+
151
+ - **Do not enable Code detection for tool calls.** Lasso classifies a tool call's arguments as their JSON text, and code detection treats that JSON as code, so every tool call is blocked.
152
+ - **Auto mask does not stop prompt injection.** An injection has nothing to mask, so under an Auto mask action it passes with a finding. Use Block for those detections.
153
+ - **Findings that do not block are logged at INFO.** ContextForge's default `LOG_LEVEL` is `ERROR`, which hides them.
154
+ - **The first check is slower.** Each team or tool context creates its own plugin instance on first use.
155
+
156
+ ## Development
157
+
158
+ ```bash
159
+ pip install -e ".[test]"
160
+ pytest -q
161
+ ```
162
+
163
+ The conformance run against a real ContextForge is described in [conformance/README.md](https://github.com/lasso-security/cpex-lasso/blob/main/conformance/README.md). Releases are described in [RELEASING.md](https://github.com/lasso-security/cpex-lasso/blob/main/RELEASING.md).
@@ -0,0 +1,60 @@
1
+ [project]
2
+ name = "cpex-lasso"
3
+ version = "0.1.0"
4
+ description = "Lasso Security guardrail plugin for ContextForge"
5
+ readme = "README.md"
6
+ license = "LicenseRef-Proprietary"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ authors = [{ name = "Lasso Security", email = "support@lasso.security" }]
10
+ keywords = ["ai", "agents", "security", "mcp", "contextforge", "guardrails", "llm"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Topic :: Security",
18
+ ]
19
+ dependencies = ["cpex>=0.1.4,<0.2", "httpx>=0.27", "pydantic>=2"]
20
+
21
+ [project.optional-dependencies]
22
+ test = ["pytest>=8"]
23
+ conformance = ["mcp-contextforge-gateway==1.1.1", "pyyaml>=6"]
24
+ lint = ["ruff>=0.8", "mypy>=1.13"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://lasso.security"
28
+ Documentation = "https://lasso-security.gitbook.io/lasso-security/"
29
+
30
+ [build-system]
31
+ requires = ["hatchling"]
32
+ build-backend = "hatchling.build"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/cpex_lasso"]
36
+
37
+ # The sdist is public on PyPI. Without this list hatchling ships every tracked file.
38
+ [tool.hatch.build.targets.sdist]
39
+ include = ["/src", "/README.md", "/LICENSE"]
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+
44
+ [tool.ruff]
45
+ target-version = "py312"
46
+ line-length = 150
47
+
48
+ [tool.ruff.lint]
49
+ select = ["E", "F", "W", "I", "UP", "B"]
50
+
51
+ [tool.mypy]
52
+ python_version = "3.12"
53
+ warn_unused_ignores = true
54
+ warn_redundant_casts = true
55
+ files = ["src"]
56
+
57
+ [[tool.mypy.overrides]]
58
+ # cpex ships no type information.
59
+ module = ["cpex", "cpex.*"]
60
+ ignore_missing_imports = true
@@ -0,0 +1,3 @@
1
+ from cpex_lasso.plugin import LassoPlugin
2
+
3
+ __all__ = ["LassoPlugin"]
@@ -0,0 +1,46 @@
1
+ from collections.abc import Mapping
2
+ from typing import Any
3
+
4
+ import httpx
5
+
6
+ API_KEY_HEADER = "lasso-api-key"
7
+ ERROR_BODY_LOG_LIMIT = 500
8
+
9
+
10
+ class LassoRequestError(RuntimeError):
11
+ """The message is shown to MCP clients by ContextForge, so the response body stays on `body` for logs only."""
12
+
13
+ def __init__(self, status_code: int, body: str):
14
+ super().__init__(f"Lasso returned HTTP {status_code}")
15
+ self.status_code = status_code
16
+ self.body = body[:ERROR_BODY_LOG_LIMIT]
17
+
18
+
19
+ class LassoAuthError(LassoRequestError):
20
+ pass
21
+
22
+
23
+ class LassoClient:
24
+ def __init__(self, base_url: str, api_key: str, timeout_seconds: float, http: httpx.AsyncClient | None = None):
25
+ self._http = http or httpx.AsyncClient(
26
+ base_url=base_url.rstrip("/"),
27
+ headers={API_KEY_HEADER: api_key},
28
+ timeout=timeout_seconds,
29
+ )
30
+
31
+ async def classify(self, request: Mapping[str, Any], mask: bool) -> dict[str, Any]:
32
+ path = "/classifix" if mask else "/classify"
33
+ response = await self._http.post(path, json=request)
34
+ return self._success_body(response)
35
+
36
+ async def aclose(self) -> None:
37
+ await self._http.aclose()
38
+
39
+ @staticmethod
40
+ def _success_body(response: httpx.Response) -> dict[str, Any]:
41
+ if response.is_success:
42
+ return response.json()
43
+ # Only 401 means a rejected key. Lasso's edge also answers 403 when it rate-limits, which is an outage, not a bad key.
44
+ if response.status_code == httpx.codes.UNAUTHORIZED:
45
+ raise LassoAuthError(response.status_code, response.text)
46
+ raise LassoRequestError(response.status_code, response.text)
@@ -0,0 +1,13 @@
1
+ from pydantic import BaseModel, ConfigDict, Field
2
+
3
+ DEFAULT_BASE_URL = "https://server.lasso.security/gateway/v3"
4
+
5
+
6
+ class LassoSettings(BaseModel):
7
+ model_config = ConfigDict(extra="forbid", frozen=True)
8
+
9
+ base_url: str = DEFAULT_BASE_URL
10
+ api_key_env: str = "LASSO_API_KEY"
11
+ mask: bool = False
12
+ timeout_seconds: float = Field(default=5.0, gt=0)
13
+ source_type: str = "contextforge"
@@ -0,0 +1,177 @@
1
+ import logging
2
+ import os
3
+ from collections.abc import Callable, Mapping
4
+ from typing import Any
5
+
6
+ from cpex.framework import (
7
+ GlobalContext,
8
+ Plugin,
9
+ PluginConfig,
10
+ PluginContext,
11
+ PluginViolation,
12
+ PromptPosthookPayload,
13
+ PromptPosthookResult,
14
+ ResourcePostFetchPayload,
15
+ ResourcePostFetchResult,
16
+ ToolPostInvokePayload,
17
+ ToolPostInvokeResult,
18
+ ToolPreInvokePayload,
19
+ ToolPreInvokeResult,
20
+ )
21
+ from pydantic import BaseModel, ValidationError
22
+
23
+ from cpex_lasso.client import LassoAuthError, LassoClient, LassoRequestError
24
+ from cpex_lasso.config import LassoSettings
25
+ from cpex_lasso.translate import (
26
+ CallContext,
27
+ MaskingError,
28
+ masked_prompt_result,
29
+ masked_resource_content,
30
+ masked_tool_args,
31
+ masked_tool_result,
32
+ new_session_id,
33
+ prompt_parts,
34
+ prompt_request,
35
+ resource_text,
36
+ session_id_from_headers,
37
+ text_request,
38
+ tool_call_request,
39
+ tool_definition_from_metadata,
40
+ tool_result_parts,
41
+ tool_result_request,
42
+ user_id_of,
43
+ )
44
+ from cpex_lasso.verdict import Verdict, VerdictKind, block_details, decide
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ SESSION_STATE_KEY = "lasso_session_id"
49
+ BLOCK_CODE = "LASSO_BLOCK"
50
+ MASKING_FAILED_CODE = "LASSO_MASKING_FAILED"
51
+ AUTH_FAILED_CODE = "LASSO_AUTH_FAILED"
52
+ FORBIDDEN = 403
53
+ SERVICE_UNAVAILABLE = 503
54
+
55
+
56
+ def _as_mapping(value: Any) -> dict[str, Any]:
57
+ if isinstance(value, BaseModel):
58
+ return value.model_dump(by_alias=True)
59
+ return dict(value) if isinstance(value, Mapping) else {}
60
+
61
+
62
+ def _restore(original: Any, masked: dict[str, Any]) -> Any:
63
+ return type(original).model_validate(masked) if isinstance(original, BaseModel) else masked
64
+
65
+
66
+ def _headers(payload: ToolPreInvokePayload) -> Mapping[str, str] | None:
67
+ return payload.headers.root if payload.headers is not None else None
68
+
69
+
70
+ def _violation(code: str, description: str, details: dict[str, Any] | None = None, status: int = FORBIDDEN) -> PluginViolation:
71
+ return PluginViolation(
72
+ reason="Blocked by Lasso",
73
+ description=description,
74
+ code=code,
75
+ details=details or {},
76
+ http_status_code=status,
77
+ )
78
+
79
+
80
+ class LassoPlugin(Plugin):
81
+ def __init__(self, config: PluginConfig):
82
+ super().__init__(config)
83
+ self._settings = LassoSettings.model_validate(self._config.config or {})
84
+ api_key = os.environ.get(self._settings.api_key_env)
85
+ if not api_key:
86
+ raise ValueError(f"{self._settings.api_key_env} is not set; cpex-lasso cannot authenticate to Lasso")
87
+ self._client = LassoClient(self._settings.base_url, api_key, self._settings.timeout_seconds)
88
+
89
+ async def shutdown(self) -> None:
90
+ await self._client.aclose()
91
+
92
+ async def tool_pre_invoke(self, payload: ToolPreInvokePayload, context: PluginContext) -> ToolPreInvokeResult:
93
+ session_id = session_id_from_headers(_headers(payload)) or new_session_id()
94
+ context.state[SESSION_STATE_KEY] = session_id
95
+ call = self._call_context(context.global_context, session_id)
96
+ request = tool_call_request(payload.name, payload.args, call, self._settings.source_type)
97
+ outcome = await self._evaluate(request, lambda verdict: masked_tool_args(verdict.masked_messages))
98
+ if isinstance(outcome, PluginViolation):
99
+ return ToolPreInvokeResult(continue_processing=False, violation=outcome)
100
+ if outcome is None:
101
+ return ToolPreInvokeResult()
102
+ return ToolPreInvokeResult(modified_payload=payload.model_copy(update={"args": outcome}))
103
+
104
+ async def tool_post_invoke(self, payload: ToolPostInvokePayload, context: PluginContext) -> ToolPostInvokeResult:
105
+ result = _as_mapping(payload.result)
106
+ parts = tool_result_parts(result)
107
+ if parts.is_empty:
108
+ return ToolPostInvokeResult()
109
+ call = self._call_context(context.global_context, context.state.get(SESSION_STATE_KEY))
110
+ request = tool_result_request(parts, call, self._settings.source_type)
111
+ outcome = await self._evaluate(request, lambda verdict: _restore(payload.result, masked_tool_result(result, parts, verdict.masked_messages)))
112
+ if isinstance(outcome, PluginViolation):
113
+ return ToolPostInvokeResult(continue_processing=False, violation=outcome)
114
+ if outcome is None:
115
+ return ToolPostInvokeResult()
116
+ return ToolPostInvokeResult(modified_payload=payload.model_copy(update={"result": outcome}))
117
+
118
+ async def prompt_post_fetch(self, payload: PromptPosthookPayload, context: PluginContext) -> PromptPosthookResult:
119
+ result = _as_mapping(payload.result)
120
+ parts = prompt_parts(result)
121
+ if not parts.messages:
122
+ return PromptPosthookResult()
123
+ request = prompt_request(parts, self._call_context(context.global_context, None), self._settings.source_type)
124
+ outcome = await self._evaluate(
125
+ request, lambda verdict: _restore(payload.result, masked_prompt_result(result, parts, verdict.masked_messages))
126
+ )
127
+ if isinstance(outcome, PluginViolation):
128
+ return PromptPosthookResult(continue_processing=False, violation=outcome)
129
+ if outcome is None:
130
+ return PromptPosthookResult()
131
+ return PromptPosthookResult(modified_payload=payload.model_copy(update={"result": outcome}))
132
+
133
+ async def resource_post_fetch(self, payload: ResourcePostFetchPayload, context: PluginContext) -> ResourcePostFetchResult:
134
+ content = _as_mapping(payload.content)
135
+ text = resource_text(content)
136
+ if text is None:
137
+ return ResourcePostFetchResult()
138
+ request = text_request(text, self._call_context(context.global_context, None), self._settings.source_type)
139
+ outcome = await self._evaluate(request, lambda verdict: _restore(payload.content, masked_resource_content(content, verdict.masked_messages)))
140
+ if isinstance(outcome, PluginViolation):
141
+ return ResourcePostFetchResult(continue_processing=False, violation=outcome)
142
+ if outcome is None:
143
+ return ResourcePostFetchResult()
144
+ return ResourcePostFetchResult(modified_payload=payload.model_copy(update={"content": outcome}))
145
+
146
+ def _call_context(self, global_context: GlobalContext, session_id: str | None) -> CallContext:
147
+ return CallContext(
148
+ call_id=global_context.request_id,
149
+ user_id=user_id_of(global_context.user, global_context.user_context),
150
+ session_id=session_id,
151
+ team_id=global_context.tenant_id,
152
+ tool=tool_definition_from_metadata(global_context.metadata),
153
+ )
154
+
155
+ async def _evaluate(self, request: dict[str, Any], apply_mask: Callable[[Verdict], Any]) -> PluginViolation | Any | None:
156
+ """Allow is None, block is a PluginViolation, mask is the rewritten value. Lasso errors propagate to ContextForge's on_error."""
157
+ try:
158
+ response = await self._client.classify(request, mask=self._settings.mask)
159
+ except LassoAuthError:
160
+ # Not raised: under on_error ignore a rejected key would otherwise disable scanning silently and forever.
161
+ logger.error("Lasso rejected the API key in %s; refusing traffic until it is fixed", self._settings.api_key_env)
162
+ return _violation(AUTH_FAILED_CODE, "The Lasso guardrail is misconfigured: its API key was rejected", status=SERVICE_UNAVAILABLE)
163
+ except LassoRequestError as error:
164
+ logger.error("Lasso returned HTTP %s: %s", error.status_code, error.body)
165
+ raise
166
+ try:
167
+ verdict = decide(response, self._settings.mask)
168
+ if verdict.kind is VerdictKind.BLOCK:
169
+ return _violation(BLOCK_CODE, "Lasso policy blocked this content", block_details(verdict))
170
+ if verdict.has_findings:
171
+ logger.info("Lasso findings without a block", extra={"lasso_findings": block_details(verdict)})
172
+ return apply_mask(verdict) if verdict.kind is VerdictKind.MASK else None
173
+ except (MaskingError, ValidationError) as error:
174
+ # A ValidationError's text quotes the content it rejected, which may still hold the data Lasso asked to mask.
175
+ detail = str(error) if isinstance(error, MaskingError) else "the masked content does not fit the result model"
176
+ logger.error("Lasso masking could not be applied, blocking instead: %s", detail)
177
+ return _violation(MASKING_FAILED_CODE, "Lasso asked to mask content that could not be rewritten safely")
@@ -0,0 +1,302 @@
1
+ """ContextForge hook data to Lasso classify requests, and masked Lasso messages back to hook data."""
2
+
3
+ import json
4
+ import os
5
+ import time
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+
10
+ TOOL_USE_ROLE = "model"
11
+ # Indirect prompt injection arrives as developer content. Lasso's rules engine scans it; the legacy
12
+ # policies plane skips developer request messages, and the plugin does not target that plane.
13
+ TOOL_RESULT_ROLE = "developer"
14
+ TEXT_ROLE = "user"
15
+ PROMPT_ROLES = frozenset({"user", "assistant"})
16
+ SESSION_HEADERS = ("x-mcp-session-id", "mcp-session-id")
17
+ ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
18
+ USER_ID_MAX_LENGTH = 128
19
+ SOURCE_MAX_BYTES = 1024
20
+
21
+
22
+ class MaskingError(ValueError):
23
+ pass
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ToolDefinition:
28
+ name: str
29
+ description: str | None = None
30
+ input_schema: Mapping[str, Any] | None = None
31
+ gateway_id: str | None = None
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class CallContext:
36
+ call_id: str
37
+ user_id: str | None = None
38
+ session_id: str | None = None
39
+ team_id: str | None = None
40
+ tool: ToolDefinition | None = None
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class ToolResultParts:
45
+ text_indices: tuple[int, ...] = ()
46
+ texts: tuple[str, ...] = ()
47
+ structured: Any = None
48
+
49
+ @property
50
+ def is_empty(self) -> bool:
51
+ return not self.texts and self.structured is None
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class PromptParts:
56
+ message_indices: tuple[int, ...] = ()
57
+ messages: tuple[dict[str, str], ...] = field(default_factory=tuple)
58
+
59
+
60
+ def _field(source: Any, name: str) -> Any:
61
+ if isinstance(source, Mapping):
62
+ return source.get(name)
63
+ return getattr(source, name, None)
64
+
65
+
66
+ def new_session_id() -> str:
67
+ """A ULID, for a call that arrives with no MCP session header, so its pre and post checks still share a session."""
68
+ value = (int(time.time() * 1000) << 80) | int.from_bytes(os.urandom(10), "big")
69
+ return "".join(ULID_ALPHABET[(value >> shift) & 0x1F] for shift in range(125, -1, -5))
70
+
71
+
72
+ def session_id_from_headers(headers: Mapping[str, str] | None) -> str | None:
73
+ if not headers:
74
+ return None
75
+ lowered = {key.lower(): value for key, value in headers.items()}
76
+ return next((lowered[name] for name in SESSION_HEADERS if lowered.get(name)), None)
77
+
78
+
79
+ def user_id_of(user: Any, user_context: Any = None) -> str | None:
80
+ email = _field(user_context, "email") or (user if isinstance(user, str) else _field(user, "email"))
81
+ if not email or len(email) > USER_ID_MAX_LENGTH:
82
+ return None
83
+ return email
84
+
85
+
86
+ def tool_definition_from_metadata(metadata: Mapping[str, Any] | None) -> ToolDefinition | None:
87
+ tool = (metadata or {}).get("tool")
88
+ name = _field(tool, "original_name") or _field(tool, "name")
89
+ if not name:
90
+ return None
91
+ return ToolDefinition(
92
+ name=name,
93
+ description=_field(tool, "description"),
94
+ input_schema=_field(tool, "input_schema"),
95
+ gateway_id=_field(tool, "gateway_id"),
96
+ )
97
+
98
+
99
+ def _source(context: CallContext, source_type: str) -> dict[str, Any]:
100
+ attributes = {
101
+ "teamId": context.team_id,
102
+ "gatewayId": context.tool.gateway_id if context.tool else None,
103
+ "tool": context.tool.name if context.tool else None,
104
+ }
105
+ source = {"type": source_type, **{key: value for key, value in attributes.items() if value}}
106
+ if len(json.dumps(source).encode()) > SOURCE_MAX_BYTES:
107
+ return {"type": source_type}
108
+ return source
109
+
110
+
111
+ def _tools(tool: ToolDefinition | None) -> list[dict[str, Any]] | None:
112
+ if tool is None:
113
+ return None
114
+ definition: dict[str, Any] = {"name": tool.name}
115
+ if tool.description:
116
+ definition["description"] = tool.description
117
+ if tool.input_schema:
118
+ definition["parameters"] = dict(tool.input_schema)
119
+ return [definition]
120
+
121
+
122
+ def _request(messages: list[dict[str, Any]], context: CallContext, source_type: str) -> dict[str, Any]:
123
+ request: dict[str, Any] = {"messages": messages, "source": _source(context, source_type)}
124
+ optional = {"sessionId": context.session_id, "userId": context.user_id, "tools": _tools(context.tool)}
125
+ request.update({key: value for key, value in optional.items() if value})
126
+ return request
127
+
128
+
129
+ def tool_call_request(tool_name: str, args: Mapping[str, Any] | None, context: CallContext, source_type: str) -> dict[str, Any]:
130
+ name = context.tool.name if context.tool else tool_name
131
+ block = {"type": "tool_use", "id": context.call_id, "name": name, "input": dict(args or {})}
132
+ return _request([{"role": TOOL_USE_ROLE, "content": block}], context, source_type)
133
+
134
+
135
+ def _block_text(part: Any) -> str | None:
136
+ if not isinstance(part, Mapping):
137
+ return None
138
+ if part.get("type") == "text":
139
+ text = part.get("text")
140
+ elif part.get("type") == "resource" and isinstance(part.get("resource"), Mapping):
141
+ text = part["resource"].get("text")
142
+ else:
143
+ return None
144
+ return text if isinstance(text, str) and text else None
145
+
146
+
147
+ def _with_block_text(part: Mapping[str, Any], text: str) -> dict[str, Any]:
148
+ if part.get("type") == "resource":
149
+ return {**part, "resource": {**part["resource"], "text": text}}
150
+ return {**part, "text": text}
151
+
152
+
153
+ def _is_empty_json(value: Any) -> bool:
154
+ return value is None or (isinstance(value, (str, list, dict)) and not value)
155
+
156
+
157
+ def _structured_as_content(structured: Any) -> Any:
158
+ """Objects go to Lasso as they are. Any other JSON value, which the MCP 2026 wire allows, goes as text."""
159
+ if isinstance(structured, Mapping):
160
+ return dict(structured)
161
+ return structured if isinstance(structured, str) else json.dumps(structured)
162
+
163
+
164
+ def _require_finite_numbers(value: Any) -> Any:
165
+ """Python reads NaN, Infinity and overflowing numbers such as 1e400 as floats that are not JSON values."""
166
+ json.dumps(value, allow_nan=False)
167
+ return value
168
+
169
+
170
+ def _json_type(value: Any) -> type:
171
+ if isinstance(value, bool):
172
+ return bool
173
+ if isinstance(value, int | float):
174
+ return float
175
+ return type(value)
176
+
177
+
178
+ def _restore_structured(original: Any, masked: Any) -> Any:
179
+ if isinstance(original, Mapping):
180
+ return _parse_object(masked, "structured tool result")
181
+ if isinstance(original, str):
182
+ if not isinstance(masked, str):
183
+ raise MaskingError("Masked structured tool result is not a string")
184
+ return masked
185
+ try:
186
+ restored = _require_finite_numbers(json.loads(masked))
187
+ except (TypeError, ValueError) as error:
188
+ raise MaskingError("Masked structured tool result is not valid JSON") from error
189
+ if _json_type(restored) is not _json_type(original):
190
+ raise MaskingError("Masked structured tool result changed its JSON type")
191
+ return restored
192
+
193
+
194
+ def tool_result_parts(result: Mapping[str, Any]) -> ToolResultParts:
195
+ content = result.get("content") or []
196
+ text_parts = [(index, text) for index, part in enumerate(content) if (text := _block_text(part)) is not None]
197
+ structured = result.get("structuredContent")
198
+ return ToolResultParts(
199
+ text_indices=tuple(index for index, _ in text_parts),
200
+ texts=tuple(text for _, text in text_parts),
201
+ structured=None if _is_empty_json(structured) else structured,
202
+ )
203
+
204
+
205
+ def tool_result_request(parts: ToolResultParts, context: CallContext, source_type: str) -> dict[str, Any]:
206
+ contents: list[Any] = [*parts.texts]
207
+ if parts.structured is not None:
208
+ contents.append(_structured_as_content(parts.structured))
209
+ messages = [
210
+ {"role": TOOL_RESULT_ROLE, "content": {"type": "tool_result", "tool_use_id": context.call_id, "content": content}} for content in contents
211
+ ]
212
+ return _request(messages, context, source_type)
213
+
214
+
215
+ def _prompt_text(message: Mapping[str, Any]) -> str | None:
216
+ content = message.get("content")
217
+ if isinstance(content, str):
218
+ return content or None
219
+ if isinstance(content, Mapping) and content.get("type") in ("text", "resource"):
220
+ return content.get("text") or None
221
+ return None
222
+
223
+
224
+ def prompt_parts(result: Mapping[str, Any]) -> PromptParts:
225
+ indices: list[int] = []
226
+ messages: list[dict[str, str]] = []
227
+ for index, message in enumerate(result.get("messages") or []):
228
+ text = _prompt_text(message)
229
+ if text is None:
230
+ continue
231
+ role = message.get("role")
232
+ indices.append(index)
233
+ messages.append({"role": role if role in PROMPT_ROLES else TEXT_ROLE, "content": text})
234
+ return PromptParts(message_indices=tuple(indices), messages=tuple(messages))
235
+
236
+
237
+ def prompt_request(parts: PromptParts, context: CallContext, source_type: str) -> dict[str, Any]:
238
+ return _request([dict(message) for message in parts.messages], context, source_type)
239
+
240
+
241
+ def resource_text(content: Mapping[str, Any]) -> str | None:
242
+ text = content.get("text")
243
+ return text if isinstance(text, str) and text else None
244
+
245
+
246
+ def text_request(text: str, context: CallContext, source_type: str) -> dict[str, Any]:
247
+ return _request([{"role": TEXT_ROLE, "content": text}], context, source_type)
248
+
249
+
250
+ def _masked_content(masked_messages: list[Mapping[str, Any]], index: int) -> Any:
251
+ try:
252
+ return masked_messages[index]["content"]
253
+ except (IndexError, KeyError, TypeError) as error:
254
+ raise MaskingError(f"Lasso returned no masked message at index {index}") from error
255
+
256
+
257
+ def _parse_object(value: Any, what: str) -> dict[str, Any]:
258
+ try:
259
+ parsed = _require_finite_numbers(dict(value) if isinstance(value, Mapping) else json.loads(value))
260
+ except (TypeError, ValueError) as error:
261
+ raise MaskingError(f"Masked {what} is not valid JSON") from error
262
+ if not isinstance(parsed, dict):
263
+ raise MaskingError(f"Masked {what} is not a JSON object")
264
+ return parsed
265
+
266
+
267
+ def masked_tool_args(masked_messages: list[Mapping[str, Any]]) -> dict[str, Any]:
268
+ block = _masked_content(masked_messages, 0)
269
+ return _parse_object(_field(block, "input"), "tool arguments")
270
+
271
+
272
+ def masked_tool_result(result: Mapping[str, Any], parts: ToolResultParts, masked_messages: list[Mapping[str, Any]]) -> dict[str, Any]:
273
+ masked = dict(result)
274
+ content = [dict(part) if isinstance(part, Mapping) else part for part in result.get("content") or []]
275
+ for position, content_index in enumerate(parts.text_indices):
276
+ text = _field(_masked_content(masked_messages, position), "content")
277
+ if not isinstance(text, str):
278
+ raise MaskingError("Masked tool result text is not a string")
279
+ content[content_index] = _with_block_text(content[content_index], text)
280
+ masked["content"] = content
281
+ if parts.structured is not None:
282
+ structured = _field(_masked_content(masked_messages, len(parts.texts)), "content")
283
+ masked["structuredContent"] = _restore_structured(parts.structured, structured)
284
+ return masked
285
+
286
+
287
+ def masked_prompt_result(result: Mapping[str, Any], parts: PromptParts, masked_messages: list[Mapping[str, Any]]) -> dict[str, Any]:
288
+ messages = [dict(message) for message in result.get("messages") or []]
289
+ for position, message_index in enumerate(parts.message_indices):
290
+ text = _masked_content(masked_messages, position)
291
+ if not isinstance(text, str):
292
+ raise MaskingError("Masked prompt text is not a string")
293
+ original = messages[message_index].get("content")
294
+ messages[message_index]["content"] = {**original, "text": text} if isinstance(original, Mapping) else text
295
+ return {**result, "messages": messages}
296
+
297
+
298
+ def masked_resource_content(content: Mapping[str, Any], masked_messages: list[Mapping[str, Any]]) -> dict[str, Any]:
299
+ text = _masked_content(masked_messages, 0)
300
+ if not isinstance(text, str):
301
+ raise MaskingError("Masked resource text is not a string")
302
+ return {**content, "text": text}
@@ -0,0 +1,127 @@
1
+ from collections.abc import Mapping
2
+ from dataclasses import dataclass, field
3
+ from enum import Enum
4
+ from typing import Any
5
+
6
+ from cpex_lasso.translate import MaskingError
7
+
8
+ AUTO_MASKING = "AUTO_MASKING"
9
+
10
+
11
+ class LassoResponseError(RuntimeError):
12
+ pass
13
+
14
+
15
+ class VerdictKind(Enum):
16
+ ALLOW = "allow"
17
+ BLOCK = "block"
18
+ MASK = "mask"
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Finding:
23
+ name: str | None
24
+ category: str | None
25
+ action: str | None
26
+ severity: str | None
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class IntentFinding:
31
+ violations: tuple[str, ...]
32
+ action: str | None
33
+ monitor_only: bool
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Verdict:
38
+ kind: VerdictKind
39
+ findings: tuple[Finding, ...] = ()
40
+ intent_findings: tuple[IntentFinding, ...] = ()
41
+ masked_messages: list[Mapping[str, Any]] = field(default_factory=list)
42
+
43
+ @property
44
+ def has_findings(self) -> bool:
45
+ return bool(self.findings or self.intent_findings)
46
+
47
+
48
+ def _text(value: Any) -> str | None:
49
+ """A display field, or None when Lasso sends something other than a string. Never raises, so a block still applies."""
50
+ return value if isinstance(value, str) else None
51
+
52
+
53
+ def _mapping(value: Any) -> Mapping[str, Any]:
54
+ return value if isinstance(value, Mapping) else {}
55
+
56
+
57
+ def _findings(response: Mapping[str, Any]) -> tuple[Finding, ...]:
58
+ # Lasso reports one finding per scanned message, so the same detection repeats when a tool
59
+ # result is sent both as text and as structured content.
60
+ findings = (
61
+ Finding(
62
+ name=_text(item.get("name")),
63
+ category=_text(item.get("category")),
64
+ action=_text(item.get("action")),
65
+ severity=_text(item.get("severity")),
66
+ )
67
+ for items in _mapping(response.get("findings")).values()
68
+ if isinstance(items, list)
69
+ for item in items
70
+ if isinstance(item, Mapping)
71
+ )
72
+ return tuple(dict.fromkeys(findings))
73
+
74
+
75
+ def _findings_are_readable(value: Any) -> bool:
76
+ if value is None:
77
+ return True
78
+ return isinstance(value, Mapping) and all(
79
+ isinstance(items, list) and all(isinstance(item, Mapping) for item in items) for items in value.values()
80
+ )
81
+
82
+
83
+ def _violations(value: Any) -> tuple[str, ...]:
84
+ if not isinstance(value, list) or not all(isinstance(violation, str) for violation in value):
85
+ return ()
86
+ return tuple(value)
87
+
88
+
89
+ def _intent_findings(response: Mapping[str, Any]) -> tuple[IntentFinding, ...]:
90
+ """Best effort: intent findings are only reported, the block itself comes from is_block, so malformed ones are dropped."""
91
+ items = response.get("intent_findings")
92
+ findings = (
93
+ IntentFinding(violations=_violations(item.get("violations")), action=_text(item.get("action")), monitor_only=item.get("monitorOnly") is True)
94
+ for item in (items if isinstance(items, list) else [])
95
+ if isinstance(item, Mapping)
96
+ )
97
+ return tuple(dict.fromkeys(findings))
98
+
99
+
100
+ def decide(response: Mapping[str, Any], masking_enabled: bool) -> Verdict:
101
+ findings = _findings(response)
102
+ intent_findings = _intent_findings(response)
103
+ if response.get("is_block") is True:
104
+ return Verdict(VerdictKind.BLOCK, findings, intent_findings)
105
+ # An unreadable group could hide an AUTO_MASKING finding, so it goes to on_error instead of allowing.
106
+ if not _findings_are_readable(response.get("findings")):
107
+ raise LassoResponseError("Lasso returned findings in an unexpected shape")
108
+ wants_mask = masking_enabled and any(finding.action == AUTO_MASKING for finding in findings)
109
+ if not wants_mask:
110
+ return Verdict(VerdictKind.ALLOW, findings, intent_findings)
111
+ masked_messages = response.get("messages")
112
+ if not isinstance(masked_messages, list) or not masked_messages:
113
+ raise MaskingError("Lasso asked to mask but returned no masked messages")
114
+ return Verdict(VerdictKind.MASK, findings, intent_findings, masked_messages)
115
+
116
+
117
+ def block_details(verdict: Verdict) -> dict[str, Any]:
118
+ return {
119
+ "findings": [
120
+ {"name": finding.name, "category": finding.category, "action": finding.action, "severity": finding.severity}
121
+ for finding in verdict.findings
122
+ ],
123
+ "intent_findings": [
124
+ {"violations": list(finding.violations), "action": finding.action, "monitor_only": finding.monitor_only}
125
+ for finding in verdict.intent_findings
126
+ ],
127
+ }