forked from tenuo-ai/tenuo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.py
More file actions
281 lines (233 loc) · 9.46 KB
/
Copy pathdemo.py
File metadata and controls
281 lines (233 loc) · 9.46 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""
Tenuo-Temporal Integration Demo
Demonstrates warrant-based authorization for Temporal workflows using
the production tenuo.temporal module:
- TenuoInterceptor enforces per-activity authorization at the worker level
- TenuoClientInterceptor injects warrant headers at workflow start
- tenuo_headers() serializes warrant + signing key for header transport
- tenuo_execute_activity() propagates headers and adds Proof-of-Possession
- EnvKeyResolver resolves signing keys from environment variables
- Parallel activity execution via asyncio.gather (each gets its own PoP)
Requirements:
pip install temporalio tenuo
Usage:
temporal server start-dev # Terminal 1
python demo.py # Terminal 2
"""
import asyncio
import base64
import logging
import os
import uuid
from datetime import timedelta
from pathlib import Path
# Temporal imports
try:
from temporalio import activity, workflow
from temporalio.client import Client
from temporalio.common import RetryPolicy
from temporalio.worker import Worker
except ImportError:
raise SystemExit("Install temporalio: pip install temporalio")
# Tenuo imports
from tenuo import SigningKey, Warrant
from tenuo_core import Subpath
from tenuo.temporal import (
TenuoInterceptor,
TenuoInterceptorConfig,
TenuoClientInterceptor,
EnvKeyResolver,
tenuo_headers,
tenuo_execute_activity,
TemporalAuditEvent,
)
# Logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger(__name__)
logging.getLogger("temporalio.activity").setLevel(logging.ERROR)
logging.getLogger("temporalio.worker").setLevel(logging.ERROR)
# =============================================================================
# Activities (Tools)
# =============================================================================
@activity.defn
async def read_file(path: str) -> str:
"""Read file — protected by Tenuo warrant."""
return Path(path).read_text()
@activity.defn
async def write_file(path: str, content: str) -> str:
"""Write file — protected by Tenuo warrant."""
Path(path).write_text(content)
return f"Wrote {len(content)} bytes to {path}"
@activity.defn
async def list_directory(path: str) -> list[str]:
"""List directory — protected by Tenuo warrant."""
return [str(p) for p in Path(path).iterdir()]
# =============================================================================
# Workflow — uses tenuo_execute_activity() for PoP-signed activity calls
# =============================================================================
@workflow.defn
class ResearchWorkflow:
"""Researches files within the scope authorized by its warrant."""
@workflow.run
async def run(self, data_dir: str) -> str:
no_retry = RetryPolicy(maximum_attempts=1)
files = await tenuo_execute_activity(
list_directory,
args=[data_dir],
start_to_close_timeout=timedelta(seconds=30),
retry_policy=no_retry,
)
results = []
for file_path in files:
if file_path.endswith(".txt"):
content = await tenuo_execute_activity(
read_file,
args=[file_path],
start_to_close_timeout=timedelta(seconds=30),
retry_policy=no_retry,
)
results.append(f"{file_path}: {len(content)} chars")
return f"Processed {len(results)} files"
@workflow.defn
class ParallelResearchWorkflow:
"""Reads multiple files in parallel — each gets its own PoP signature."""
@workflow.run
async def run(self, data_dir: str) -> str:
no_retry = RetryPolicy(maximum_attempts=1)
timeout = timedelta(seconds=30)
# Parallel reads: each tenuo_execute_activity() call gets an
# independent PoP slot keyed by (workflow_id, tool, args), so
# asyncio.gather works correctly without signature collision.
contents = await asyncio.gather(
tenuo_execute_activity(
read_file, args=[f"{data_dir}/paper1.txt"],
start_to_close_timeout=timeout, retry_policy=no_retry,
),
tenuo_execute_activity(
read_file, args=[f"{data_dir}/paper2.txt"],
start_to_close_timeout=timeout, retry_policy=no_retry,
),
tenuo_execute_activity(
read_file, args=[f"{data_dir}/notes.txt"],
start_to_close_timeout=timeout, retry_policy=no_retry,
),
)
total = sum(len(c) for c in contents)
return f"Parallel read {len(contents)} files ({total} chars)"
# =============================================================================
# Audit callback
# =============================================================================
def on_audit(event: TemporalAuditEvent):
if event.decision == "ALLOW":
logger.info(f" ALLOW {event.tool} (warrant: {event.warrant_id})")
else:
logger.warning(f" DENY {event.tool} — {event.denial_reason}")
# =============================================================================
# Main
# =============================================================================
async def main():
# --- Client setup (production TenuoClientInterceptor) ---
client_interceptor = TenuoClientInterceptor()
client = await Client.connect(
"localhost:7233", interceptors=[client_interceptor],
)
logger.info("Connected to Temporal server")
# --- Key generation (in production: Vault / KMS) ---
control_key = SigningKey.generate()
agent_key = SigningKey.generate()
# Publish agent key for the worker's EnvKeyResolver
os.environ["TENUO_KEY_agent1"] = base64.b64encode(
agent_key.secret_key_bytes()
).decode()
# --- Mint warrant ---
warrant = (
Warrant.mint_builder()
.holder(agent_key.public_key)
.capability("read_file", path=Subpath("/tmp/tenuo-demo"))
.capability("list_directory", path=Subpath("/tmp/tenuo-demo"))
.ttl(3600)
.mint(control_key)
)
logger.info(f"Minted warrant {warrant.id}")
logger.info(f" Tools: {warrant.tools}")
logger.info(f" Expires: {warrant.expires_at()}")
# Unique task queue per run avoids interference from old Temporal tasks
task_queue = f"tenuo-demo-{uuid.uuid4().hex[:8]}"
# --- Demo data ---
demo_dir = Path("/tmp/tenuo-demo")
demo_dir.mkdir(exist_ok=True)
(demo_dir / "paper1.txt").write_text("Content of paper 1")
(demo_dir / "paper2.txt").write_text("Content of paper 2")
(demo_dir / "notes.txt").write_text("Research notes")
# --- Worker setup with production TenuoInterceptor ---
worker_interceptor = TenuoInterceptor(
TenuoInterceptorConfig(
key_resolver=EnvKeyResolver(),
on_denial="raise",
audit_callback=on_audit,
trusted_roots=[control_key.public_key],
)
)
from temporalio.worker.workflow_sandbox import (
SandboxedWorkflowRunner,
SandboxRestrictions,
)
sandbox_runner = SandboxedWorkflowRunner(
restrictions=SandboxRestrictions.default.with_passthrough_modules(
"tenuo", "tenuo_core",
)
)
async with Worker(
client,
task_queue=task_queue,
workflows=[ResearchWorkflow, ParallelResearchWorkflow],
activities=[read_file, write_file, list_directory],
interceptors=[worker_interceptor],
workflow_runner=sandbox_runner,
):
logger.info("Worker started\n")
# ── Authorized sequential access ─────────────────────────
logger.info("=== Sequential access (path=/tmp/tenuo-demo) ===")
client_interceptor.set_headers(
tenuo_headers(warrant, "agent1", agent_key)
)
result = await client.execute_workflow(
ResearchWorkflow.run,
args=[str(demo_dir)],
id=f"research-{uuid.uuid4().hex[:8]}",
task_queue=task_queue,
)
logger.info(f"Result: {result}\n")
# ── Parallel activity execution ──────────────────────────
logger.info("=== Parallel activities (asyncio.gather) ===")
client_interceptor.set_headers(
tenuo_headers(warrant, "agent1", agent_key)
)
result = await client.execute_workflow(
ParallelResearchWorkflow.run,
args=[str(demo_dir)],
id=f"parallel-{uuid.uuid4().hex[:8]}",
task_queue=task_queue,
)
logger.info(f"Result: {result}\n")
# ── Unauthorized access ──────────────────────────────────
logger.info("=== Unauthorized access (path=/etc) ===")
try:
from temporalio.client import WorkflowFailureError
await client.execute_workflow(
ResearchWorkflow.run,
args=["/etc"], # outside warrant scope
id=f"unauth-{uuid.uuid4().hex[:8]}",
task_queue=task_queue,
)
logger.error("BUG: should have been denied!")
except WorkflowFailureError as e:
logger.info(f"Correctly denied: {e.cause}")
except Exception as e:
logger.info(f"Correctly denied: {e}")
if __name__ == "__main__":
asyncio.run(main())