Repository navigation
Expand file tree
/
Copy path10_user_isolation.py
More file actions
173 lines (141 loc) Β· 6.49 KB
/
Copy path10_user_isolation.py
File metadata and controls
173 lines (141 loc) Β· 6.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python3
"""
Example 10: User Isolation and Security
This example demonstrates the user-level security model for MCP servers:
- Per-user artifact isolation (users cannot see each other's files)
- The correct API for listing a user's artifacts (list_by_user)
- Why search() requires user_id
- Sandbox-shared artifacts (opt-in cross-user visibility)
"""
import asyncio
import os
os.environ.setdefault("ARTIFACT_PROVIDER", "memory")
os.environ.setdefault("SESSION_PROVIDER", "memory")
from chuk_artifacts import ArtifactStore
async def main():
print("=" * 70)
print("USER ISOLATION AND SECURITY")
print("=" * 70)
store = ArtifactStore(sandbox_id="demo-sandbox")
# ========================================================================
# Part 1: Store artifacts for two different users
# ========================================================================
print("\nπ PART 1: STORING ARTIFACTS FOR TWO USERS")
print("-" * 70)
# Alice stores a spreadsheet
alice_sheet = await store.store(
data=b"revenue,Q1,Q2\nalice_corp,100,200",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
summary="Alice's revenue sheet",
scope="user",
user_id="alice",
)
print(f"\n Alice stored: {alice_sheet}")
# Alice stores a presentation
alice_deck = await store.store(
data=b"slide1: intro\nslide2: results",
mime="application/vnd.openxmlformats-officedocument.presentationml.presentation",
summary="Alice's Q2 deck",
scope="user",
user_id="alice",
)
print(f" Alice stored: {alice_deck}")
# Bob stores a spreadsheet
bob_sheet = await store.store(
data=b"expenses,Q1,Q2\nbob_corp,50,80",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
summary="Bob's expense sheet",
scope="user",
user_id="bob",
)
print(f" Bob stored: {bob_sheet}")
# ========================================================================
# Part 2: list_by_user β correct API for MCP tools
# ========================================================================
print("\nβ
PART 2: list_by_user() β ISOLATED TO ONE USER")
print("-" * 70)
alice_files = await store.list_by_user("alice")
print(f"\n Alice's files ({len(alice_files)}):")
for f in alice_files:
print(f" β’ {f.summary} [{f.mime.split('.')[-1]}]")
bob_files = await store.list_by_user("bob")
print(f"\n Bob's files ({len(bob_files)}):")
for f in bob_files:
print(f" β’ {f.summary} [{f.mime.split('.')[-1]}]")
assert len(alice_files) == 2, "Alice should have 2 files"
assert len(bob_files) == 1, "Bob should have 1 file"
assert all(f.owner_id == "alice" for f in alice_files), (
"All Alice files owned by alice"
)
assert all(f.owner_id == "bob" for f in bob_files), "All Bob files owned by bob"
print("\n β No cross-user leakage confirmed")
# ========================================================================
# Part 3: Filter by MIME type (MCP tool: "list all spreadsheets")
# ========================================================================
print("\nπ PART 3: list_by_user() WITH MIME FILTER")
print("-" * 70)
xlsx_mime = "application/vnd.openxmlformats-officedocument.spreadsheetml"
alice_sheets = await store.list_by_user("alice", mime_prefix=xlsx_mime)
print(f"\n Alice's spreadsheets: {len(alice_sheets)}")
print(f" β’ {alice_sheets[0].summary}")
# Bob calling list_by_user("alice") is already blocked at the MCP layer
# (user_id comes from the auth context, not the request)
bob_sheets = await store.list_by_user("bob", mime_prefix=xlsx_mime)
print(f"\n Bob's spreadsheets: {len(bob_sheets)}")
print(f" β’ {bob_sheets[0].summary}")
print("\n β Each user only sees their own spreadsheets")
# ========================================================================
# Part 4: search() without user_id is blocked
# ========================================================================
print("\nπ PART 4: search() WITHOUT user_id IS BLOCKED")
print("-" * 70)
try:
# This is the vulnerable pattern Sheerin flagged β now blocked
await store.search(mime_prefix=xlsx_mime)
print(" β BUG: Should have raised ValueError")
except ValueError as e:
print(f"\n β Blocked: {e}")
# search() with user_id is fine
results = await store.search(user_id="alice", mime_prefix=xlsx_mime)
print(f"\n β search(user_id='alice') works: {len(results)} result(s)")
# ========================================================================
# Part 5: Sandbox-shared artifacts (explicit opt-in)
# ========================================================================
print("\nπ PART 5: SANDBOX-SHARED ARTIFACTS (opt-in)")
print("-" * 70)
# Admins can store shared resources accessible to everyone
shared_id = await store.store(
data=b"company logo bytes",
mime="image/png",
summary="Company logo (shared)",
scope="sandbox",
)
print(f"\n Shared artifact: {shared_id}")
# Anyone can search sandbox scope without user_id β this is intentional
shared = await store.search(scope="sandbox")
print(f" β search(scope='sandbox') finds {len(shared)} shared artifact(s)")
print(f" β’ {shared[0].summary}")
# ========================================================================
# Summary
# ========================================================================
print("\n" + "=" * 70)
print("β¨ USER ISOLATION SUMMARY")
print("=" * 70)
print("""
SECURITY RULES:
β list_by_user(user_id) β always isolated to one user
β search(user_id=..., ...) β user_id required (no cross-user scans)
β search(scope='sandbox') β shared artifacts only (opt-in)
β search() β BLOCKED: raises ValueError
β search(scope='user') β BLOCKED: user_id required
MCP TOOL PATTERN:
async def list_my_spreadsheets(ctx):
user_id = ctx.get_user_id() # from auth context
return await store.list_by_user(
user_id,
mime_prefix="application/vnd.openxmlformats-officedocument.spreadsheetml",
)
This ensures Alice's MCP server call NEVER returns Bob's files.
""")
if __name__ == "__main__":
asyncio.run(main())