Skip to content

The agent that grows with you

fix(agent): refuse ambient credential chains for multiplex profiles

beardthelion6087b40932b8
diff --git a/agent/azure_identity_adapter.py b/agent/azure_identity_adapter.py
index 7df2b13575b..8d95a2aff0f 100644
--- a/agent/azure_identity_adapter.py
+++ b/agent/azure_identity_adapter.py
@@ -11,6 +11,7 @@ Reference: https://learn.microsoft.com/azure/ai-foundry/foundry-models/how-to/co
from __future__ import annotations
+import contextvars
import functools
import logging
import os
@@ -104,13 +105,24 @@ def _default_chain_credential(config: EntraIdentityConfig) -> Any:
# Routed multiplex profiles: (home key, config) -> credential. DefaultAzureCredential reads AZURE_* from the
# process env, which under an override belongs to the LAUNCH profile, so a served profile's service principal
-# is built explicitly from its own secret scope (client secret first, then workload identity), falling back
-# to the default chain only when the profile sets no AZURE_* of its own.
+# is built explicitly from its own secret scope (client secret first, then workload identity). Under multiplex
+# the ambient default chain is refused outright when the profile sets no credential of its own: every source it
+# could mint from (env SP, CLI/azd/PowerShell caches, host managed identity) is the launch context's identity,
+# and _inject_bearer would ship it to whatever base_url the served profile configured.
_credentials_by_home: Dict[tuple, Any] = {}
+_AMBIENT_CHAIN_REFUSAL = (
+ "Entra ID auth is refused for this profile: it sets no AZURE_* credential of its own, and under "
+ "multiplexed profiles the ambient DefaultAzureCredential chain (process env, az CLI caches, host "
+ "managed identity) mints the LAUNCH profile's identity, which would be sent to this profile's "
+ "base_url. Set AZURE_TENANT_ID + AZURE_CLIENT_ID + AZURE_CLIENT_SECRET or "
+ "AZURE_FEDERATED_TOKEN_FILE in this profile's own config; AZURE_CLIENT_ID alone selects the "
+ "host's user-assigned managed identity."
+)
+
def _scoped_credential(ai: Any, config: EntraIdentityConfig) -> Any:
- from agent.secret_scope import current_secret_scope
+ from agent.secret_scope import current_secret_scope, is_multiplex_active
scope = current_secret_scope() or {}
read = lambda name: (scope.get(name) or "").strip() # noqa: E731
tenant, client = read("AZURE_TENANT_ID"), read("AZURE_CLIENT_ID")
@@ -118,6 +130,12 @@ def _scoped_credential(ai: Any, config: EntraIdentityConfig) -> Any:
return ai.ClientSecretCredential(tenant, client, read("AZURE_CLIENT_SECRET"))
if tenant and client and read("AZURE_FEDERATED_TOKEN_FILE"):
return ai.WorkloadIdentityCredential(tenant_id=tenant, client_id=client, token_file_path=read("AZURE_FEDERATED_TOKEN_FILE"))
+ if client and not tenant and not read("AZURE_CLIENT_SECRET") and not read("AZURE_FEDERATED_TOKEN_FILE"):
+ # AZURE_CLIENT_ID alone names a user-assigned managed identity: an explicit
+ # per-profile choice, not an ambient borrow (same as the SDK's env-driven MI).
+ return ai.ManagedIdentityCredential(client_id=client)
+ if is_multiplex_active():
+ raise RuntimeError(_AMBIENT_CHAIN_REFUSAL)
kwargs = {} if config.exclude_interactive_browser else {"exclude_interactive_browser_credential": False}
return ai.DefaultAzureCredential(**kwargs)
@@ -167,6 +185,7 @@ def build_token_provider(scope: Optional[str] = None, *, config: Optional[EntraI
def _probe_token(config: EntraIdentityConfig, timeout_seconds: float) -> Optional[Dict[str, Any]]:
"""``get_token`` on a daemon thread under a hard deadline → ``{"token"}`` / ``{"error"}`` / None on timeout."""
result: Dict[str, Any] = {}
+ ctx = contextvars.copy_context()
def _probe() -> None:
try:
@@ -174,7 +193,9 @@ def _probe_token(config: EntraIdentityConfig, timeout_seconds: float) -> Optiona
except Exception as exc:
result["error"] = str(exc)
- thread = threading.Thread(target=_probe, daemon=True)
+ # A bare Thread drops contextvars, so the probe would run UNSCOPED under
+ # multiplexing — minting the launch profile's chain and hiding the refusal.
+ thread = threading.Thread(target=lambda: ctx.run(_probe), daemon=True)
thread.start()
thread.join(timeout=max(0.01, timeout_seconds))
return None if thread.is_alive() else result
@@ -218,7 +239,7 @@ def _scoped_env(name: str) -> str:
_ENV_SOURCE_CHECKS = (
("WorkloadIdentityCredential (AZURE_FEDERATED_TOKEN_FILE)", lambda: _scoped_env("AZURE_FEDERATED_TOKEN_FILE")),
("EnvironmentCredential (client secret)",
- lambda: _env("AZURE_CLIENT_ID") and _scoped_env("AZURE_CLIENT_SECRET") and _env("AZURE_TENANT_ID")),
+ lambda: _scoped_env("AZURE_CLIENT_ID") and _scoped_env("AZURE_CLIENT_SECRET") and _scoped_env("AZURE_TENANT_ID")),
("ManagedIdentityCredential (IDENTITY_ENDPOINT)", lambda: _env("IDENTITY_ENDPOINT") or _env("MSI_ENDPOINT")),
)
@@ -236,7 +257,7 @@ def describe_active_credential(config: Optional[EntraIdentityConfig] = None, *,
return info
config = _resolve_config(config, scope, **overrides)
info["scope"] = config.scope
- if tenant := _env("AZURE_TENANT_ID"):
+ if tenant := _scoped_env("AZURE_TENANT_ID"):
info["tenant_id_env"] = tenant
info["env_sources"] = [label for label, present in _ENV_SOURCE_CHECKS if present()]
result = _probe_token(config, timeout_seconds)
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.py
index 017af30c3ab..232e8616a6d 100644
--- a/agent/bedrock_adapter.py
+++ b/agent/bedrock_adapter.py
@@ -53,13 +53,34 @@ def scoped_aws_session_kwargs() -> Dict[str, str]:
Under a HERMES_HOME override the process env holds the LAUNCH profile's ``AWS_*`` (or nothing), so
every Bedrock client for a served profile must be built from that profile's own ``.env`` values.
- """
+ Under multiplexing a profile that sets none of its own must NOT get ``{}`` — ``boto3.Session()``
+ would then resolve the ambient default chain (process env, ~/.aws, instance metadata), i.e. the
+ launch context's identity, exactly the borrow the Entra adapter refuses. ``AWS_PROFILE`` counts as
+ an explicit per-profile choice (it names an entry in the shared AWS config, like the Entra
+ ``AZURE_CLIENT_ID``-only managed-identity opt-in)."""
from hermes_constants import get_hermes_home_override
if get_hermes_home_override() is None:
return {}
- from agent.secret_scope import current_secret_scope
+ from agent.secret_scope import current_secret_scope, is_multiplex_active
scope = current_secret_scope() or {}
- return {kw: scope[var].strip() for kw, var in _AWS_SCOPED_CREDENTIAL_VARS if (scope.get(var) or "").strip()}
+ kwargs = {kw: scope[var].strip() for kw, var in _AWS_SCOPED_CREDENTIAL_VARS
+ if (scope.get(var) or "").strip()}
+ # Under multiplexing a partial set is not enough: boto3 fills whatever is missing from the
+ # ambient chain (process env, ~/.aws, instance metadata), i.e. the launch context's identity —
+ # the same borrow the Entra adapter refuses. Require a COMPLETE credential: the key pair, or
+ # AWS_PROFILE naming an entry in the shared AWS config (an explicit per-profile choice, like
+ # the Entra AZURE_CLIENT_ID-only managed-identity opt-in).
+ complete = ("aws_access_key_id" in kwargs and "aws_secret_access_key" in kwargs) \
+ or "profile_name" in kwargs
+ if not complete and is_multiplex_active():
+ raise RuntimeError(
+ "Bedrock auth is refused for this profile: it sets no complete AWS credential of its "
+ "own, and under multiplexed profiles the ambient default chain (process env, ~/.aws, "
+ "instance metadata) would sign this profile's calls with the LAUNCH context's identity. "
+ "Set AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY in this profile's own config, or "
+ "AWS_PROFILE to name a shared AWS config profile."
+ )
+ return kwargs
# Bedrock-hosted GPT-5.x models are served from the Bedrock Mantle OpenAI-compatible endpoint, not
# Converse. Narrow allowlist so GPT-OSS models stay on the native path.
@@ -108,8 +129,10 @@ def _cached_client(cache: Dict[str, Any], service: str, region: str):
key = (hermes_home_key(), service, region)
client = _bedrock_clients_by_home.get(key)
if client is None:
- boto3 = _require_boto3()
- client = boto3.Session(**scoped_aws_session_kwargs()).client(service, region_name=region)
+ # Scope check first: a cred-less multiplex profile must hit the ambient-chain
+ # refusal, not a boto3 ImportError on hosts that lack the package.
+ kwargs = scoped_aws_session_kwargs()
+ client = _require_boto3().Session(**kwargs).client(service, region_name=region)
_bedrock_clients_by_home[key] = client
return client
@@ -178,9 +201,17 @@ def is_bedrock_openai_base_url(base_url: str) -> bool:
def resolve_bedrock_bearer_token(env: Optional[Dict[str, str]] = None) -> str:
- """Return AWS_BEARER_TOKEN_BEDROCK when Bedrock API-key auth is configured."""
- env = env if env is not None else os.environ
- return (env.get("AWS_BEARER_TOKEN_BEDROCK", "") or "").strip()
+ """Return AWS_BEARER_TOKEN_BEDROCK when Bedrock API-key auth is configured.
+
+ Under a HERMES_HOME override the read goes through the profile secret scope so a
+ served profile never inherits the launch profile's bearer from the process env."""
+ if env is not None:
+ return (env.get("AWS_BEARER_TOKEN_BEDROCK", "") or "").strip()
+ from hermes_constants import get_hermes_home_override
+ if get_hermes_home_override() is not None:
+ from agent.secret_scope import get_secret
+ return (get_secret("AWS_BEARER_TOKEN_BEDROCK", "") or "").strip()
+ return (os.environ.get("AWS_BEARER_TOKEN_BEDROCK", "") or "").strip()
class BedrockOpenAISigV4Auth(httpx.Auth):
@@ -195,7 +226,8 @@ class BedrockOpenAISigV4Auth(httpx.Auth):
def auth_flow(self, request): # pragma: no cover - exercised by live call
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
- credentials = _require_boto3().Session(**scoped_aws_session_kwargs()).get_credentials()
+ kwargs = scoped_aws_session_kwargs()
+ credentials = _require_boto3().Session(**kwargs).get_credentials()
if credentials is None:
raise RuntimeError(
"No AWS credentials available for Bedrock OpenAI Responses. "
diff --git a/tests/agent/test_azure_identity_adapter.py b/tests/agent/test_azure_identity_adapter.py
index 0ff9d7c7b07..7d5cfed0892 100644
--- a/tests/agent/test_azure_identity_adapter.py
+++ b/tests/agent/test_azure_identity_adapter.py
@@ -251,6 +251,7 @@ class _FakeAzureIdentity:
self.last_credential_kwargs = None
self.last_scope = None
self.credential_count = 0
+ self.scoped_calls = []
def DefaultAzureCredential(self, **kwargs): # noqa: N802 — match SDK
self.last_credential_kwargs = kwargs
@@ -260,6 +261,18 @@ class _FakeAzureIdentity:
kwargs=kwargs,
)
+ def ClientSecretCredential(self, tenant_id, client_id, client_secret): # noqa: N802
+ self.scoped_calls.append(("client_secret", tenant_id, client_id, client_secret))
+ return SimpleNamespace(kind="client_secret", tenant_id=tenant_id, client_id=client_id)
+
+ def WorkloadIdentityCredential(self, **kwargs): # noqa: N802
+ self.scoped_calls.append(("workload_identity", kwargs))
+ return SimpleNamespace(kind="workload_identity", kwargs=kwargs)
+
+ def ManagedIdentityCredential(self, **kwargs): # noqa: N802
+ self.scoped_calls.append(("managed_identity", kwargs))
+ return SimpleNamespace(kind="managed_identity", kwargs=kwargs)
+
def get_bearer_token_provider(self, credential, scope):
self.last_scope = scope
# Return a callable that mints a token when invoked.
@@ -274,6 +287,9 @@ def fake_azure_identity(monkeypatch):
fake_module = SimpleNamespace(
DefaultAzureCredential=fake.DefaultAzureCredential,
+ ClientSecretCredential=fake.ClientSecretCredential,
+ WorkloadIdentityCredential=fake.WorkloadIdentityCredential,
+ ManagedIdentityCredential=fake.ManagedIdentityCredential,
get_bearer_token_provider=fake.get_bearer_token_provider,
)
monkeypatch.setitem(sys.modules, "azure", SimpleNamespace(identity=fake_module))
@@ -320,6 +336,161 @@ class TestBuildCredential:
assert fake_azure_identity.credential_count == 2
+class TestScopedCredential:
+ """Multiplex isolation: a routed profile must never mint the launch
+ profile's ambient credential chain (vertex_adapter refuses the same
+ pattern for GOOGLE_APPLICATION_CREDENTIALS)."""
+
+ @pytest.fixture
+ def routed_home(self, tmp_path):
+ """Install a HERMES_HOME override so build_credential takes the scoped path."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ token = set_hermes_home_override(str(tmp_path / "profile_home"))
+ yield
+ reset_hermes_home_override(token)
+
+ @pytest.fixture
+ def multiplex(self):
+ from agent import secret_scope
+ secret_scope.set_multiplex_active(True)
+ yield secret_scope
+ secret_scope.set_multiplex_active(False)
+
+ @pytest.fixture
+ def scoped(self, multiplex, request):
+ """Install a secret scope for the duration of a test."""
+ def _set(secrets):
+ token = multiplex.set_secret_scope(secrets)
+ request.addfinalizer(lambda: multiplex.reset_secret_scope(token))
+ return _set
+
+ def test_multiplex_refuses_ambient_chain(
+ self, fake_azure_identity, routed_home, multiplex, monkeypatch, scoped,
+ ):
+ """The finding: scope has no AZURE_* of its own but the process env
+ carries the launch profile's service principal. The served profile
+ must not mint it."""
+ from agent.azure_identity_adapter import EntraIdentityConfig, build_credential
+ monkeypatch.setenv("AZURE_TENANT_ID", "launch-tenant")
+ monkeypatch.setenv("AZURE_CLIENT_ID", "launch-client")
+ monkeypatch.setenv("AZURE_CLIENT_SECRET", "launch-secret")
+ scoped({})
+ with pytest.raises(RuntimeError, match="ambient DefaultAzureCredential"):
+ build_credential(EntraIdentityConfig())
+ assert fake_azure_identity.credential_count == 0
+ assert fake_azure_identity.scoped_calls == []
+
+ def test_multiplex_unscoped_refuses_too(
+ self, fake_azure_identity, routed_home, multiplex,
+ ):
+ """No secret scope installed at all still refuses (fail closed)."""
+ from agent.azure_identity_adapter import EntraIdentityConfig, build_credential
+ with pytest.raises(RuntimeError, match="ambient DefaultAzureCredential"):
+ build_credential(EntraIdentityConfig())
+
+ def test_multiplex_scope_builds_client_secret(
+ self, fake_azure_identity, routed_home, multiplex, scoped,
+ ):
+ from agent.azure_identity_adapter import EntraIdentityConfig, build_credential
+ scoped({
+ "AZURE_TENANT_ID": "t", "AZURE_CLIENT_ID": "c", "AZURE_CLIENT_SECRET": "s",
+ })
+ cred = build_credential(EntraIdentityConfig())
+ assert cred.kind == "client_secret"
+ assert fake_azure_identity.scoped_calls == [("client_secret", "t", "c", "s")]
+ assert fake_azure_identity.credential_count == 0
+
+ def test_multiplex_scope_builds_workload_identity(
+ self, fake_azure_identity, routed_home, multiplex, scoped,
+ ):
+ from agent.azure_identity_adapter import EntraIdentityConfig, build_credential
+ scoped({
+ "AZURE_TENANT_ID": "t", "AZURE_CLIENT_ID": "c",
+ "AZURE_FEDERATED_TOKEN_FILE": "/var/run/secrets/token",
+ })
+ cred = build_credential(EntraIdentityConfig())
+ assert cred.kind == "workload_identity"
+ assert fake_azure_identity.scoped_calls == [
+ ("workload_identity", {"tenant_id": "t", "client_id": "c",
+ "token_file_path": "/var/run/secrets/token"})]
+
+ def test_client_id_alone_routes_to_managed_identity(
+ self, fake_azure_identity, routed_home, multiplex, scoped,
+ ):
+ """Explicit per-profile opt-in to the host's user-assigned managed identity."""
+ from agent.azure_identity_adapter import EntraIdentityConfig, build_credential
+ scoped({"AZURE_CLIENT_ID": "user-assigned-id"})
+ cred = build_credential(EntraIdentityConfig())
+ assert cred.kind == "managed_identity"
+ assert fake_azure_identity.scoped_calls == [
+ ("managed_identity", {"client_id": "user-assigned-id"})]
+ assert fake_azure_identity.credential_count == 0
+
+ def test_non_multiplex_override_keeps_default_chain(
+ self, fake_azure_identity, routed_home, monkeypatch,
+ ):
+ """A single-profile override run (hermes -p beta) legitimately inherits
+ the process env: the refusal only applies while multiplexing."""
+ from agent.azure_identity_adapter import EntraIdentityConfig, build_credential
+ cred = build_credential(EntraIdentityConfig())
+ assert cred is not None
+ assert fake_azure_identity.credential_count == 1
+
+ def test_e2e_token_provider_refuses_under_multiplex(
+ self, fake_azure_identity, routed_home, multiplex, scoped,
+ ):
+ """The real consumer chain: build_token_provider -> build_credential ->
+ _scoped_credential. A cred-less served profile fails at construction."""
+ from agent.azure_identity_adapter import build_token_provider
+ scoped({})
+ with pytest.raises(RuntimeError, match="ambient DefaultAzureCredential"):
+ build_token_provider()
+
+ def test_e2e_token_provider_mints_scoped_identity(
+ self, fake_azure_identity, routed_home, multiplex, scoped,
+ ):
+ """A profile with its own SP gets a working provider minting via its
+ scope, never the process env."""
+ from agent.azure_identity_adapter import build_token_provider, materialize_bearer_for_http
+ scoped({"AZURE_TENANT_ID": "t", "AZURE_CLIENT_ID": "c", "AZURE_CLIENT_SECRET": "s"})
+ provider = build_token_provider()
+ assert materialize_bearer_for_http(provider).startswith("jwt-for-")
+ assert fake_azure_identity.scoped_calls == [("client_secret", "t", "c", "s")]
+
+ def test_e2e_per_home_cache_isolation(
+ self, fake_azure_identity, multiplex, scoped, tmp_path,
+ ):
+ """Two routed homes, one process: A's scoped credential is cached under
+ A's home key and never served to cred-less B."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from agent.azure_identity_adapter import EntraIdentityConfig, build_credential
+ tok_a = set_hermes_home_override(str(tmp_path / "home_a"))
+ try:
+ scoped({"AZURE_TENANT_ID": "t", "AZURE_CLIENT_ID": "c", "AZURE_CLIENT_SECRET": "s"})
+ cred_a = build_credential(EntraIdentityConfig())
+ assert cred_a.kind == "client_secret"
+ finally:
+ reset_hermes_home_override(tok_a)
+ tok_b = set_hermes_home_override(str(tmp_path / "home_b"))
+ try:
+ scoped({})
+ with pytest.raises(RuntimeError, match="ambient DefaultAzureCredential"):
+ build_credential(EntraIdentityConfig())
+ finally:
+ reset_hermes_home_override(tok_b)
+
+ def test_probe_surfaces_refusal_as_error(
+ self, fake_azure_identity, routed_home, multiplex, scoped,
+ ):
+ """Doctor/probe path must not raise: the refusal lands in the error field."""
+ from agent.azure_identity_adapter import describe_active_credential, has_azure_identity_credentials
+ scoped({})
+ assert has_azure_identity_credentials() is False
+ info = describe_active_credential()
+ assert info["ok"] is False
+ assert "ambient DefaultAzureCredential" in info["error"]
+
+
class TestBuildTokenProvider:
def test_returns_callable_for_scope(self, fake_azure_identity):
diff --git a/tests/agent/test_bedrock_adapter.py b/tests/agent/test_bedrock_adapter.py
index d2a558b307b..f34341a7ad2 100644
--- a/tests/agent/test_bedrock_adapter.py
+++ b/tests/agent/test_bedrock_adapter.py
@@ -123,6 +123,120 @@ class TestHasAwsCredentials:
assert has_aws_credentials({}) is False
+class TestScopedAwsSessionKwargs:
+ """Multiplex isolation: a routed profile must not mint the launch context's
+ ambient AWS chain (same refusal the Entra adapter applies to
+ DefaultAzureCredential)."""
+
+ @pytest.fixture
+ def routed_home(self, tmp_path):
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ token = set_hermes_home_override(str(tmp_path / "profile_home"))
+ yield
+ reset_hermes_home_override(token)
+
+ @pytest.fixture
+ def multiplex(self):
+ from agent import secret_scope
+ secret_scope.set_multiplex_active(True)
+ yield secret_scope
+ secret_scope.set_multiplex_active(False)
+
+ @pytest.fixture
+ def scoped(self, multiplex, request):
+ def _set(secrets):
+ token = multiplex.set_secret_scope(secrets)
+ request.addfinalizer(lambda: multiplex.reset_secret_scope(token))
+ return _set
+
+ def test_multiplex_refuses_ambient_chain(
+ self, routed_home, multiplex, scoped, monkeypatch,
+ ):
+ """Scope has no AWS_* of its own but the process env carries the launch
+ profile's keys: Session({}) would silently sign with them."""
+ from agent.bedrock_adapter import scoped_aws_session_kwargs
+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "launch-key")
+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "launch-secret")
+ scoped({})
+ with pytest.raises(RuntimeError, match="ambient default chain"):
+ scoped_aws_session_kwargs()
+
+ def test_multiplex_unscoped_refuses_too(self, routed_home, multiplex):
+ from agent.bedrock_adapter import scoped_aws_session_kwargs
+ with pytest.raises(RuntimeError, match="ambient default chain"):
+ scoped_aws_session_kwargs()
+
+ def test_multiplex_partial_set_refused(self, routed_home, multiplex, scoped):
+ """A lone session token still leaves boto3 to fill key/secret from the
+ ambient chain, so an incomplete set refuses too."""
+ from agent.bedrock_adapter import scoped_aws_session_kwargs
+ scoped({"AWS_SESSION_TOKEN": "only-token"})
+ with pytest.raises(RuntimeError, match="ambient default chain"):
+ scoped_aws_session_kwargs()
+
+ def test_multiplex_complete_key_pair_passes(self, routed_home, multiplex, scoped):
+ from agent.bedrock_adapter import scoped_aws_session_kwargs
+ scoped({"AWS_ACCESS_KEY_ID": "k", "AWS_SECRET_ACCESS_KEY": "s"})
+ assert scoped_aws_session_kwargs() == {
+ "aws_access_key_id": "k", "aws_secret_access_key": "s"}
+
+ def test_multiplex_aws_profile_is_explicit_optin(self, routed_home, multiplex, scoped):
+ from agent.bedrock_adapter import scoped_aws_session_kwargs
+ scoped({"AWS_PROFILE": "named"})
+ assert scoped_aws_session_kwargs() == {"profile_name": "named"}
+
+ def test_non_multiplex_override_keeps_ambient(self, routed_home):
+ """Single-profile override run: the process env is the operator's own."""
+ from agent.bedrock_adapter import scoped_aws_session_kwargs
+ assert scoped_aws_session_kwargs() == {}
+
+ def test_bearer_token_reads_scope_under_multiplex(
+ self, routed_home, multiplex, scoped, monkeypatch,
+ ):
+ """The launch profile's AWS_BEARER_TOKEN_BEDROCK must not leak to a served
+ profile whose scope does not define it."""
+ from agent.bedrock_adapter import resolve_bedrock_bearer_token
+ monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "launch-token")
+ scoped({})
+ assert resolve_bedrock_bearer_token() == ""
+ scoped({"AWS_BEARER_TOKEN_BEDROCK": "own-token"})
+ assert resolve_bedrock_bearer_token() == "own-token"
+
+ def test_e2e_cached_client_refuses_before_session(
+ self, routed_home, multiplex, scoped, monkeypatch,
+ ):
+ """The real consumer path: _cached_client must refuse BEFORE constructing
+ boto3.Session, so no ambient chain is ever consulted."""
+ import agent.bedrock_adapter as ba
+ session = MagicMock()
+ fake_boto3 = MagicMock()
+ fake_boto3.Session = session
+ monkeypatch.setattr(ba, "_require_boto3", lambda: fake_boto3)
+ ba.reset_client_cache()
+ scoped({})
+ with pytest.raises(RuntimeError, match="ambient default chain"):
+ ba._cached_client({}, "bedrock-runtime", "us-east-1")
+ session.assert_not_called()
+ ba.reset_client_cache()
+
+ def test_e2e_cached_client_builds_scoped_session(
+ self, routed_home, multiplex, scoped, monkeypatch,
+ ):
+ """A profile with its own key pair gets a Session built from ITS scope."""
+ import agent.bedrock_adapter as ba
+ session = MagicMock()
+ fake_boto3 = MagicMock()
+ fake_boto3.Session = session
+ monkeypatch.setattr(ba, "_require_boto3", lambda: fake_boto3)
+ ba.reset_client_cache()
+ scoped({"AWS_ACCESS_KEY_ID": "k", "AWS_SECRET_ACCESS_KEY": "s"})
+ cache = {}
+ ba._cached_client(cache, "bedrock-runtime", "us-east-1")
+ session.assert_called_once_with(
+ aws_access_key_id="k", aws_secret_access_key="s")
+ ba.reset_client_cache()
+
+
class TestResolveBedrocRegion:
def test_prefers_aws_region(self):
from agent.bedrock_adapter import resolve_bedrock_region