stranger-test 0.0.1__py3-none-any.whl

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,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: stranger-test
3
+ Version: 0.0.1
4
+ Summary: Tests MCP servers for cross-identity and delegated-authority (RFC 8693) authorization leaks.
5
+ Author: Vedant Agarwal
6
+ License-Expression: Apache-2.0
7
+ Keywords: mcp,model-context-protocol,security,authorization,confused-deputy
8
+ Classifier: Development Status :: 2 - Pre-Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Topic :: Security
14
+ Classifier: Topic :: Software Development :: Testing
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # Stranger Test
21
+
22
+ Stranger Test is a free, standard-library-only Python tool and library for
23
+ testing **MCP (Model Context Protocol) servers** for cross-identity and
24
+ delegated-authority authorization leaks.
25
+
26
+ An MCP server is a trusted middleman that usually holds many users' credentials
27
+ and data. The question Stranger Test asks is simple: can one identity's data,
28
+ events, or authority reach another identity through the server? We organise
29
+ these failures into a taxonomy of 14 **XID** leak classes, and build detection
30
+ ahead of a class becoming common rather than after. Two of the earliest-built
31
+ detectors are:
32
+
33
+ - **XID-13** — cross-identity subscription/notification leak.
34
+ - **XID-10** — delegation dropped or forged: the on-behalf-of / token-exchange
35
+ confused-deputy problem.
36
+
37
+ ## Try it
38
+
39
+ See a leak caught in under a minute, with no third-party dependencies. This
40
+ starts the bundled practice MCP subscription server on a loopback port and runs
41
+ the XID-13 subscription probe against it — first in `leaky` mode, then in `safe`
42
+ mode. From the repository root, with plain system Python:
43
+
44
+ ```
45
+ python3 -m strangertest.demo
46
+ ```
47
+
48
+ In `leaky` mode, identity B hears identity A's resource update — a leak:
49
+
50
+ ```
51
+ Subscription-leak probe (XID-13) against the bundled practice server.
52
+ B subscribes to A's resource; A changes it; did B hear about it?
53
+
54
+ [leaky] LEAK: identity 'B' received update notifications for 'note://alice/secret', a resource owned by identity 'A' — cross-identity subscription/notification leak.
55
+ [safe] OK: identity 'B' received no notifications for 'A''s resource 'note://alice/secret'.
56
+ ```
57
+
58
+ The `leaky` line is the detection; the `safe` line is the same probe reporting a
59
+ correctly-scoped server clean.
60
+
61
+ ## How it works
62
+
63
+ Every probe is an **A/B probe**: act as identity **A**, observe as identity
64
+ **B**, and check whether the line between them held.
65
+
66
+ - **Positive controls.** A probe first proves its observer actually works, so
67
+ that "no leak" cannot be a false negative caused by a broken observer.
68
+ - **An explicit `inconclusive` grade.** When the probe cannot observe what it
69
+ needs — an undecodable delegated token, a stream that will not open, a server
70
+ too old to carry the channel — it reports *inconclusive*, which is distinct
71
+ from *no leak*. It never reports a leak it could not actually see, and never
72
+ calls an unobservable server clean.
73
+ - **Authorized-first.** Every probe passes the target through an authorization
74
+ guard before any connection is made (see *Scope and safety* below).
75
+
76
+ The three probes:
77
+
78
+ 1. **Read probe** (`strangertest.probe`) — A plants a uniquely-marked record;
79
+ B tries to read it back. If B sees A's marker, authority crossed identities.
80
+ 2. **Subscription probe / XID-13** (`strangertest.subscribe`) — B opens a
81
+ subscription stream on a resource owned by A; A then changes it. If B
82
+ receives an update notification for A's resource, one identity's events
83
+ reached another. Detection is exact-URI, exact-method — not a substring
84
+ search — and the stream is opened and acknowledged *before* A acts, because
85
+ the channel does not replay.
86
+ 3. **Delegation probe / XID-10** (`strangertest.delegate`) — the server acts
87
+ on behalf of a user against an upstream you control. The probe drives it as
88
+ A, then B, then A again (the second A call catches a deputy that cached or
89
+ bled B's token into A's request) and inspects what reached the upstream:
90
+ subject preserved, acting agent present, audience correct, scope narrowed,
91
+ a distinct token per principal, and no cross-identity bleed. Identity is
92
+ `(issuer, subject)`, so two users named the same from different providers
93
+ are not conflated.
94
+
95
+ **Transports** (`strangertest.transports`), standard library only: **stdio**
96
+ (subprocess, newline-delimited JSON-RPC) and **Streamable HTTP** (JSON or SSE),
97
+ including the 2026-07-28 "modern" per-request envelope.
98
+
99
+ ## Install and run
100
+
101
+ Requires Python 3.9+. The core library and unit tests use the standard library
102
+ only — no third-party dependencies.
103
+
104
+ Unit tests, from the repository root:
105
+
106
+ ```
107
+ python3 -m unittest discover
108
+ ```
109
+
110
+ (106 tests.)
111
+
112
+ ## Integration gates
113
+
114
+ The integration "gates" in `integration/` exercise the probes end-to-end
115
+ against real servers. They need extra dependencies (`pyjwt[crypto]`, plus the
116
+ target server itself), are **not** run by `python3 -m unittest discover`, and
117
+ skip cleanly when their dependencies are absent.
118
+
119
+ - **XID-13 subscription gate** — drives the subscription probe against the
120
+ official MCP SDK subscriptions example server.
121
+ - **XID-10 thin-deputy gate** (`integration/xid10_thin_deputy_gate.py`) — runs
122
+ the delegation probe over a real RFC 8693 token exchange against a set of
123
+ deliberately-broken deputy fixtures: `static_credential`, `token_passthrough`,
124
+ `cached_token_reuse`, and a conflated-issuer case. Each is a known leak the
125
+ probe must flag, for the right reason.
126
+ - **XID-10 ContextForge gate** (`integration/xid10_contextforge_gate.py`) —
127
+ drives the delegation probe through a real IBM ContextForge gateway doing
128
+ RFC 8693 token exchange. Configured by `XID10_MODE`
129
+ (`delegation` | `impersonation` | `two_issuers`) and `XID10_TRIGGER`
130
+ (`tool` | `resource`).
131
+ - **XID-10 agentgateway gate** (`integration/xid10_agentgateway_gate.py`) —
132
+ drives the same delegation probe, same six checks and scenarios, through a
133
+ second, unrelated third-party gateway: **agentgateway v1.7.0** (the official
134
+ release binary, configured by its config file only). A second gateway so the
135
+ probe's behaviour is not tied to any one implementation.
136
+
137
+ The setup recipes are in
138
+ [`integration/CONTEXTFORGE_GATE.md`](integration/CONTEXTFORGE_GATE.md) and
139
+ [`integration/AGENTGATEWAY_GATE.md`](integration/AGENTGATEWAY_GATE.md).
140
+ Everything in the gates runs on localhost only.
141
+
142
+ ## A sample result
143
+
144
+ Run against a real **IBM ContextForge 1.1.1** gateway (macOS, Python 3.13); the
145
+ same scenarios run against **agentgateway v1.7.0** with the same results:
146
+
147
+ - **Faithful delegation** grades clean — all checks pass.
148
+ - **Impersonation** (no actor token) is flagged, because the exchanged token
149
+ carries no acting-agent `act` claim, so the agent acting for the user is
150
+ invisible.
151
+ - **Two issuers** — two users both named `alice` from different providers are
152
+ kept distinct through the exchange (distinct tokens, no cross-identity reuse);
153
+ no conflation.
154
+
155
+ To be clear about what this does and does not show: **no vulnerability was found
156
+ in either gateway.** The probe's ability to *detect* leaks is demonstrated by the
157
+ deliberately-broken thin-deputy fixtures above, each of which the probe flags.
158
+ A comparison against the older **1.0.6** release (to check a since-fixed
159
+ historical behaviour) is noted as **future work** and has not yet been run.
160
+
161
+ ## Scope and safety
162
+
163
+ Point Stranger Test only at **localhost, servers you run, or targets you are
164
+ explicitly authorized to test.** The authorization guard allows local
165
+ development hosts (loopback, `.localhost`, `.test`) automatically and refuses
166
+ every other target unless you pass explicit authorization recording who
167
+ permitted the test. There is deliberately no "scan everything" mode: one target,
168
+ one authorization.
169
+
170
+ Any real finding is for **private, responsible disclosure** to the server's
171
+ owner. Do not name-and-shame.
172
+
173
+ ## License
174
+
175
+ Apache-2.0 (see `LICENSE`).
@@ -0,0 +1,20 @@
1
+ stranger_test-0.0.1.dist-info/licenses/LICENSE,sha256=MoUlvyTgr0MePbNMsmSKMTMf-1eLncnnFGHi-jpRqys,11345
2
+ strangertest/__init__.py,sha256=m3VR3N-Oh5SN7A_ODUz_zykPr3dMZYU9ArfTOGlFRf8,645
3
+ strangertest/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
4
+ strangertest/cli.py,sha256=H8DraoLyrkoG0F_N3yFDBjoUNP85cZGH0k7juSADAMA,7457
5
+ strangertest/delegate.py,sha256=YwgGZsRphnJEd0aqK_w-j-ByF5YlhZ7b7Ch3_zOqPbA,13203
6
+ strangertest/demo.py,sha256=I6mcEU5Cxt4Eme_e9-8yzVLMSCrK2mUL-78fGOg2uTk,2170
7
+ strangertest/guard.py,sha256=g09R-uFyk4VhH46n19h1RgmgmTlX9tMsgh41CCVdl3E,4130
8
+ strangertest/mcp_client.py,sha256=Pub_TgEZJs6WB4JjhFbIjKAxgyM-glRk55HpGlyIgJM,11564
9
+ strangertest/practice_delegation_http.py,sha256=DfR0TazZw4JpebBqW273o12IlVNaJZlx1Lwhag2eK7E,10252
10
+ strangertest/practice_http.py,sha256=kVG1Oair2FC4uMXPXRRw4xdyqlCrKJ5b9y5ROpnwm_0,10594
11
+ strangertest/practice_server.py,sha256=4dqB9Z5shEhy55LTMgY0u4TczRAwS30mIs_H6SxUYao,3669
12
+ strangertest/probe.py,sha256=4TQFWSz04JUI1n_a45Y-PIvDUQue32Xu60z5fn85rks,6780
13
+ strangertest/source_audit.py,sha256=Lsk-damQBF9y_ApMfpoGsjhMk1WP8Xrkw2qfsj6KorM,27736
14
+ strangertest/subscribe.py,sha256=SQ9rSyKZXh3lqm9FNJOOFOY0du0kmq7eMTj2maz-9oc,6172
15
+ strangertest/transports.py,sha256=u4s8GhCs64CG5RP3QjTCIDOFrJMKGKVJKHk-yyy91xc,19927
16
+ stranger_test-0.0.1.dist-info/METADATA,sha256=DD5-CDI9sp1hfvegQ8aOLwlfJIZvffCTRRLbssEgxYg,8058
17
+ stranger_test-0.0.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
18
+ stranger_test-0.0.1.dist-info/entry_points.txt,sha256=rw0SZnHsynNiIzAQjBDmAl83fZMKfBh5iacamQZ-k7o,55
19
+ stranger_test-0.0.1.dist-info/top_level.txt,sha256=IbFfa1eSSL7S_W-mS6Zp1PmUxy7RY939UvgdiyvTxpo,13
20
+ stranger_test-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ strangertest = strangertest.cli:main
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Vedant Agarwal
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1 @@
1
+ strangertest
@@ -0,0 +1,16 @@
1
+ """Stranger Test — an authorized-only MCP confused-deputy leak tester."""
2
+
3
+ from .guard import ( # noqa: F401
4
+ Authorization,
5
+ AuthorizationError,
6
+ authorize,
7
+ extract_host,
8
+ is_local_target,
9
+ )
10
+ from .mcp_client import JSONRPCError, MCPClient, Transport # noqa: F401
11
+ from .delegate import DelegationReport, MockUpstream, run_delegation_probe # noqa: F401
12
+ from .probe import Identity, ProbeError, ProbePlan, ProbeReport, new_marker, run_probe # noqa: F401
13
+ from .subscribe import SubscriptionReport, run_subscription_probe # noqa: F401
14
+ from .transports import HTTPTransport, StdioTransport # noqa: F401
15
+
16
+ __version__ = "0.0.1"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
strangertest/cli.py ADDED
@@ -0,0 +1,184 @@
1
+ """Command-line interface for Stranger Test.
2
+
3
+ For now the CLI runs the bundled local practice server end-to-end:
4
+
5
+ python3 -m strangertest practice # the leaky server: should find a leak
6
+ python3 -m strangertest practice --safe # the isolated server: should be clean
7
+ python3 -m strangertest practice --json # full JSON report
8
+
9
+ ``scan`` runs the same probe against an authorized HTTP server. For both, exit
10
+ code is 1 when a leak is found and 0 when none is, so the same command works as
11
+ a CI check.
12
+
13
+ ``survey <path>`` is the static side: it reads MCP server source code and lists
14
+ low-confidence candidates. It always exits 0 unless the path is missing.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import os
22
+ import sys
23
+ import tempfile
24
+ from typing import List, Optional
25
+
26
+ from . import __version__
27
+ from .guard import AuthorizationError
28
+ from .mcp_client import MCPClient
29
+ from .probe import Identity, ProbeError, ProbePlan, run_probe
30
+ from .source_audit import survey
31
+ from .transports import HTTPTransport, HTTPTransportError, StdioTransport
32
+
33
+
34
+ def _practice_identity(label: str, identity_id: str, mode: str, store_path: str) -> Identity:
35
+ command = [sys.executable, "-m", "strangertest.practice_server"]
36
+ env = {
37
+ "STRANGERTEST_MODE": mode,
38
+ "STRANGERTEST_IDENTITY": identity_id,
39
+ "STRANGERTEST_STORE": store_path,
40
+ }
41
+ return Identity(label=label, connect=lambda: MCPClient(StdioTransport(command, env=env)))
42
+
43
+
44
+ def cmd_practice(args: argparse.Namespace) -> int:
45
+ mode = "safe" if args.safe else "leaky"
46
+ plan = ProbePlan.key_value("kv_set", "kv_get", "secret")
47
+ with tempfile.TemporaryDirectory() as tmp:
48
+ store = os.path.join(tmp, "store.json")
49
+ report = run_probe(
50
+ "http://localhost/practice",
51
+ _practice_identity("A", "alice", mode, store),
52
+ _practice_identity("B", "bob", mode, store),
53
+ plan,
54
+ )
55
+ if args.json:
56
+ print(json.dumps(report.to_dict(), indent=2))
57
+ else:
58
+ print(report.summary())
59
+ return 1 if report.leaked else 0
60
+
61
+
62
+ def cmd_scan(args: argparse.Namespace) -> int:
63
+ def http_identity(label: str, token) -> Identity:
64
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
65
+ return Identity(
66
+ label=label,
67
+ connect=lambda: MCPClient(HTTPTransport(args.url, headers=headers)),
68
+ )
69
+
70
+ plan = ProbePlan.key_value(args.plant_tool, args.read_tool, args.key)
71
+ try:
72
+ report = run_probe(
73
+ args.url,
74
+ http_identity("A", args.token_a),
75
+ http_identity("B", args.token_b),
76
+ plan,
77
+ authorized=args.authorized,
78
+ authorization_note=args.authorization_note,
79
+ )
80
+ except AuthorizationError as exc:
81
+ print(f"refused: {exc}", file=sys.stderr)
82
+ return 2
83
+ except ProbeError as exc:
84
+ print(f"inconclusive: {exc}", file=sys.stderr)
85
+ return 2
86
+ except HTTPTransportError as exc:
87
+ print(f"error: {exc}", file=sys.stderr)
88
+ return 2
89
+
90
+ if args.json:
91
+ print(json.dumps(report.to_dict(), indent=2))
92
+ else:
93
+ print(report.summary())
94
+ return 1 if report.leaked else 0
95
+
96
+
97
+ def cmd_survey(args: argparse.Namespace) -> int:
98
+ # Static only: reads source files, never connects to anything, so there is
99
+ # no target to authorize. Exit code is 0 even with candidates, because a
100
+ # candidate is a low-confidence hit to read by hand, not a confirmed leak.
101
+ try:
102
+ report = survey(args.path, include_tests=args.include_tests)
103
+ except FileNotFoundError:
104
+ print(f"error: no such path: {args.path}", file=sys.stderr)
105
+ return 2
106
+ if args.json:
107
+ print(json.dumps(report.to_dict(include_all=args.all), indent=2))
108
+ else:
109
+ print(report.summary())
110
+ return 0
111
+
112
+
113
+ def build_parser() -> argparse.ArgumentParser:
114
+ parser = argparse.ArgumentParser(
115
+ prog="strangertest",
116
+ description="Authorized tester for cross-identity confused-deputy leaks in MCP servers.",
117
+ )
118
+ parser.add_argument("--version", action="version", version=f"stranger-test {__version__}")
119
+ sub = parser.add_subparsers(dest="command")
120
+
121
+ practice = sub.add_parser(
122
+ "practice", help="Run the probe against the bundled local practice server."
123
+ )
124
+ practice.add_argument(
125
+ "--safe",
126
+ action="store_true",
127
+ help="Use the correctly-isolated server instead of the leaky one.",
128
+ )
129
+ practice.add_argument(
130
+ "--json", action="store_true", help="Print the full JSON report."
131
+ )
132
+ practice.set_defaults(func=cmd_practice)
133
+
134
+ scan = sub.add_parser(
135
+ "scan",
136
+ help="Probe an authorized MCP server over HTTP as two identities.",
137
+ description=(
138
+ "Plants a marker as identity A (via --token-a) and checks whether "
139
+ "identity B (--token-b, or anonymous if omitted) can read it back. "
140
+ "Non-local targets require --authorized and are your responsibility "
141
+ "to be permitted to test."
142
+ ),
143
+ )
144
+ scan.add_argument("url", help="MCP server endpoint, e.g. https://mcp.example.com/mcp")
145
+ scan.add_argument("--token-a", dest="token_a", default=None, help="Bearer token for identity A (the planter).")
146
+ scan.add_argument("--token-b", dest="token_b", default=None, help="Bearer token for identity B (the reader); omit for an anonymous B.")
147
+ scan.add_argument("--plant-tool", dest="plant_tool", required=True, help="Tool name A calls to store the marker.")
148
+ scan.add_argument("--read-tool", dest="read_tool", required=True, help="Tool name B calls to read it back.")
149
+ scan.add_argument("--key", default="secret", help="Key the marker is stored under (default: secret).")
150
+ scan.add_argument("--authorized", action="store_true", help="Confirm you are authorized to test this target (required for non-local hosts).")
151
+ scan.add_argument("--authorization-note", dest="authorization_note", default=None, help="Who authorized this test; recorded in the report.")
152
+ scan.add_argument("--json", action="store_true", help="Print the full JSON report.")
153
+ scan.set_defaults(func=cmd_scan)
154
+
155
+ surv = sub.add_parser(
156
+ "survey",
157
+ help="Statically triage MCP server source code (reads files only).",
158
+ description=(
159
+ "Parses Python source under PATH and lists tool handlers that touch "
160
+ "stored/shared state but reference no caller identity. This is "
161
+ "coarse, low-confidence triage: every hit needs reading by hand. "
162
+ "Nothing is executed and nothing is connected to."
163
+ ),
164
+ )
165
+ surv.add_argument("path", help="A source file or a directory of MCP server source.")
166
+ surv.add_argument("--json", action="store_true", help="Print the full JSON report.")
167
+ surv.add_argument("--all", action="store_true", help="With --json, include every handler found, not only the candidates.")
168
+ surv.add_argument("--include-tests", dest="include_tests", action="store_true", help="Also scan test files and tests/ directories.")
169
+ surv.set_defaults(func=cmd_survey)
170
+ return parser
171
+
172
+
173
+ def main(argv: Optional[List[str]] = None) -> int:
174
+ parser = build_parser()
175
+ args = parser.parse_args(argv)
176
+ func = getattr(args, "func", None)
177
+ if func is None:
178
+ parser.print_help()
179
+ return 2
180
+ return func(args)
181
+
182
+
183
+ if __name__ == "__main__":
184
+ raise SystemExit(main())