-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_http.py
More file actions
1635 lines (1473 loc) · 62.3 KB
/
Copy pathtest_http.py
File metadata and controls
1635 lines (1473 loc) · 62.3 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""HTTP endpoint tests.
We don't spawn a full subprocess (too slow, fragile on CI) — instead we
instantiate a ThreadingHTTPServer in-process on an ephemeral port and drive
it with urllib. This matches the real code path in serve_proxy except for
signal handling, which we don't exercise."""
from __future__ import annotations
import json
import os
import socket
import stat
import threading
import time
import urllib.error
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
from typing import Any
import jwt
import pytest
# We reach inside serve_proxy to grab the Handler class. The simplest path
# that preserves the production code path is to re-import and re-build the
# server via the public function's logic. Here we clone enough of serve_proxy
# to stand up an HTTP server for testing. If serve_proxy gets refactored into
# a factory, swap this for a direct call.
import vibap.mission as mission_module
from vibap.passport import ALGORITHM, MissionPassport, issue_passport
from vibap.proxy import GovernanceProxy, serve_proxy
from vibap.receipt import verify_chain
from tests.conftest import (
v01_default_status_list_token,
v01_default_status_url,
v01_required_md_extras,
)
def _build_server_thread(proxy: GovernanceProxy, private_key, port: int):
"""Start serve_proxy in a background daemon thread bound to 127.0.0.1:port.
Returns (thread, server_url, shutdown_callable). We monkeypatch
ThreadingHTTPServer.serve_forever to return after shutdown and
avoid registering a SIGTERM handler in a thread (signals only work on
the main thread)."""
# Swap serve_proxy's signal.signal for a no-op in this thread via a
# monkeypatch-free approach: we run the server manually here.
# Easier path: import the Handler factory used internally. But it's a
# closure inside serve_proxy, so we simply call serve_proxy and let it
# install its signal handler — signal.signal() from a non-main thread
# raises ValueError. To work around, monkeypatch signal.signal before
# running.
import signal as _signal
original = _signal.signal
_signal.signal = lambda *_a, **_kw: None # type: ignore[assignment]
stop_event = threading.Event()
def run() -> None:
try:
serve_proxy(
proxy=proxy,
private_key=private_key,
host="127.0.0.1",
port=port,
require_auth=False,
no_tls=True,
)
finally:
stop_event.set()
thread = threading.Thread(target=run, daemon=True)
thread.start()
# Wait for the server to respond to /health.
base = f"http://127.0.0.1:{port}"
deadline = time.time() + 5
last_exc: Exception | None = None
while time.time() < deadline:
try:
with urllib.request.urlopen(base + "/health", timeout=0.5) as resp:
if resp.status == 200:
break
except Exception as exc: # noqa: BLE001
last_exc = exc
time.sleep(0.05)
else:
raise RuntimeError(f"proxy never became healthy: {last_exc}")
def shutdown() -> None:
# Send a shutdown by closing the server via an internal request.
# ThreadingHTTPServer exposes shutdown() but we don't have a handle to
# the server instance. Fallback: rely on daemon=True + test process
# teardown. This is fine for unit tests.
_signal.signal = original
return thread, base, shutdown
def _post(url: str, payload: dict[str, Any]) -> tuple[int, dict[str, Any]]:
status, body, _ = _post_with_headers(url, payload)
return status, body
def _post_with_headers(url: str, payload: dict[str, Any]) -> tuple[int, dict[str, Any], dict[str, str]]:
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=5) as resp:
return resp.status, json.loads(resp.read().decode("utf-8")), dict(resp.headers.items())
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8")
try:
parsed = json.loads(body)
except json.JSONDecodeError:
parsed = {"raw": body}
return exc.code, parsed, dict(exc.headers.items())
def _get(url: str) -> tuple[int, dict[str, Any]]:
with urllib.request.urlopen(url, timeout=5) as resp:
return resp.status, json.loads(resp.read().decode("utf-8"))
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return int(sock.getsockname()[1])
@pytest.fixture
def http_proxy(proxy, private_key, unused_tcp_port):
thread, base, shutdown = _build_server_thread(proxy, private_key, unused_tcp_port)
yield base, proxy
shutdown()
class TestHTTPHealth:
def test_get_health_returns_200(self, http_proxy):
base, _ = http_proxy
status, body = _get(base + "/health")
assert status == 200
assert body["status"] == "ok"
assert "version" in body
class TestHTTPEvaluate:
def test_permit_decision(self, http_proxy, example_mission, private_key):
base, _ = http_proxy
token = issue_passport(example_mission, private_key, ttl_s=60)
status, start = _post(base + "/session/start", {"token": token})
assert status == 200
session_id = start["session_id"]
status, body = _post(
base + "/evaluate",
{"session_id": session_id, "tool_name": "read_file", "arguments": {"path": "/x"}},
)
assert status == 200
assert body["decision"] == "PERMIT"
def test_deny_decision(self, http_proxy, example_mission, private_key):
base, _ = http_proxy
token = issue_passport(example_mission, private_key, ttl_s=60)
_, start = _post(base + "/session/start", {"token": token})
session_id = start["session_id"]
status, body = _post(
base + "/evaluate",
{"session_id": session_id, "tool_name": "delete_file", "arguments": {}},
)
assert status == 200
assert body["decision"] == "DENY"
assert "reason" in body
def test_revoked_active_session_returns_403(self, http_proxy, example_mission, private_key):
base, proxy = http_proxy
token = issue_passport(example_mission, private_key, ttl_s=60)
_, start = _post(base + "/session/start", {"token": token})
session_id = start["session_id"]
status, body = _post(
base + "/evaluate",
{"session_id": session_id, "tool_name": "read_file", "arguments": {"path": "/x"}},
)
assert status == 200
assert body["decision"] == "PERMIT"
proxy.revoke(session_id)
status, body = _post(
base + "/evaluate",
{"session_id": session_id, "tool_name": "read_file", "arguments": {"path": "/x"}},
)
assert status == 403
assert body == {"error": "passport_revoked"}
class TestHTTPDelegate:
def test_valid_delegation_returns_200(self, http_proxy, private_key):
base, _ = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="p",
allowed_tools=["read", "write"],
delegation_allowed=True,
max_delegation_depth=2,
max_duration_s=300,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
# Parent session must be started before delegation (Phase 2e / external-review-G F3)
_post(base + "/session/start", {"token": parent_token})
status, body = _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": "child",
"child_mission": "sub",
"child_allowed_tools": ["read"],
"child_ttl_s": 60,
},
)
assert status == 200
assert "child_token" in body
assert body["child_claims"]["allowed_tools"] == ["read"]
def test_delegation_escalation_returns_403(self, http_proxy, private_key):
base, _ = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="p",
allowed_tools=["read"],
delegation_allowed=True,
max_delegation_depth=2,
max_duration_s=300,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_post(base + "/session/start", {"token": parent_token})
status, body = _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": "child",
"child_mission": "evil",
"child_allowed_tools": ["read", "rm_rf"],
"child_ttl_s": 60,
},
)
assert status == 403
assert "scope escalation" in body.get("error", "")
def test_duplicate_delegation_request_id_is_idempotent(
self, http_proxy, private_key
):
base, proxy = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
max_tool_calls=1,
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_, start = _post(base + "/session/start", {"token": parent_token})
request = {
"parent_token": parent_token,
"child_agent_id": "child",
"child_mission": "sub",
"child_allowed_tools": ["read"],
"child_max_tool_calls": 1,
"delegation_request_id": "retry-1",
}
status1, body1 = _post(base + "/delegate", request)
status2, body2 = _post(base + "/delegate", request)
assert status1 == 200
assert status2 == 200
assert body1["child_claims"]["max_tool_calls"] == 1
assert body2["child_claims"]["max_tool_calls"] == 1
assert body2["child_token"] == body1["child_token"]
assert body2["child_claims"]["jti"] == body1["child_claims"]["jti"]
snapshot = proxy.lineage_budget_ledger.snapshot(start["session_id"])
assert snapshot["reserved_total"] == 1
assert len(snapshot["reservations"]) == 1
reservation = snapshot["reservations"]["retry-1"]
assert reservation["child_jti"] == body1["child_claims"]["jti"]
parent_session = proxy.get_session(start["session_id"])
matching_children = [
child
for child in parent_session.delegated_children
if child["delegation_request_id"] == "retry-1"
]
assert len(matching_children) == 1
assert matching_children[0]["child_jti"] == body1["child_claims"]["jti"]
delegation_events = [
event
for event in parent_session.events
if event.tool_name == "delegate_passport"
and event.arguments.get("delegation_request_id") == "retry-1"
]
assert len(delegation_events) == 1
def test_duplicate_delegation_request_id_normalized_retry_is_idempotent(
self, http_proxy, private_key
):
base, _ = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read", "write"],
resource_scope=["/data/*", "/logs/*"],
max_tool_calls=3,
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_post(base + "/session/start", {"token": parent_token})
first = {
"parent_token": parent_token,
"child_agent_id": "child",
"child_mission": "sub",
"child_allowed_tools": ["write", "read"],
"child_resource_scope": ["/logs/*", "/data/*"],
"child_max_tool_calls": 2,
"child_ttl_s": 120,
"delegation_request_id": "retry-normalized",
}
second = dict(
first,
child_allowed_tools=["read", "write"],
child_resource_scope=["/data/*", "/logs/*"],
)
status1, body1 = _post(base + "/delegate", first)
status2, body2 = _post(base + "/delegate", second)
assert status1 == 200
assert status2 == 200
assert body2["child_token"] == body1["child_token"]
assert body2["child_claims"]["jti"] == body1["child_claims"]["jti"]
assert body2["child_claims"]["allowed_tools"] == ["read", "write"]
assert body2["child_claims"]["resource_scope"] == ["/data/*", "/logs/*"]
def test_conflicting_delegation_request_id_returns_409(
self, http_proxy, private_key
):
base, _ = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
max_tool_calls=2,
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_post(base + "/session/start", {"token": parent_token})
first = {
"parent_token": parent_token,
"child_agent_id": "child-a",
"child_mission": "sub",
"child_allowed_tools": ["read"],
"child_max_tool_calls": 1,
"delegation_request_id": "dup",
}
second = dict(first, child_agent_id="child-b")
status1, _ = _post(base + "/delegate", first)
status2, body2 = _post(base + "/delegate", second)
assert status1 == 200
assert status2 == 409
assert "different reservation" in body2.get("error", "")
@pytest.mark.parametrize(
("field", "replacement"),
[
("child_mission", "narrow-request"),
("child_allowed_tools", ["read"]),
("child_resource_scope", ["/data/*"]),
("child_max_tool_calls", 1),
("child_ttl_s", 60),
],
)
def test_duplicate_delegation_request_id_changed_request_fields_return_409(
self, http_proxy, private_key, field, replacement
):
base, _ = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read", "write"],
resource_scope=["/data/*", "/logs/*"],
max_tool_calls=5,
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_post(base + "/session/start", {"token": parent_token})
first = {
"parent_token": parent_token,
"child_agent_id": "child",
"child_mission": "broad",
"child_allowed_tools": ["read", "write"],
"child_resource_scope": ["/data/*", "/logs/*"],
"child_max_tool_calls": 2,
"child_ttl_s": 120,
"delegation_request_id": "dup-same-child",
}
second = dict(first, **{field: replacement})
status1, body1 = _post(base + "/delegate", first)
status2, body2 = _post(base + "/delegate", second)
assert status1 == 200
assert body1["child_claims"]["mission"] == "broad"
assert body1["child_claims"]["allowed_tools"] == ["read", "write"]
assert body1["child_claims"]["resource_scope"] == ["/data/*", "/logs/*"]
assert body1["child_claims"]["max_tool_calls"] == 2
assert status2 == 409
assert "different reservation" in body2.get("error", "")
assert "child_token" not in body2
def test_persisted_delegation_session_files_are_private_under_permissive_umask(
self, tmp_path, public_key, private_key, session_keys_dir
):
state_dir = tmp_path / "caller-state"
state_dir.mkdir(mode=0o755)
original_umask = os.umask(0o022)
shutdown = None
try:
proxy = GovernanceProxy(
log_path=tmp_path / "governance_log.jsonl",
state_dir=state_dir,
public_key=public_key,
keys_dir=session_keys_dir,
)
_, base, shutdown = _build_server_thread(proxy, private_key, _free_port())
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
max_tool_calls=2,
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_, start = _post(base + "/session/start", {"token": parent_token})
status, _body = _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": "child",
"child_mission": "sub",
"child_allowed_tools": ["read"],
"child_max_tool_calls": 1,
"delegation_request_id": "secret-replay",
},
)
assert status == 200
session_path = proxy._session_path(start["session_id"])
payload = json.loads(session_path.read_text(encoding="utf-8"))
assert any(
isinstance(child.get("child_token"), str) and child["child_token"]
for child in payload["delegated_children"]
)
assert stat.S_IMODE(state_dir.stat().st_mode) == 0o700
assert stat.S_IMODE((state_dir / "sessions").stat().st_mode) == 0o700
assert stat.S_IMODE(session_path.stat().st_mode) == 0o600
assert stat.S_IMODE(session_path.stat().st_mode) & 0o077 == 0
finally:
os.umask(original_umask)
if shutdown is not None:
shutdown()
def test_two_http_proxies_shared_state_concurrent_sibling_budget(
self, tmp_path, public_key, private_key, session_keys_dir
):
shared_state = tmp_path / "shared-state"
p1 = GovernanceProxy(
log_path=tmp_path / "p1.jsonl",
state_dir=shared_state,
public_key=public_key,
keys_dir=session_keys_dir,
)
p2 = GovernanceProxy(
log_path=tmp_path / "p2.jsonl",
state_dir=shared_state,
public_key=public_key,
keys_dir=session_keys_dir,
)
_, base1, shutdown1 = _build_server_thread(p1, private_key, _free_port())
_, base2, shutdown2 = _build_server_thread(p2, private_key, _free_port())
try:
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
max_tool_calls=5,
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_, start = _post(base1 + "/session/start", {"token": parent_token})
def delegate(i: int) -> tuple[int, dict[str, Any]]:
base = base1 if i % 2 == 0 else base2
return _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": f"child-{i}",
"child_mission": f"sub-{i}",
"child_allowed_tools": ["read"],
"child_max_tool_calls": 1,
"delegation_request_id": f"r{i}",
},
)
with ThreadPoolExecutor(max_workers=16) as pool:
results = list(pool.map(delegate, range(24)))
accepted = [
body["child_claims"]["max_tool_calls"]
for status, body in results
if status == 200
]
rejected = [status for status, _ in results if status != 200]
assert sum(accepted) == 5
assert all(status == 403 for status in rejected)
assert p1.lineage_budget_ledger.snapshot(start["session_id"])[
"reserved_total"
] == 5
finally:
shutdown2()
shutdown1()
class TestHTTPAuthAndValidation:
@pytest.mark.parametrize(
("path", "payload"),
[
("/verify", {"token": "not-a-jwt"}),
("/session/start", {"token": "not-a-jwt"}),
("/sessions", {"token": "not-a-jwt"}),
(
"/delegate",
{
"parent_token": "not-a-jwt",
"child_agent_id": "child",
"child_mission": "subtask",
"child_allowed_tools": ["read"],
},
),
],
)
def test_invalid_jwt_returns_401_with_www_authenticate(
self, http_proxy, path, payload
):
base, _ = http_proxy
status, body, headers = _post_with_headers(base + path, payload)
assert status == 401
assert body == {"error": "invalid_token"}
assert headers["WWW-Authenticate"] == 'Bearer error="invalid_token"'
def test_issue_with_non_object_mission_returns_400(self, http_proxy):
base, _ = http_proxy
status, body = _post(base + "/issue", {"mission": None})
assert status == 400
assert body == {"error": "mission must be a JSON object"}
def test_issue_with_lineage_budgets_fails_phase1_deferred(self, http_proxy):
base, _ = http_proxy
status, body = _post(
base + "/issue",
{
"mission": {
"agent_id": "parent",
"mission": "coordinate child work",
"allowed_tools": ["read"],
"delegation_allowed": True,
"max_delegation_depth": 1,
"lineage_budgets": [
{"type": "max_child_tool_calls", "limit": 3}
],
}
},
)
assert status == 400
assert "token" not in body
assert "lineage_budgets" in body.get("error", "")
assert "Phase 1" in body.get("error", "")
assert "deferred" in body.get("error", "")
def test_delegate_rejects_string_child_tools_before_char_splitting(
self, http_proxy, private_key
):
base, _ = http_proxy
parent = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent, private_key, ttl_s=300)
_post(base + "/session/start", {"token": parent_token})
status, body = _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": "child",
"child_mission": "sub",
"child_allowed_tools": "read",
},
)
assert status == 400
assert body == {
"error": "child_allowed_tools must be a JSON array of non-empty strings"
}
def test_delegate_rejects_string_child_resource_scope_before_char_splitting(
self, http_proxy, private_key
):
base, _ = http_proxy
parent = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
resource_scope=["/data/*"],
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent, private_key, ttl_s=300)
_post(base + "/session/start", {"token": parent_token})
status, body = _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": "child",
"child_mission": "sub",
"child_allowed_tools": ["read"],
"child_resource_scope": "/data/*",
},
)
assert status == 400
assert body == {
"error": "child_resource_scope must be a JSON array of non-empty strings"
}
class TestHTTPSessionEnd:
def test_session_end_includes_attestation(self, http_proxy, example_mission, private_key):
base, _ = http_proxy
token = issue_passport(example_mission, private_key, ttl_s=60)
_, start = _post(base + "/session/start", {"token": token})
session_id = start["session_id"]
_post(
base + "/evaluate",
{"session_id": session_id, "tool_name": "read_file", "arguments": {}},
)
status, body = _post(base + "/session/end", {"session_id": session_id})
assert status == 200
assert "attestation_token" in body
assert "summary" in body
assert body["summary"]["permits"] >= 1
def test_session_start_returns_503_when_replay_cache_deleted(self, http_proxy, example_mission, private_key):
base, proxy = http_proxy
token = issue_passport(example_mission, private_key, ttl_s=60)
_post(base + "/session/start", {"token": token})
proxy.replay_cache_path.unlink()
fresh_token = issue_passport(example_mission, private_key, ttl_s=60)
status, body = _post(base + "/session/start", {"token": fresh_token})
assert status == 503
assert body == {"error": "replay_cache_unavailable"}
def test_attest_is_idempotent_after_end(self, http_proxy, example_mission, private_key):
base, _ = http_proxy
token = issue_passport(example_mission, private_key, ttl_s=60)
_, start = _post(base + "/session/start", {"token": token})
session_id = start["session_id"]
_post(
base + "/evaluate",
{"session_id": session_id, "tool_name": "read_file", "arguments": {}},
)
status, body = _post(base + "/end", {"session": session_id})
assert status == 200
assert "summary" in body
status1, attestation1 = _post(base + "/attest", {"session": session_id})
time.sleep(1.1)
status2, attestation2 = _post(base + "/attest", {"session": session_id})
assert status1 == 200
assert status2 == 200
assert attestation1 == attestation2
class TestDelegateRequiresActiveParentSession:
"""Regression test for external-review-G F3: /delegate previously fell back to the
parent's ceiling if the parent session wasn't in the in-memory dict.
Now it must refuse unless there's a persisted session for the parent jti."""
def test_delegate_without_started_parent_returns_403(
self, http_proxy, private_key
):
base, _ = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
max_tool_calls=100, # Big budget
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
# Do NOT call /session/start. Attempt to delegate directly.
status, body = _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": "c",
"child_mission": "sub",
"child_allowed_tools": ["read"],
"child_max_tool_calls": 999, # try to get huge budget
},
)
assert status == 403
assert "parent session" in body.get("error", "").lower()
def test_delegate_with_ended_parent_returns_403(
self, http_proxy, private_key
):
"""A parent session that's been ended should not be able to spawn children."""
base, _ = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
max_tool_calls=100,
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_, start = _post(base + "/session/start", {"token": parent_token})
session_id = start["session_id"]
_post(base + "/session/end", {"session_id": session_id})
status, body = _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": "c",
"child_mission": "sub",
"child_allowed_tools": ["read"],
},
)
assert status == 403
assert "ended" in body.get("error", "").lower()
def test_delegate_with_active_parent_caps_child_at_remaining(
self, http_proxy, private_key
):
"""With a real parent session that has used some budget, the child's
budget is clamped to the remaining, not the ceiling."""
base, _ = http_proxy
parent_mission = MissionPassport(
agent_id="parent",
mission="coord",
allowed_tools=["read"],
max_tool_calls=10,
delegation_allowed=True,
max_delegation_depth=2,
)
parent_token = issue_passport(parent_mission, private_key, ttl_s=300)
_, start = _post(base + "/session/start", {"token": parent_token})
session_id = start["session_id"]
# Burn 7 calls of the 10 budget
for _ in range(7):
_post(base + "/evaluate", {
"session_id": session_id,
"tool_name": "read",
"arguments": {},
})
# Delegate — parent has 3 remaining; child should get at most 3
status, body = _post(
base + "/delegate",
{
"parent_token": parent_token,
"child_agent_id": "c",
"child_mission": "sub",
"child_allowed_tools": ["read"],
"child_max_tool_calls": 999, # ask for way more
},
)
assert status == 200
assert body["child_claims"]["max_tool_calls"] == 3
assert body["parent_calls_remaining_at_delegation"] == 3
class _AATResponse:
def __init__(self, body: str | bytes) -> None:
self._body = body.encode("utf-8") if isinstance(body, str) else body
def read(self, size: int = -1) -> bytes:
if size < 0:
return self._body
return self._body[:size]
def __enter__(self) -> "_AATResponse":
return self
def __exit__(self, exc_type, exc, tb) -> bool:
return False
def _install_aat_fetch_map(
monkeypatch,
mapping: dict[str, str],
*,
private_key=None,
mission_ids: list[str] | None = None,
) -> None:
"""As :func:`tests.test_aat_adapter._install_fetch_map`, but for the
HTTP integration tests. Pass ``private_key`` + ``mission_ids`` to
auto-include the never-revoked status-list responses for each
mission's helper-default revocation URL (FIX-3, 2026-04-28)."""
full_mapping: dict[str, str] = dict(mapping)
if private_key is not None and mission_ids:
for mission_id in mission_ids:
url = v01_default_status_url(mission_id)
full_mapping.setdefault(
url, v01_default_status_list_token(private_key, mission_id)
)
def fake_urlopen(request, timeout=0, context=None): # noqa: ANN001, ARG001
url = request.full_url if hasattr(request, "full_url") else str(request)
return _AATResponse(full_mapping[url])
monkeypatch.setattr(mission_module, "urlopen", fake_urlopen)
def _issue_aat_md(private_key, *, mission_id: str) -> str:
mission = MissionPassport(
agent_id="md-authority",
mission="authoritative AAT HTTP mission",
allowed_tools=["read"],
forbidden_tools=[],
resource_scope=[],
max_tool_calls=3,
max_duration_s=300,
delegation_allowed=True,
max_delegation_depth=2,
)
return issue_passport(
mission,
private_key,
ttl_s=300,
extra_claims=v01_required_md_extras(mission_id=mission_id),
)
def _issue_aat_http_token(
private_key,
*,
mission_ref: dict[str, str],
tools: list[str],
grant_id: str | None = None,
) -> str:
now = int(time.time())
return jwt.encode(
{
"iss": "https://tenuo.example/issuer",
"sub": "aat-http-agent",
"iat": now,
"exp": now + 300,
"jti": grant_id or str(uuid.uuid4()),
"aat_type": "delegation",
"del_depth": 0,
"del_max_depth": 2,
"mission_ref": mission_ref,
"authorization_details": [
{
"type": "attenuating_agent_token",
"tools": {tool: {} for tool in tools},
"max_tool_calls": 2,
}
],
"cnf": {"jwk": {"kid": "holder-key"}},
},
private_key,
algorithm=ALGORITHM,
)
class TestHTTPAATInterop:
def test_aat_session_evaluate_delegate_receipt_chain(
self, http_proxy, private_key, public_key, monkeypatch
):
base, proxy = http_proxy
mission_id = "urn:ardur:mission:aat:http"
md_url = "https://issuer.example/md/aat-http.jwt"
md_token = _issue_aat_md(private_key, mission_id=mission_id)
md = mission_module.load_mission_declaration(md_token, public_key)
_install_aat_fetch_map(
monkeypatch,
{md_url: md_token},
private_key=private_key,
mission_ids=[mission_id],
)
aat_jti = str(uuid.uuid4())
aat_token = _issue_aat_http_token(
private_key,
grant_id=aat_jti,
mission_ref={
"uri": md_url,
"mission_id": mission_id,
"mission_digest": md.payload_digest,
},
tools=["read"],
)
# require_pop=False is an explicit opt-out: the test factory above
# mints a cnf-bearing AAT, but this test is exercising the HTTP
# session/evaluate/delegate path, not RFC 7800 PoP. Since 2026-04-28
# the proxy defaults require_pop=True for cnf-bearing AATs, so the
# opt-out has to be visible in the request body. PoP coverage lives
# in test_aat_adapter.py::TestAATProofOfPossession; HTTP-side
# PoP coverage is the new TestHTTPAATPoP class below.
status, start = _post(
base + "/session/start",
{"token_type": "aat", "token": aat_token, "require_pop": False},
)
assert status == 200
assert start["session_id"] == aat_jti
assert start["credential_format"] == "aat-compatible-jwt"
status, body = _post(
base + "/evaluate",
{"session_id": aat_jti, "tool_name": "read", "arguments": {}},
)
assert status == 200
assert body["decision"] == "PERMIT"
status, delegated = _post(
base + "/delegate",
{
"parent_token": aat_token,
"child_agent_id": "aat-child",
"child_mission": "subtask",
"child_allowed_tools": ["read"],
"child_max_tool_calls": 1,
"delegation_request_id": "aat-http-child",
},
)
assert status == 200
assert delegated["parent_jti"] == aat_jti
entries = [
json.loads(line)
for line in proxy.receipts_log_path.read_text(encoding="utf-8").splitlines()
]
claims = verify_chain([entry["jwt"] for entry in entries], public_key)
assert [claim["tool"] for claim in claims] == ["read", "delegate_passport"]
assert {claim["grant_id"] for claim in claims} == {aat_jti}
assert claims[0]["evidence_proof_ref"]["mission_digest"] == md.payload_digest
# --- Round-3 audit (2026-04-28): the round-2 audit flagged that the only
# HTTP /sessions PoP test was the require_pop=False opt-out path. The
# fail-closed default + the kb_jwt size bound were untested. These
# regressions pin the new HTTP-edge guards so future refactors can't