-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathtest_auth_framework.py
More file actions
1546 lines (1209 loc) · 52.1 KB
/
Copy pathtest_auth_framework.py
File metadata and controls
1546 lines (1209 loc) · 52.1 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
"""Unit tests for the pluggable request-auth framework."""
from __future__ import annotations
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
from agent_control_server.auth_framework.core import (
Operation,
Principal,
clear_authorizers,
get_authorizer,
require_operation,
set_authorizer,
)
from agent_control_server.auth_framework.providers import (
AccessLevel,
HeaderAuthProvider,
HttpUpstreamAuthProvider,
LocalJwtVerifyProvider,
NoAuthProvider,
)
from agent_control_server.auth_framework.providers.header import (
DEFAULT_OPERATION_ACCESS,
)
from agent_control_server.auth_framework.providers.http_upstream import (
HttpUpstreamConfig,
)
from agent_control_server.config import auth_settings
from agent_control_server.errors import (
APIError,
AuthenticationError,
ForbiddenError,
NotFoundError,
)
from agent_control_server.models import DEFAULT_NAMESPACE_KEY
def _build_request(
*,
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
):
"""Build a minimal Starlette-compatible request mock."""
request = MagicMock()
request.headers = headers or {}
request.cookies = cookies or {}
return request
def _clear_auth_settings_cache() -> None:
for attr in (
"_parsed_api_keys",
"_parsed_admin_api_keys",
"_all_valid_keys",
"_all_admin_keys",
):
auth_settings.__dict__.pop(attr, None)
# 32-byte test secret (HS256 wants >= 32 bytes; shorter raises a warning).
_TEST_SECRET = "test-runtime-secret-12345678901234567890"
_OTHER_SECRET = "other-runtime-secret-1234567890123456789"
# ---------------------------------------------------------------------------
# Coverage of operation -> access-level mapping
# ---------------------------------------------------------------------------
def test_default_operation_access_covers_every_operation():
"""Every Operation member must declare a default access level."""
missing = [op for op in Operation if op not in DEFAULT_OPERATION_ACCESS]
assert not missing, f"Operations missing default access mapping: {missing}"
# ---------------------------------------------------------------------------
# NoAuthProvider
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_no_auth_provider_allows_any_operation():
provider = NoAuthProvider(default_namespace_key="ns-local")
principal = await provider.authorize(
_build_request(),
Operation.CONTROLS_DELETE,
)
assert principal == Principal(namespace_key="ns-local")
@pytest.mark.asyncio
async def test_no_auth_provider_grants_runtime_exchange_scope():
provider = NoAuthProvider()
principal = await provider.authorize(
_build_request(),
Operation.RUNTIME_TOKEN_EXCHANGE,
)
assert principal.scopes == (Operation.RUNTIME_USE.value,)
# ---------------------------------------------------------------------------
# HeaderAuthProvider
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_header_provider_no_auth_mode_passes_admin_op():
"""When ``api_key_enabled`` is False, even admin operations succeed.
Preserves the pre-framework behavior where setting the server into
no-auth mode opens every endpoint regardless of access level.
"""
provider = HeaderAuthProvider()
with patch("agent_control_server.auth.auth_settings.api_key_enabled", False):
principal = await provider.authorize(
_build_request(),
Operation.CONTROL_BINDINGS_WRITE,
)
assert principal.namespace_key == DEFAULT_NAMESPACE_KEY
assert principal.is_admin is False
@pytest.mark.asyncio
async def test_header_provider_public_returns_default_namespace():
provider = HeaderAuthProvider(
operation_access={Operation.CONTROL_BINDINGS_READ: AccessLevel.PUBLIC}
)
principal = await provider.authorize(
_build_request(),
Operation.CONTROL_BINDINGS_READ,
)
assert principal == Principal(namespace_key=DEFAULT_NAMESPACE_KEY)
@pytest.mark.asyncio
async def test_header_provider_authenticated_calls_local_validator():
provider = HeaderAuthProvider()
expected_client = MagicMock(is_admin=False, key_id="abc12345")
with patch(
"agent_control_server.auth_framework.providers.header._validate_api_key",
new=AsyncMock(return_value=expected_client),
) as mocked:
principal = await provider.authorize(
_build_request(headers={"X-API-Key": "key-123"}),
Operation.CONTROL_BINDINGS_READ,
)
mocked.assert_awaited_once()
args, kwargs = mocked.await_args
assert args[0] == "key-123"
assert kwargs["require_admin"] is False
assert principal.namespace_key == DEFAULT_NAMESPACE_KEY
assert principal.is_admin is False
assert principal.caller_id == "abc12345"
@pytest.mark.asyncio
async def test_header_provider_admin_op_requires_admin():
provider = HeaderAuthProvider()
admin_client = MagicMock(is_admin=True, key_id="admin01")
with patch(
"agent_control_server.auth_framework.providers.header._validate_api_key",
new=AsyncMock(return_value=admin_client),
) as mocked:
principal = await provider.authorize(
_build_request(headers={"X-API-Key": "admin-key"}),
Operation.CONTROL_BINDINGS_WRITE,
)
args, kwargs = mocked.await_args
assert kwargs["require_admin"] is True
assert principal.is_admin is True
@pytest.mark.asyncio
async def test_header_provider_v1_ignores_namespace_header():
"""V1 always returns the default namespace regardless of header value."""
provider = HeaderAuthProvider(
operation_access={Operation.CONTROL_BINDINGS_READ: AccessLevel.PUBLIC}
)
principal = await provider.authorize(
_build_request(headers={"X-Namespace-Key": "org-foo"}),
Operation.CONTROL_BINDINGS_READ,
)
assert principal.namespace_key == DEFAULT_NAMESPACE_KEY
@pytest.mark.asyncio
async def test_header_provider_unknown_operation_raises():
provider = HeaderAuthProvider(operation_access={})
with pytest.raises(RuntimeError, match="No access level"):
await provider.authorize(
_build_request(),
Operation.CONTROL_BINDINGS_READ,
)
# ---------------------------------------------------------------------------
# HttpUpstreamAuthProvider
# ---------------------------------------------------------------------------
def _build_upstream(
response_factory,
*,
config_overrides: dict[str, Any] | None = None,
) -> HttpUpstreamAuthProvider:
config_kwargs: dict[str, Any] = {"url": "https://upstream.example/check"}
if config_overrides:
config_kwargs.update(config_overrides)
config = HttpUpstreamConfig(**config_kwargs)
transport = httpx.MockTransport(response_factory)
client = httpx.AsyncClient(transport=transport)
return HttpUpstreamAuthProvider(config, client=client)
def _patch_owned_upstream_client(monkeypatch) -> dict[str, Any]:
captured: dict[str, Any] = {}
ssl_context = object()
class FakeAsyncClient:
def __init__(self, **kwargs: Any) -> None:
captured.update(kwargs)
async def aclose(self) -> None:
captured["closed"] = True
def fake_create_default_context(*, cafile: str | None = None) -> object:
captured["cafile"] = cafile
return ssl_context
monkeypatch.setattr(
"agent_control_server.auth_framework.providers.http_upstream.httpx.AsyncClient",
FakeAsyncClient,
)
monkeypatch.setattr(
"agent_control_server.auth_framework.providers.http_upstream.ssl.create_default_context",
fake_create_default_context,
)
captured["ssl_context"] = ssl_context
return captured
@pytest.mark.asyncio
async def test_http_upstream_returns_principal_on_200():
captured: dict[str, Any] = {}
def factory(request: httpx.Request) -> httpx.Response:
captured["url"] = str(request.url)
captured["headers"] = dict(request.headers)
return httpx.Response(
200,
json={
"namespace_key": "org-7",
"is_admin": True,
"caller_id": "user-42",
},
)
provider = _build_upstream(factory)
request = _build_request(headers={"X-API-Key": "caller-key"})
principal = await provider.authorize(request, Operation.CONTROL_BINDINGS_WRITE)
assert principal == Principal(namespace_key="org-7", is_admin=True, caller_id="user-42")
assert captured["url"] == "https://upstream.example/check"
assert captured["headers"]["x-api-key"] == "caller-key"
@pytest.mark.asyncio
async def test_http_upstream_forwards_service_token():
captured: dict[str, Any] = {}
def factory(request: httpx.Request) -> httpx.Response:
captured["headers"] = dict(request.headers)
return httpx.Response(200, json={"namespace_key": "ns"})
provider = _build_upstream(
factory,
config_overrides={
"service_token": "shh",
"service_token_header": "X-Custom-Token",
},
)
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_READ)
assert captured["headers"]["x-custom-token"] == "shh"
def test_http_upstream_rejects_service_token_header_collision():
with pytest.raises(ValueError, match="service_token_header"):
HttpUpstreamConfig(
url="https://upstream.example/check",
service_token="shh",
service_token_header="Authorization",
)
def test_http_upstream_rejects_extra_forwarded_service_token_header_collision():
with pytest.raises(ValueError, match="service_token_header"):
HttpUpstreamConfig(
url="https://upstream.example/check",
service_token="shh",
service_token_header="X-Custom-Auth",
extra_forward_headers=("x-custom-auth",),
)
@pytest.mark.asyncio
async def test_http_upstream_uses_ca_file_for_owned_client(monkeypatch):
captured = _patch_owned_upstream_client(monkeypatch)
provider = HttpUpstreamAuthProvider(
HttpUpstreamConfig(
url="https://upstream.example/check",
timeout_seconds=2.5,
ca_file="/etc/agent-control/auth-upstream-ca/ca.crt",
)
)
await provider.aclose()
assert captured["timeout"] == 2.5
assert captured["cafile"] == "/etc/agent-control/auth-upstream-ca/ca.crt"
assert captured["verify"] is captured["ssl_context"]
assert captured["closed"] is True
@pytest.mark.asyncio
async def test_http_upstream_forwards_extra_headers():
# Given: a provider configured with an extra header in its forward list
captured: dict[str, Any] = {}
def factory(request: httpx.Request) -> httpx.Response:
captured["headers"] = dict(request.headers)
return httpx.Response(200, json={"namespace_key": "ns"})
provider = _build_upstream(
factory,
config_overrides={"extra_forward_headers": ("X-Deployer-Auth",)},
)
# When: the inbound request carries the extra header
inbound = _build_request(headers={"X-Deployer-Auth": "k_abc", "X-API-Key": "k1"})
await provider.authorize(inbound, Operation.CONTROL_BINDINGS_READ)
# Then: both the default and the extra header reach the upstream
assert captured["headers"]["x-deployer-auth"] == "k_abc"
assert captured["headers"]["x-api-key"] == "k1"
@pytest.mark.asyncio
async def test_http_upstream_default_forward_set_unchanged():
# Given: a provider with no extra_forward_headers
captured: dict[str, Any] = {}
def factory(request: httpx.Request) -> httpx.Response:
captured["headers"] = dict(request.headers)
return httpx.Response(200, json={"namespace_key": "ns"})
provider = _build_upstream(factory)
# When: the inbound carries an unlisted header alongside a default one
inbound = _build_request(
headers={"X-API-Key": "k1", "X-Deployer-Auth": "should-not-forward"}
)
await provider.authorize(inbound, Operation.CONTROL_BINDINGS_READ)
# Then: only the default-set header reaches the upstream
assert captured["headers"].get("x-api-key") == "k1"
assert "x-deployer-auth" not in captured["headers"]
@pytest.mark.asyncio
async def test_http_upstream_extra_forward_dedupes_against_defaults():
# Given: extra list duplicates a default header (different case)
captured: dict[str, Any] = {}
def factory(request: httpx.Request) -> httpx.Response:
captured["headers"] = dict(request.headers)
return httpx.Response(200, json={"namespace_key": "ns"})
provider = _build_upstream(
factory,
config_overrides={"extra_forward_headers": ("x-api-key", "Authorization")},
)
# When: inbound has both
inbound = _build_request(headers={"X-API-Key": "k1", "Authorization": "Bearer t"})
await provider.authorize(inbound, Operation.CONTROL_BINDINGS_READ)
# Then: each header appears exactly once on the upstream request
forwarded = captured["headers"]
assert sum(1 for k in forwarded if k.lower() == "x-api-key") == 1
assert sum(1 for k in forwarded if k.lower() == "authorization") == 1
@pytest.mark.asyncio
@pytest.mark.parametrize(
"status, expected",
[
(401, AuthenticationError),
(403, ForbiddenError),
(404, NotFoundError),
],
)
async def test_http_upstream_maps_client_errors(status, expected):
provider = _build_upstream(lambda req: httpx.Response(status))
with pytest.raises(expected):
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE)
@pytest.mark.asyncio
async def test_http_upstream_fails_closed_on_5xx():
provider = _build_upstream(lambda req: httpx.Response(500, text="boom"))
with pytest.raises(APIError) as exc_info:
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE)
assert exc_info.value.status_code == 503
# Status is named in the detail so operators can distinguish the
# catch-all path from the rate-limit branch below.
assert "500" in exc_info.value.detail
@pytest.mark.asyncio
@pytest.mark.parametrize("status", [400, 422])
async def test_http_upstream_unexpected_4xx_reports_upstream_rejection(status):
provider = _build_upstream(lambda req: httpx.Response(status, text="bad request"))
with pytest.raises(APIError) as exc_info:
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE)
assert exc_info.value.status_code == 502
assert exc_info.value.error_code == "AUTH_UPSTREAM_REJECTED"
assert str(status) in exc_info.value.detail
@pytest.mark.asyncio
async def test_http_upstream_surfaces_rate_limit_distinctly():
"""Upstream 429 must surface a rate-limit-specific detail and hint."""
def factory(_request: httpx.Request) -> httpx.Response:
return httpx.Response(429, headers={"Retry-After": "30"})
provider = _build_upstream(factory)
with pytest.raises(APIError) as exc_info:
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE)
assert exc_info.value.status_code == 503
assert "rate-limit" in exc_info.value.detail
assert "Retry-After: 30" in exc_info.value.hint
@pytest.mark.asyncio
async def test_http_upstream_rate_limit_without_retry_after_header():
"""Rate-limit hint omits the Retry-After clause when the header is absent."""
provider = _build_upstream(lambda req: httpx.Response(429))
with pytest.raises(APIError) as exc_info:
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE)
assert exc_info.value.status_code == 503
assert "rate-limit" in exc_info.value.detail
assert "Retry-After" not in exc_info.value.hint
@pytest.mark.asyncio
async def test_http_upstream_fails_closed_on_network_error():
def boom(_request: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("unreachable")
provider = _build_upstream(boom)
with pytest.raises(APIError) as exc_info:
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE)
assert exc_info.value.status_code == 503
@pytest.mark.asyncio
async def test_http_upstream_rejects_malformed_principal():
provider = _build_upstream(lambda req: httpx.Response(200, json={"not_namespace_key": "x"}))
with pytest.raises(APIError) as exc_info:
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE)
assert exc_info.value.status_code == 502
@pytest.mark.asyncio
async def test_http_upstream_rejects_naive_expires_at():
"""A timezone-less ISO ``expires_at`` must fail closed at the parser.
Comparing a naive datetime against ``datetime.now(UTC)`` later in
the mint path raises ``TypeError`` and surfaces as a 500, so we
reject at the boundary instead and surface a 502 alongside the rest
of the malformed-grant fail-closed path.
"""
provider = _build_upstream(
lambda req: httpx.Response(
200,
json={
"namespace_key": "ns",
"is_admin": False,
"caller_id": "user",
"expires_at": "2030-01-01T00:00:00", # no tz info
},
)
)
with pytest.raises(APIError) as exc_info:
await provider.authorize(_build_request(), Operation.CONTROL_BINDINGS_WRITE)
assert exc_info.value.status_code == 502
# ---------------------------------------------------------------------------
# require_operation factory
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_require_operation_routes_to_installed_authorizer():
seen: dict[str, Any] = {}
class _Recording:
async def authorize(self, request, operation, context=None):
seen["op"] = operation
seen["context"] = context
return Principal(namespace_key="ns", is_admin=False)
set_authorizer(_Recording())
try:
dep = require_operation(
Operation.CONTROL_BINDINGS_WRITE,
context_builder=lambda r: {"k": "v"},
)
principal = await dep(_build_request())
finally:
set_authorizer(HeaderAuthProvider())
assert seen == {
"op": Operation.CONTROL_BINDINGS_WRITE,
"context": {"k": "v"},
}
assert principal.namespace_key == "ns"
@pytest.mark.asyncio
async def test_get_authorizer_raises_when_unset():
set_authorizer(None)
try:
with pytest.raises(RuntimeError, match="No RequestAuthorizer"):
get_authorizer()
finally:
set_authorizer(HeaderAuthProvider())
# ---------------------------------------------------------------------------
# Per-operation authorizer overrides
# ---------------------------------------------------------------------------
class _StubAuthorizer:
def __init__(self, label: str) -> None:
self.label = label
self.calls: list[Operation] = []
async def authorize(self, request, operation, context=None):
self.calls.append(operation)
return Principal(namespace_key=f"ns-{self.label}")
def test_set_authorizer_with_operation_overrides_default():
clear_authorizers()
default = _StubAuthorizer("default")
runtime = _StubAuthorizer("runtime")
set_authorizer(default)
set_authorizer(runtime, operation=Operation.RUNTIME_USE)
assert get_authorizer(Operation.CONTROL_BINDINGS_WRITE) is default
assert get_authorizer(Operation.RUNTIME_USE) is runtime
def test_set_authorizer_clear_override_falls_back_to_default():
clear_authorizers()
default = _StubAuthorizer("default")
runtime = _StubAuthorizer("runtime")
set_authorizer(default)
set_authorizer(runtime, operation=Operation.RUNTIME_USE)
set_authorizer(None, operation=Operation.RUNTIME_USE)
assert get_authorizer(Operation.RUNTIME_USE) is default
@pytest.mark.asyncio
async def test_require_operation_routes_through_per_operation_override():
clear_authorizers()
default = _StubAuthorizer("default")
runtime = _StubAuthorizer("runtime")
set_authorizer(default)
set_authorizer(runtime, operation=Operation.RUNTIME_USE)
await require_operation(Operation.CONTROL_BINDINGS_READ)(_build_request())
await require_operation(Operation.RUNTIME_USE)(_build_request())
assert default.calls == [Operation.CONTROL_BINDINGS_READ]
assert runtime.calls == [Operation.RUNTIME_USE]
# ---------------------------------------------------------------------------
# Runtime token mint / verify
# ---------------------------------------------------------------------------
def test_runtime_token_round_trips():
from agent_control_server.auth_framework.runtime_token import (
mint_runtime_token,
verify_runtime_token,
)
token, claims = mint_runtime_token(
namespace_key="default",
actor_id="actor-1",
target_type="log_stream",
target_id="ls-9",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=60,
)
decoded = verify_runtime_token(token, _TEST_SECRET)
assert decoded.actor_id == claims.actor_id
assert decoded.target_type == "log_stream"
assert decoded.target_id == "ls-9"
assert decoded.scopes == ("runtime.use",)
def test_runtime_token_rejects_wrong_secret():
from agent_control_server.auth_framework.runtime_token import (
RuntimeTokenError,
mint_runtime_token,
verify_runtime_token,
)
token, _ = mint_runtime_token(
namespace_key="default",
actor_id="x",
target_type="t",
target_id="i",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=60,
)
with pytest.raises(RuntimeTokenError):
verify_runtime_token(token, _OTHER_SECRET)
def test_runtime_token_rejects_expired():
from datetime import UTC, datetime, timedelta
from agent_control_server.auth_framework.runtime_token import (
RuntimeTokenError,
mint_runtime_token,
verify_runtime_token,
)
past = datetime.now(UTC) - timedelta(hours=1)
token, _ = mint_runtime_token(
namespace_key="default",
actor_id="x",
target_type="t",
target_id="i",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=1,
now=past,
)
with pytest.raises(RuntimeTokenError, match="expired"):
verify_runtime_token(token, _TEST_SECRET)
def test_runtime_token_caps_ttl_at_upstream_grant():
from datetime import UTC, datetime, timedelta
from agent_control_server.auth_framework.runtime_token import (
mint_runtime_token,
)
now = datetime.now(UTC)
grant_expires = now + timedelta(seconds=5)
_, claims = mint_runtime_token(
namespace_key="default",
actor_id="x",
target_type="t",
target_id="i",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=3600,
upstream_expires_at=grant_expires,
now=now,
)
assert claims.expires_at == grant_expires
def test_runtime_token_rejects_already_expired_upstream_grant():
"""``upstream_expires_at <= issued_at`` must raise instead of minting.
Otherwise the exchange endpoint returns a 200 with an ``exp`` in the
past, handing the caller a token that's dead on arrival.
"""
from datetime import UTC, datetime, timedelta
from agent_control_server.auth_framework.runtime_token import (
UpstreamGrantExpiredError,
mint_runtime_token,
)
now = datetime.now(UTC)
expired = now - timedelta(seconds=1)
with pytest.raises(UpstreamGrantExpiredError):
mint_runtime_token(
namespace_key="default",
actor_id="x",
target_type="t",
target_id="i",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=3600,
upstream_expires_at=expired,
now=now,
)
def test_runtime_token_rejects_grant_expiring_at_issue_time():
"""``upstream_expires_at == issued_at`` is also unusable: zero TTL."""
from datetime import UTC, datetime
from agent_control_server.auth_framework.runtime_token import (
UpstreamGrantExpiredError,
mint_runtime_token,
)
now = datetime.now(UTC)
with pytest.raises(UpstreamGrantExpiredError):
mint_runtime_token(
namespace_key="default",
actor_id="x",
target_type="t",
target_id="i",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=3600,
upstream_expires_at=now,
now=now,
)
def test_runtime_token_rejects_naive_upstream_expires_at():
"""Naive datetimes raise ``RuntimeTokenError``, not ``TypeError``.
The HTTP-upstream parser already rejects naive ``expires_at``
fields, but the helper has other call sites (custom authorizers,
tests) that can still pass one. The comparison against
``datetime.now(UTC)`` would otherwise raise a raw ``TypeError`` and
surface as a 500 instead of a typed authorization error.
"""
from datetime import datetime
from agent_control_server.auth_framework.runtime_token import (
RuntimeTokenError,
mint_runtime_token,
)
naive = datetime(2026, 1, 1, 12, 0, 0) # no tzinfo
with pytest.raises(RuntimeTokenError, match="timezone-aware"):
mint_runtime_token(
namespace_key="default",
actor_id="x",
target_type="t",
target_id="i",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=3600,
upstream_expires_at=naive,
)
@pytest.mark.parametrize(
"kwargs, message",
[
({"actor_id": ""}, "actor_id is required"),
({"target_type": ""}, "target_type is required"),
({"target_id": ""}, "target_id is required"),
],
)
def test_runtime_token_rejects_empty_required_claims(kwargs, message):
from agent_control_server.auth_framework.runtime_token import (
RuntimeTokenError,
mint_runtime_token,
)
token_kwargs = {
"namespace_key": "default",
"actor_id": "actor",
"target_type": "target",
"target_id": "target-id",
"scopes": ("runtime.use",),
"secret": _TEST_SECRET,
"ttl_seconds": 60,
}
token_kwargs.update(kwargs)
with pytest.raises(RuntimeTokenError, match=message):
mint_runtime_token(**token_kwargs)
def test_runtime_token_rejects_management_token_passed_to_runtime_verify():
"""A token without ``domain=runtime`` must be rejected by runtime verify."""
import jwt
from agent_control_server.auth_framework.runtime_token import (
RuntimeTokenError,
verify_runtime_token,
)
bad = jwt.encode(
{
"iss": "agent-control/server",
"domain": "management",
"iat": 0,
"exp": 9_999_999_999,
},
_TEST_SECRET,
algorithm="HS256",
)
with pytest.raises(RuntimeTokenError, match="not a runtime token"):
verify_runtime_token(bad, _TEST_SECRET)
# ---------------------------------------------------------------------------
# LocalJwtVerifyProvider
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_local_jwt_provider_returns_target_bound_principal():
from agent_control_server.auth_framework.providers import LocalJwtVerifyProvider
from agent_control_server.auth_framework.runtime_token import (
mint_runtime_token,
)
token, _ = mint_runtime_token(
namespace_key="default",
actor_id="actor-7",
target_type="log_stream",
target_id="ls-42",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=60,
)
provider = LocalJwtVerifyProvider(secret=_TEST_SECRET)
request = _build_request(headers={"Authorization": f"Bearer {token}"})
principal = await provider.authorize(
request,
Operation.RUNTIME_USE,
context={"target_type": "log_stream", "target_id": "ls-42"},
)
assert principal.target_type == "log_stream"
assert principal.target_id == "ls-42"
assert principal.caller_id == "actor-7"
assert principal.scopes == ("runtime.use",)
@pytest.mark.asyncio
async def test_local_jwt_provider_missing_token_raises_401():
from agent_control_server.auth_framework.providers import LocalJwtVerifyProvider
from agent_control_server.errors import AuthenticationError
provider = LocalJwtVerifyProvider(secret=_TEST_SECRET)
with pytest.raises(AuthenticationError):
await provider.authorize(_build_request(), Operation.RUNTIME_USE)
@pytest.mark.asyncio
async def test_local_jwt_provider_wrong_scope_raises_403():
from agent_control_server.auth_framework.providers import LocalJwtVerifyProvider
from agent_control_server.auth_framework.runtime_token import (
mint_runtime_token,
)
from agent_control_server.errors import ForbiddenError
token, _ = mint_runtime_token(
namespace_key="default",
actor_id="x",
target_type="t",
target_id="i",
scopes=("runtime.read_only",),
secret=_TEST_SECRET,
ttl_seconds=60,
)
provider = LocalJwtVerifyProvider(secret=_TEST_SECRET)
request = _build_request(headers={"Authorization": f"Bearer {token}"})
with pytest.raises(ForbiddenError):
await provider.authorize(request, Operation.RUNTIME_USE)
@pytest.mark.asyncio
async def test_local_jwt_provider_rejects_non_bearer_authorization():
from agent_control_server.auth_framework.providers import LocalJwtVerifyProvider
from agent_control_server.errors import AuthenticationError
provider = LocalJwtVerifyProvider(secret=_TEST_SECRET)
request = _build_request(headers={"Authorization": "Basic abc"})
with pytest.raises(AuthenticationError):
await provider.authorize(request, Operation.RUNTIME_USE)
@pytest.mark.asyncio
async def test_local_jwt_provider_carries_token_namespace_to_principal():
"""Tokens minted in a non-default namespace must verify under that namespace."""
from agent_control_server.auth_framework.providers import LocalJwtVerifyProvider
from agent_control_server.auth_framework.runtime_token import (
mint_runtime_token,
)
token, _ = mint_runtime_token(
namespace_key="org-7",
actor_id="a",
target_type="log_stream",
target_id="ls",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=60,
)
provider = LocalJwtVerifyProvider(secret=_TEST_SECRET)
request = _build_request(headers={"Authorization": f"Bearer {token}"})
principal = await provider.authorize(
request,
Operation.RUNTIME_USE,
context={"target_type": "log_stream", "target_id": "ls"},
)
assert principal.namespace_key == "org-7"
@pytest.mark.asyncio
async def test_local_jwt_provider_rejects_missing_target_context():
"""A target-bound runtime token requires matching request target context."""
from agent_control_server.auth_framework.providers import LocalJwtVerifyProvider
from agent_control_server.auth_framework.runtime_token import (
mint_runtime_token,
)
from agent_control_server.errors import ForbiddenError
token, _ = mint_runtime_token(
namespace_key="default",
actor_id="a",
target_type="log_stream",
target_id="bound-target",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=60,
)
provider = LocalJwtVerifyProvider(secret=_TEST_SECRET)
request = _build_request(headers={"Authorization": f"Bearer {token}"})
with pytest.raises(ForbiddenError, match="target_type does not match"):
await provider.authorize(request, Operation.RUNTIME_USE)
@pytest.mark.asyncio
async def test_local_jwt_provider_enforces_target_context_match():
"""When the dependency surfaces a target context, the provider enforces it."""
from agent_control_server.auth_framework.providers import LocalJwtVerifyProvider
from agent_control_server.auth_framework.runtime_token import (
mint_runtime_token,
)
from agent_control_server.errors import ForbiddenError
token, _ = mint_runtime_token(
namespace_key="default",
actor_id="a",
target_type="log_stream",
target_id="bound-target",
scopes=("runtime.use",),
secret=_TEST_SECRET,
ttl_seconds=60,
)
provider = LocalJwtVerifyProvider(secret=_TEST_SECRET)
request = _build_request(headers={"Authorization": f"Bearer {token}"})
with pytest.raises(ForbiddenError, match="target_id does not match"):
await provider.authorize(
request,
Operation.RUNTIME_USE,
context={
"target_type": "log_stream",