GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — OpenShell/python/openshell/sandbox_test.py at main · NVIDIA/OpenShell Expand file tree/ Copy pathsandbox_test.pyMore file actions 3300 lines (2710 loc) · 109 KB / Copy pathsandbox_test.pyFile metadata and controls3300 lines (2710 loc) · 109 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 # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import contextlib import json import os import pickle import threading import time from concurrent import futures from copy import deepcopy from dataclasses import asdict from pathlib import Path from types import SimpleNamespace from typing import TYPE_CHECKING, Any, Never, cast import grpc import pytest from google.protobuf.struct_pb2 import Struct import openshell.sandbox as sandbox_module from openshell._proto import openshell_pb2, openshell_pb2_grpc from openshell.mutations import DeletionOutcome from openshell.sandbox import ( _OIDC_TOKEN_EXPIRY_GRACE_SECONDS, _PYTHON_CLOUDPICKLE_BOOTSTRAP, _SANDBOX_PYTHON_BIN, ClientCredentialsAuth, Page, Pager, Sandbox, SandboxClient, SandboxConditionRef, SandboxError, SandboxRef, SandboxStatusRef, SandboxTemplateClient, ServiceAuthorizationMode, ServiceExposure, TlsConfig, _atomic_replace, _BearerAuthInterceptor, _load_cluster_bearer_token, _make_cluster_bearer_provider, _normalize_bearer, _OidcRefresher, _OwnerCache, _read_oidc_token_bundle, _sandbox_ref, _validate_oauth_url, ) if TYPE_CHECKING: from collections.abc import Generator def _request_workspace(request: Any) -> str | None: scope = request.workspace_scope if scope.WhichOneof("selection") == "workspace": return cast("str", scope.workspace) return None def _request_selects_all_workspaces(request: Any) -> bool: return request.workspace_scope.WhichOneof("selection") == "all_workspaces" def _request_sandbox(request: Any) -> str: name = getattr(request, "name", "") if name: return cast("str", name) return cast("str", request.sandbox) def _client_credentials_fixture() -> dict[str, Any]: return json.loads( ( Path(__file__).parents[2] / "sdk/conformance/oauth-client-credentials.json" ).read_text() ) def test_oauth_client_credentials_conformance_fixture() -> None: fixture = _client_credentials_fixture() assert fixture["expiry"]["leeway_seconds"] == _OIDC_TOKEN_EXPIRY_GRACE_SECONDS for value in fixture["urls"]["allowed"]: assert _validate_oauth_url("issuer", value) == value for value in fixture["urls"]["rejected"]: with pytest.raises(SandboxError): _validate_oauth_url("issuer", value) def test_client_credentials_auth_exact_form_cache_and_redaction() -> None: fixture = _client_credentials_fixture() seen: list[tuple[str, bytes]] = [] def handler(request: Any) -> Any: import httpx seen.append((str(request.url), bytes(request.content))) if request.method == "GET": return httpx.Response( 200, json={ "issuer": "https://issuer.example.com/", "token_endpoint": "https://issuer.example.com/token", }, ) return httpx.Response( 200, json={ "access_token": "service-token", "expires_in": fixture["expiry"]["valid_expires_in"], }, ) import httpx auth = ClientCredentialsAuth( issuer="https://issuer.example.com", client_id="service-client", client_secret="conformance-secret", scopes=("sandbox:read", "sandbox:write"), audience="openshell-gateway", _transport=httpx.MockTransport(handler), ) assert auth() == "service-token" assert auth() == "service-token" assert len(seen) == 2 form = dict(__import__("urllib.parse").parse.parse_qsl(seen[1][1].decode())) assert form == { field: fixture["request"][field] for field in ( "grant_type", "client_id", "client_secret", "scope", "audience", ) } assert "conformance-secret" not in repr(auth) def test_client_credentials_auth_preserves_explicit_empty_scopes() -> None: import httpx form: dict[str, str] = {} def handler(request: Any) -> Any: if request.method == "GET": return httpx.Response( 200, json={ "issuer": "https://issuer.example.com", "token_endpoint": "https://issuer.example.com/token", }, ) form.update( __import__("urllib.parse").parse.parse_qsl(request.content.decode()) ) return httpx.Response(200, json={"access_token": "token", "expires_in": 120}) auth = ClientCredentialsAuth( issuer="https://issuer.example.com", client_id="client", client_secret="secret", scopes=(), _transport=httpx.MockTransport(handler), ) auth._apply_gateway_metadata({"oidc_scopes": "sandbox:read sandbox:write"}) assert auth() == "token" assert auth._scopes == () assert "scope" not in form @pytest.mark.parametrize( "expires_in", _client_credentials_fixture()["expiry"]["invalid_expires_in"] ) def test_client_credentials_auth_rejects_invalid_expiry(expires_in: object) -> None: import httpx fixture = _client_credentials_fixture() def handler(request: Any) -> Any: if request.method == "GET": return httpx.Response( 200, json={ "issuer": fixture["discovery"]["matching_issuer"], "token_endpoint": "https://issuer.example.com/token", }, ) return httpx.Response( 200, json={"access_token": "token", "expires_in": expires_in} ) auth = ClientCredentialsAuth( issuer=fixture["discovery"]["configured_issuer"], client_id="client", client_secret="secret", _transport=httpx.MockTransport(handler), ) with pytest.raises(SandboxError, match="positive finite expires_in"): auth() @pytest.mark.parametrize( "status", _client_credentials_fixture()["discovery"]["redirect_statuses"] ) def test_client_credentials_auth_refuses_discovery_redirect(status: int) -> None: import httpx requests = 0 def handler(_request: Any) -> Any: nonlocal requests requests += 1 return httpx.Response( status, headers={"location": "https://attacker.example.com/discovery"}, ) auth = ClientCredentialsAuth( issuer="https://issuer.example.com", client_id="client", client_secret="secret", _transport=httpx.MockTransport(handler), ) with pytest.raises(SandboxError, match=f"HTTP {status}"): auth() assert requests == 1 @pytest.mark.parametrize( "status", _client_credentials_fixture()["discovery"]["redirect_statuses"] ) def test_client_credentials_auth_refuses_token_redirect(status: int) -> None: import httpx requests: list[str] = [] def handler(request: Any) -> Any: requests.append(str(request.url)) if request.method == "GET": return httpx.Response( 200, json={ "issuer": "https://issuer.example.com", "token_endpoint": "https://issuer.example.com/token", }, ) return httpx.Response( status, headers={"location": "https://attacker.example.com/token"}, ) auth = ClientCredentialsAuth( issuer="https://issuer.example.com", client_id="client", client_secret="secret", _transport=httpx.MockTransport(handler), ) with pytest.raises(SandboxError, match=f"HTTP {status}"): auth() assert requests == [ "https://issuer.example.com/.well-known/openid-configuration", "https://issuer.example.com/token", ] def test_client_credentials_auth_rejects_discovery_issuer_mismatch() -> None: import httpx fixture = _client_credentials_fixture() auth = ClientCredentialsAuth( issuer=fixture["discovery"]["configured_issuer"], client_id="client", client_secret="secret", _transport=httpx.MockTransport( lambda _request: httpx.Response( 200, json={ "issuer": fixture["discovery"]["mismatched_issuer"], "token_endpoint": "https://attacker.example.com/token", }, ) ), ) with pytest.raises(SandboxError, match="issuer mismatch"): auth() def test_client_credentials_auth_rejects_oversized_response() -> None: import httpx fixture = _client_credentials_fixture() auth = ClientCredentialsAuth( issuer="https://issuer.example.com", client_id="client", client_secret="secret", _transport=httpx.MockTransport( lambda _request: httpx.Response( 200, content=b"x" * (fixture["limits"]["max_response_bytes"] + 1) ) ), ) with pytest.raises(SandboxError, match="too large"): auth() def test_client_credentials_auth_single_flight_and_retry() -> None: import httpx token_calls = 0 release = threading.Event() def handler(request: Any) -> Any: nonlocal token_calls if request.method == "GET": return httpx.Response( 200, json={ "issuer": "http://127.0.0.1:8080", "token_endpoint": "http://127.0.0.1:8080/token", }, ) token_calls += 1 release.wait(timeout=2) return httpx.Response(200, json={"access_token": "shared", "expires_in": 120}) auth = ClientCredentialsAuth( issuer="http://127.0.0.1:8080", client_id="client", client_secret="secret", _transport=httpx.MockTransport(handler), ) results: list[str] = [] threads = [ threading.Thread(target=lambda: results.append(auth())) for _ in range(8) ] for thread in threads: thread.start() while token_calls == 0: time.sleep(0.001) release.set() for thread in threads: thread.join() assert results == ["shared"] * 8 assert token_calls == 1 def test_client_credentials_auth_fails_closed_and_redacts_errors() -> None: import httpx def supplier() -> str: raise RuntimeError("supplier-sensitive-detail") auth = ClientCredentialsAuth( issuer="http://localhost:8080", client_id="client", client_secret=supplier, _transport=httpx.MockTransport( lambda _request: httpx.Response( 200, json={ "issuer": "http://localhost:8080", "token_endpoint": "http://localhost:8080/token", }, ) ), ) with pytest.raises(SandboxError, match="supplier failed") as exc_info: auth() assert "supplier-sensitive-detail" not in str(exc_info.value) with pytest.raises(SandboxError, match="must use HTTPS"): ClientCredentialsAuth( issuer="http://remote.example.com", client_id="client", client_secret="secret", )() def test_client_credentials_auth_does_not_use_stale_token_after_renewal_failure() -> ( None ): import httpx exchanges = 0 def handler(request: Any) -> Any: nonlocal exchanges if request.method == "GET": return httpx.Response( 200, json={ "issuer": "http://localhost:8080", "token_endpoint": "http://localhost:8080/token", }, ) exchanges += 1 if exchanges == 1: return httpx.Response(200, json={"access_token": "stale", "expires_in": 30}) return httpx.Response(503, json={"error": "provider-sensitive-detail"}) auth = ClientCredentialsAuth( issuer="http://localhost:8080", client_id="client", client_secret="secret", _transport=httpx.MockTransport(handler), ) assert auth() == "stale" with pytest.raises(SandboxError, match="HTTP 503") as exc_info: auth() assert "stale" not in str(exc_info.value) assert "provider-sensitive-detail" not in str(exc_info.value) class _FakeStub: class GetSandbox: @staticmethod def with_call(*_args: object, **_kwargs: object) -> Never: raise grpc.RpcError() def __init__(self) -> None: self.request: openshell_pb2.ExecSandboxRequest | None = None def ExecSandbox( self, request: openshell_pb2.ExecSandboxRequest, timeout: float | None = None, ): self.request = request _ = timeout yield openshell_pb2.ExecSandboxEvent( exit=openshell_pb2.ExecSandboxExit(exit_code=0) ) def _client_with_fake_stub(stub: object) -> SandboxClient: client = object.__new__(SandboxClient) client._timeout = 30.0 client._stub = cast("Any", stub) client._owners = _OwnerCache() return client class _RoutingGateway(openshell_pb2_grpc.OpenShellServicer): """Gateway that reports an owner and, behind a replica route, can answer like Envoy with a trailers-only UNAVAILABLE.""" def __init__( self, owner: str, *, reject_routed: str | None = None, fail: str = "" ) -> None: self.owner = owner self.reject_routed = reject_routed self.fail = fail self.wanted_owner: list[str] = [] self.routes: list[str] = [] def GetSandbox(self, request, context): _ = request headers = dict(context.invocation_metadata()) self.wanted_owner.append(headers.get("x-openshell-want-owner", "")) if self.owner: context.send_initial_metadata((("x-openshell-owner", self.owner),)) return openshell_pb2.SandboxResponse() def ExecSandbox(self, request, context): _ = request route = dict(context.invocation_metadata()).get("x-openshell-replica", "") self.routes.append(route) if route and self.reject_routed is not None: context.abort(grpc.StatusCode.UNAVAILABLE, self.reject_routed) if self.fail: context.abort(grpc.StatusCode.UNAVAILABLE, self.fail) yield openshell_pb2.ExecSandboxEvent( stdout=openshell_pb2.ExecSandboxStdout(data=b"ok") ) yield openshell_pb2.ExecSandboxEvent( exit=openshell_pb2.ExecSandboxExit(exit_code=0) ) @contextlib.contextmanager def _routing_client(gateway: _RoutingGateway) -> Generator[SandboxClient]: server = grpc.server(futures.ThreadPoolExecutor(max_workers=2)) openshell_pb2_grpc.add_OpenShellServicer_to_server(gateway, server) port = server.add_insecure_port("127.0.0.1:0") server.start() try: with SandboxClient(f"127.0.0.1:{port}", timeout=5) as client: yield client finally: server.stop(None) def test_exec_routes_to_reported_owner_and_caches_it() -> None: gateway = _RoutingGateway("openshell-1") with _routing_client(gateway) as client: for _ in range(2): result = client.exec("box", ["true"], workspace="default") assert result.stdout == "ok" assert gateway.wanted_owner == ["1"] assert gateway.routes == ["openshell-1", "openshell-1"] def test_exec_without_owner_sends_no_hint() -> None: gateway = _RoutingGateway("") with _routing_client(gateway) as client: assert client.exec("box", ["true"], workspace="default").exit_code == 0 assert gateway.routes == [""] @pytest.mark.parametrize("message", ["", "no healthy upstream"]) def test_exec_retries_once_unrouted_when_owner_route_is_empty(message: str) -> None: gateway = _RoutingGateway("openshell-1", reject_routed=message) with _routing_client(gateway) as client: for _ in range(2): result = client.exec("box", ["true"], workspace="default") assert result.stdout == "ok" assert gateway.routes == ["openshell-1", "", "openshell-1", ""] assert gateway.wanted_owner == ["1", "1"] def test_exec_does_not_retry_gateway_errors() -> None: gateway = _RoutingGateway("openshell-1", fail="supervisor not connected") with ( _routing_client(gateway) as client, pytest.raises(grpc.RpcError, match="supervisor not connected"), ): client.exec("box", ["true"], workspace="default") assert gateway.routes == ["openshell-1"] def _template_client_with_fake_stub(stub: object) -> SandboxTemplateClient: client = object.__new__(SandboxTemplateClient) client._timeout = 30.0 client._stub = cast("Any", stub) return client def test_exec_sends_stdin_payload() -> None: stub = _FakeStub() client = _client_with_fake_stub(stub) result = client.exec( "sandbox-1", ["python", "-c", "print('ok')"], workspace="default", stdin=b"payload", ) assert result.exit_code == 0 assert stub.request is not None assert stub.request.stdin == b"payload" def test_exec_python_serializes_callable_payload() -> None: stub = _FakeStub() client = _client_with_fake_stub(stub) def add(a: int, b: int) -> int: return a + b result = client.exec_python("sandbox-1", add, workspace="default", args=(2, 3)) assert result.exit_code == 0 assert stub.request is not None assert stub.request.command == [ _SANDBOX_PYTHON_BIN, "-c", _PYTHON_CLOUDPICKLE_BOOTSTRAP, ] assert stub.request.environment["OPENSHELL_PYFUNC_B64"] assert stub.request.stdin == b"" def test_from_active_cluster_reads_gateway_metadata_layout( tmp_path: Path, monkeypatch: Any, ) -> None: gateway_name = "test-gateway" gateway_dir = tmp_path / "openshell" / "gateways" / gateway_name mtls_dir = gateway_dir / "mtls" mtls_dir.mkdir(parents=True) (tmp_path / "openshell" / "active_gateway").write_text(gateway_name) (gateway_dir / "metadata.json").write_text( json.dumps({"gateway_endpoint": "https://127.0.0.1:8443"}) ) (mtls_dir / "ca.crt").write_text("ca") (mtls_dir / "tls.crt").write_text("cert") (mtls_dir / "tls.key").write_text("key") monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) monkeypatch.delenv("OPENSHELL_GATEWAY", raising=False) client = SandboxClient.from_active_cluster() try: assert client._cluster_name == gateway_name finally: client.close() def test_from_active_cluster_prefers_openshell_gateway_env( tmp_path: Path, monkeypatch: Any, ) -> None: gateway_name = "env-gateway" gateway_dir = tmp_path / "openshell" / "gateways" / gateway_name mtls_dir = gateway_dir / "mtls" mtls_dir.mkdir(parents=True) (gateway_dir / "metadata.json").write_text( json.dumps({"gateway_endpoint": "https://127.0.0.1:8443"}) ) (mtls_dir / "ca.crt").write_text("ca") (mtls_dir / "tls.crt").write_text("cert") (mtls_dir / "tls.key").write_text("key") monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) monkeypatch.setenv("OPENSHELL_GATEWAY", gateway_name) client = SandboxClient.from_active_cluster() try: assert client._cluster_name == gateway_name finally: client.close() # --------------------------------------------------------------------------- # OIDC bearer auth # --------------------------------------------------------------------------- class _FakeClientCallDetails: """grpc.ClientCallDetails is a NamedTuple in real gRPC; for unit tests we just need an object with the same field set and a ._replace shim.""" __slots__ = ("credentials", "metadata", "method", "timeout", "wait_for_ready") def __init__( self, method: str = "/Test/Method", timeout: float | None = None, metadata: Any = None, credentials: Any = None, wait_for_ready: Any = None, ) -> None: self.method = method self.timeout = timeout self.metadata = metadata self.credentials = credentials self.wait_for_ready = wait_for_ready def _replace(self, **kwargs: Any) -> _FakeClientCallDetails: return _FakeClientCallDetails( method=kwargs.get("method", self.method), timeout=kwargs.get("timeout", self.timeout), metadata=kwargs.get("metadata", self.metadata), credentials=kwargs.get("credentials", self.credentials), wait_for_ready=kwargs.get("wait_for_ready", self.wait_for_ready), ) def test_normalize_bearer_accepts_str_or_callable() -> None: assert _normalize_bearer(None) is None static = _normalize_bearer("abc") assert static is not None assert static() == "abc" counter = [0] def provider() -> str: counter[0] += 1 return f"token-{counter[0]}" dynamic = _normalize_bearer(provider) assert dynamic is not None assert dynamic() == "token-1" assert dynamic() == "token-2" def test_bearer_interceptor_attaches_authorization_header() -> None: interceptor = _BearerAuthInterceptor(lambda: "secret-token") captured: dict[str, Any] = {} def continuation(details: Any, request: Any) -> str: captured["details"] = details captured["request"] = request return "result" details = _FakeClientCallDetails(metadata=[("x-existing", "yes")]) result = interceptor.intercept_unary_unary(continuation, details, "payload") assert result == "result" md = list(captured["details"].metadata) # Pre-existing metadata preserved, authorization appended last. assert ("x-existing", "yes") in md assert ("authorization", "Bearer secret-token") in md assert captured["request"] == "payload" def test_bearer_interceptor_handles_empty_metadata() -> None: interceptor = _BearerAuthInterceptor(lambda: "t") captured: dict[str, Any] = {} def continuation(details: Any, _request: Any) -> None: captured["metadata"] = list(details.metadata) details = _FakeClientCallDetails(metadata=None) interceptor.intercept_unary_unary(continuation, details, request="x") assert captured["metadata"] == [("authorization", "Bearer t")] def test_bearer_interceptor_calls_token_provider_per_request() -> None: tokens = iter(["t1", "t2", "t3"]) interceptor = _BearerAuthInterceptor(lambda: next(tokens)) seen: list[str] = [] def continuation(details: Any, _request: Any) -> None: for key, value in details.metadata: if key == "authorization": seen.append(value) for _ in range(3): interceptor.intercept_unary_unary( continuation, _FakeClientCallDetails(), request="x" ) assert seen == ["Bearer t1", "Bearer t2", "Bearer t3"] def test_load_cluster_bearer_token_reads_oidc_token_json(tmp_path: Path) -> None: gateway_dir = tmp_path / "gw" gateway_dir.mkdir() (gateway_dir / "oidc_token.json").write_text( json.dumps( { "access_token": "jwt-blob", "refresh_token": "rt", "expires_at": 9999999999, "issuer": "https://idp.example/realms/openshell", "client_id": "openshell-cli", } ) ) assert _load_cluster_bearer_token(gateway_dir) == "jwt-blob" def test_load_cluster_bearer_token_returns_none_when_missing( tmp_path: Path, ) -> None: assert _load_cluster_bearer_token(tmp_path / "absent") is None def test_load_cluster_bearer_token_tolerates_unreadable_file( tmp_path: Path, ) -> None: gateway_dir = tmp_path / "gw" gateway_dir.mkdir() (gateway_dir / "oidc_token.json").write_text("not json") assert _load_cluster_bearer_token(gateway_dir) is None def test_load_cluster_bearer_token_rejects_missing_access_token( tmp_path: Path, ) -> None: gateway_dir = tmp_path / "gw" gateway_dir.mkdir() (gateway_dir / "oidc_token.json").write_text(json.dumps({"refresh_token": "rt"})) assert _load_cluster_bearer_token(gateway_dir) is None def _setup_gateway_dir( tmp_path: Path, monkeypatch: Any, *, name: str = "g", endpoint: str = "http://127.0.0.1:8080", auth_mode: str | None = None, mtls_files: dict[str, str] | None = None, oidc_bundle: dict | None = None, ) -> Path: gateway_dir = tmp_path / "openshell" / "gateways" / name gateway_dir.mkdir(parents=True) (tmp_path / "openshell" / "active_gateway").write_text(name) meta: dict[str, Any] = {"gateway_endpoint": endpoint} if auth_mode is not None: meta["auth_mode"] = auth_mode (gateway_dir / "metadata.json").write_text(json.dumps(meta)) if mtls_files: mtls_dir = gateway_dir / "mtls" mtls_dir.mkdir() for fname, body in mtls_files.items(): (mtls_dir / fname).write_text(body) if oidc_bundle is not None: (gateway_dir / "oidc_token.json").write_text(json.dumps(oidc_bundle)) monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) monkeypatch.delenv("OPENSHELL_GATEWAY", raising=False) return gateway_dir def _channel_is_intercepted(channel: Any) -> bool: """grpc.intercept_channel returns a _Channel whose module name ends in `interceptor`. We don't depend on the class name (it varies across gRPC versions); module is stable.""" return type(channel).__module__.endswith("interceptor") def test_from_active_cluster_loads_bearer_when_auth_mode_is_oidc( tmp_path: Path, monkeypatch: Any, ) -> None: """Finding 3: bearer is attached iff metadata.auth_mode == "oidc".""" _setup_gateway_dir( tmp_path, monkeypatch, auth_mode="oidc", oidc_bundle={"access_token": "from-disk"}, ) client = SandboxClient.from_active_cluster() try: assert _channel_is_intercepted(client._channel) finally: client.close() def test_from_active_cluster_ignores_stale_token_when_auth_mode_not_oidc( tmp_path: Path, monkeypatch: Any, ) -> None: """Finding 3: a stale oidc_token.json alongside a non-OIDC gateway must NOT cause bearer auth to be attached.""" _setup_gateway_dir( tmp_path, monkeypatch, # auth_mode omitted (or "mtls", "plaintext") — anything but "oidc". oidc_bundle={"access_token": "stale-from-disk"}, ) client = SandboxClient.from_active_cluster() try: # Plain channel, no interceptor wrapper. assert not _channel_is_intercepted(client._channel) finally: client.close() def test_from_active_cluster_https_oidc_without_mtls_uses_tls_with_system_roots( tmp_path: Path, monkeypatch: Any, ) -> None: """Finding 1: https OIDC gateways without mTLS material must still use a TLS channel (system roots) — NOT fall back to insecure_channel.""" _setup_gateway_dir( tmp_path, monkeypatch, endpoint="https://gateway.example:443", auth_mode="oidc", oidc_bundle={"access_token": "t"}, ) client = SandboxClient.from_active_cluster() try: # The bearer interceptor wraps the channel, so inspect the # wrapped channel's class to confirm it's a secure (TLS) channel. inner = getattr(client._channel, "_channel", client._channel) # gRPC's `grpc.secure_channel` returns a `_Channel` from # `grpc._channel`; we can't trivially introspect "secure" vs # "insecure" on the wrapper itself. Probe by attempting to # extract the connectivity state — both kinds expose it — and # rely on a behavioral assertion: an insecure channel against # a hostname-only endpoint would have already attached TCP-only # subchannels. Easier: verify TlsConfig() was used by checking # the SandboxClient endpoint normalized correctly. # The most direct assertion is on the client config: assert client._endpoint == "gateway.example:443" # And the channel must not be insecure. assert "InsecureChannelCredentials" not in repr(inner) finally: client.close() def test_from_active_cluster_https_ca_only_layout( tmp_path: Path, monkeypatch: Any, ) -> None: """Finding 1: a CA-only mtls directory (ca.crt but no tls.crt/tls.key) must produce a CA-only TLS channel, not a FileNotFoundError.""" _setup_gateway_dir( tmp_path, monkeypatch, endpoint="https://gateway.example:443", auth_mode="oidc", mtls_files={ "ca.crt": "-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----\n" }, oidc_bundle={"access_token": "t"}, ) # Should not raise. client = SandboxClient.from_active_cluster() try: assert client._endpoint == "gateway.example:443" finally: client.close() def test_tls_config_rejects_partial_client_identity() -> None: """Cert without key (or vice versa) is a misconfiguration.""" import pytest as _pytest with _pytest.raises(ValueError, match="cert_path and key_path"): TlsConfig(cert_path=Path("/x.crt")) def test_tls_config_allows_empty_for_system_roots() -> None: """`TlsConfig()` is the system-roots-trust flavor.""" cfg = TlsConfig() assert cfg.ca_path is None and cfg.cert_path is None and cfg.key_path is None # --------------------------------------------------------------------------- # Provider semantics: per-RPC reload + expiry # --------------------------------------------------------------------------- def test_cluster_bearer_provider_reloads_on_every_call(tmp_path: Path) -> None: """The fail-closed (no-refresh) provider re-reads oidc_token.json each invocation, so a long-lived SandboxClient picks up CLI rotations without reconstruction.""" gateway_dir = tmp_path token_file = gateway_dir / "oidc_token.json" token_file.write_text(json.dumps({"access_token": "first"})) provider, _ = _make_cluster_bearer_provider(gateway_dir, "g", auto_refresh=False) assert provider() == "first" # Simulate `openshell gateway login` writing a new token. token_file.write_text(json.dumps({"access_token": "second"})) assert provider() == "second" def test_cluster_bearer_provider_raises_on_expired_token(tmp_path: Path) -> None: """Fail-closed provider raises on expiry with a clear re-login hint.""" gateway_dir = tmp_path (gateway_dir / "oidc_token.json").write_text( json.dumps({"access_token": "expired", "expires_at": 1}) ) provider, _ = _make_cluster_bearer_provider( gateway_dir, "stale-gateway", auto_refresh=False ) import pytest as _pytest with _pytest.raises(SandboxError, match="expired"): provider() def test_cluster_bearer_provider_raises_when_file_missing(tmp_path: Path) -> None: provider, _ = _make_cluster_bearer_provider( tmp_path / "absent", "g", auto_refresh=False ) import pytest as _pytest with _pytest.raises(SandboxError, match="missing or unreadable"): provider() def test_cluster_bearer_provider_raises_on_missing_access_token( tmp_path: Path, ) -> None: (tmp_path / "oidc_token.json").write_text(json.dumps({"refresh_token": "r"})) provider, _ = _make_cluster_bearer_provider(tmp_path, "g", auto_refresh=False) import pytest as _pytest with _pytest.raises(SandboxError, match="no access token"): provider() # --------------------------------------------------------------------------- # OAuth2 native refresh (_OidcRefresher) — opt-in via auto_refresh=True. # --------------------------------------------------------------------------- def _write_bundle( gateway_dir: Path, *, access_token: str = "fresh", refresh_token: str = "r-orig", expires_at: int | None = None, issuer: str = "https://idp.example/realms/openshell", client_id: str = "openshell-cli", ) -> None: bundle: dict[str, Any] = { "access_token": access_token, |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |