Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to SkillEvaluator are documented in this file.

## Unreleased

### Security

- Update LiteLLM and the minimum AWS SDK version in the optional LLM and
Comment thread
chrisknvidia marked this conversation as resolved.
Resolved
Tier 3 installs. Bedrock preflight and host inference reject HTTP endpoint
overrides when bearer authentication is configured.

### Changed

- Claude Code log recovery pairs batched and delayed tool results without repeatedly
Expand Down Expand Up @@ -52,6 +58,12 @@ All notable changes to SkillEvaluator are documented in this file.

### Fixed

- Bedrock preflight and host inference now sign requests with IAM credentials
when `AWS_BEARER_TOKEN_BEDROCK` is empty or whitespace-only, for example when
a CI job exports an unset secret. Previously the Tier 3 preflight sent a blank
`Authorization: Bearer` header, and host inference failed with an illegal
header value. This includes models called through the Bedrock Responses
route.
- Tier 2 rubric prompts fence SKILL.md and each supplementary file preview.
The fence length exceeds any backtick run in the rendered content. File and
skill labels are escaped and length-limited. The judge is instructed to
Expand Down
9 changes: 6 additions & 3 deletions docs/tier3-runtime.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,12 @@ The exact Harbor pin is deliberate: its CLI, Python models, result artifacts,
and environment/agent subclass interfaces form one compatibility surface. This
release targets stable Harbor 0.25.0 rather than unreleased `main`. Harbor stays
behind the operator-selected `tier3` extra, so static Tier 1 installs do not pull
it in. The shared LLM client window (`litellm>=1.92.0,<1.94.0.dev0`) admits
patched 1.92 and 1.93 releases validated with this integration while excluding
prerelease and as-yet unvalidated 1.94 behavior.
it in. The shared LLM client uses `litellm>=1.110.2,<1.111.0.dev0` with
`boto3>=1.44.0`. When you set `AWS_BEARER_TOKEN_BEDROCK`, use HTTPS for the
Bedrock catalog and runtime endpoints checked by preflight and for the
endpoint overrides used by the LiteLLM client: `AWS_BEDROCK_RUNTIME_ENDPOINT`,
`BEDROCK_MANTLE_API_BASE`, `ANTHROPIC_AWS_BASE_URL`, and
`ANTHROPIC_AWS_API_BASE`.

The integration preserves SkillEvaluator's runtime and artifact contracts while
using Harbor 0.25:
Expand Down
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ dependencies = [
# Shared public LLM / embedding clients used by LLM-backed checks, Tier 2, and Tier 3.
llm = [
"anthropic>=0.83.0",
"boto3>=1.34.0",
"litellm>=1.92.0,<1.94.0.dev0",
# Botocore 1.44 introduced HTTPS enforcement for bearer authentication.
"boto3>=1.44.0",
"litellm>=1.110.2,<1.111.0.dev0",
Comment thread
chrisknvidia marked this conversation as resolved.
Resolved
"openai>=2.21.0",
]
# Tier 2 intra-skill deduplication and local-catalog inter-skill similarity.
Expand Down
98 changes: 90 additions & 8 deletions src/skillevaluator/inference/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ class supports two usage patterns:
import re
import threading
import urllib.error
from collections.abc import Callable, Mapping, Sequence
from collections.abc import Callable, Iterator, Mapping, Sequence
from contextlib import contextmanager, nullcontext
from dataclasses import replace
from typing import Any, NamedTuple
from urllib.parse import urlsplit
Expand Down Expand Up @@ -56,6 +57,7 @@ class supports two usage patterns:
anthropic_refusal_fallback_model,
completion_token_limit,
effective_reasoning_effort,
has_bedrock_bearer_token,
is_claude_5_5_or_later,
is_openai_reasoning_model,
resolve_extra_headers,
Expand All @@ -67,6 +69,69 @@ class supports two usage patterns:
_NATIVE_OPENAI_AUTHORITIES = frozenset({"api.openai.com", "api.openai.com:443"})
_NATIVE_OPENAI_PATHS = frozenset({"/v1", "/v1/"})

_BEDROCK_BEARER_TOKEN_ENV = "AWS_BEARER_TOKEN_BEDROCK"


class _BedrockTokenWindow:
"""Blank AWS_BEARER_TOKEN_BEDROCK while Bedrock calls are in flight, then restore it exactly.

LiteLLM's Bedrock Responses route picks its token as `api_key or <this variable>`, so an empty
`api_key` still falls back to a whitespace-only value and sends it as a Bearer header. LiteLLM
has no per-call setting that skips that fallback. Concurrent calls share one blanked window:
the first saves the value and the last puts it back.
"""

def __init__(self) -> None:
self._lock = threading.Lock()
self._holders = 0
self._saved: str | None = None

@contextmanager
def blank(self) -> Iterator[None]:
with self._lock:
if self._holders == 0:
self._saved = os.environ.get(_BEDROCK_BEARER_TOKEN_ENV)
os.environ[_BEDROCK_BEARER_TOKEN_ENV] = ""
self._holders += 1
try:
yield
finally:
with self._lock:
self._holders -= 1
if self._holders == 0:
if self._saved is None:
os.environ.pop(_BEDROCK_BEARER_TOKEN_ENV, None)
else:
os.environ[_BEDROCK_BEARER_TOKEN_ENV] = self._saved
self._saved = None


_bedrock_token_window = _BedrockTokenWindow()

# Endpoint overrides that LiteLLM's Bedrock routes send the bearer token to.
_BEDROCK_BEARER_ENDPOINT_VARIABLES = (
"AWS_BEDROCK_RUNTIME_ENDPOINT", # bedrock-runtime routes, such as Converse and Responses
"BEDROCK_MANTLE_API_BASE", # the mantle/ route
# The hosted-platform route sends the token only when its own API key is not set.
"ANTHROPIC_AWS_BASE_URL",
"ANTHROPIC_AWS_API_BASE",
)


def _require_https_for_bedrock_bearer_endpoints() -> None:
"""Refuse to send a Bedrock bearer token to a plain HTTP endpoint override."""
for variable in _BEDROCK_BEARER_ENDPOINT_VARIABLES:
endpoint = os.environ.get(variable)
if not endpoint:
continue
try:
target = urlsplit(endpoint)
uses_https = target.scheme == "https" and target.hostname is not None
except ValueError:
uses_https = False
if not uses_https:
raise LLMClientError(f"{variable} must use HTTPS with a Bedrock bearer token.")


def _effective_openai_base_url(explicit_base_url: str | None) -> str:
if explicit_base_url is not None:
Expand Down Expand Up @@ -792,14 +857,31 @@ def _anthropic_kwargs(include_schema: bool) -> dict[str, Any]:
raise LLMClientError(
"The 'litellm' package is required for Bedrock LLM operations. Install with: pip install 'skillevaluator[llm]'"
) from exc
response = completion(
model=config.litellm_model,
messages=_chat_messages(system_prompt, turns),
aws_region_name=config.region,
**_temperature_kwargs(config.model, self._temperature),
**({"max_tokens": max_tokens} if max_tokens is not None else {}),
**({"timeout": self._timeout} if self._timeout is not None else {}),
# LiteLLM can load environment variables on its first import.
has_bearer_token = has_bedrock_bearer_token()
if has_bearer_token:
_require_https_for_bedrock_bearer_endpoints()
# Mantle resolves its own endpoint. An explicit runtime override takes precedence in LiteLLM.
endpoint = (
os.environ.get("AWS_BEDROCK_RUNTIME_ENDPOINT")
if has_bearer_token and "/mantle/" not in f"/{config.model}"
else None
)
# LiteLLM sends a whitespace-only AWS_BEARER_TOKEN_BEDROCK as a blank Bearer header.
# An empty key makes it sign with the IAM credentials, as it does for an unset variable.
# The Responses route also reads the variable itself, so hide it for the call.
ignore_blank_token = _BEDROCK_BEARER_TOKEN_ENV in os.environ and not has_bearer_token
with _bedrock_token_window.blank() if ignore_blank_token else nullcontext():
response = completion(
model=config.litellm_model,
messages=_chat_messages(system_prompt, turns),
aws_region_name=config.region,
**({"aws_bedrock_runtime_endpoint": endpoint} if endpoint else {}),
**({"api_key": ""} if ignore_blank_token else {}),
**_temperature_kwargs(config.model, self._temperature),
**({"max_tokens": max_tokens} if max_tokens is not None else {}),
**({"timeout": self._timeout} if self._timeout is not None else {}),
)
return _extract_choice_content(response)

def _openai_kwargs(include_schema: bool) -> dict[str, Any]:
Expand Down
12 changes: 10 additions & 2 deletions src/skillevaluator/provider_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
_HEX_DIGIT_BYTES = frozenset(b"0123456789abcdefABCDEF")
_UNRESERVED_BYTES = frozenset(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
_NO_CUSTOM_TEMPERATURE_MODEL_IDS = frozenset({"claude-mythos-preview"})
_ANTHROPIC_BEDROCK_PREFIX_RE = re.compile(r"^(?:(?:[a-z]{2}|global)\.)?anthropic\.")
_BEDROCK_VENDOR_PREFIX_RE = re.compile(r"^(?:(?:[a-z]{2}|global)\.)?(?:anthropic|openai)\.")
# Gateway catalogs can put vendor words before the model name, as in
# ``aws/anthropic/bedrock-claude-opus-5-5``.
_GATEWAY_LEAF_PREFIX_RE = re.compile(r"^(?:[a-z]+-)+?(?=(?:claude|gpt)-)")
Expand Down Expand Up @@ -150,7 +150,7 @@ def _model_leaf(model: str) -> str:
"""Return a normalized model ID for capability checks only."""
leaf = str(model or "").strip().casefold().rsplit("/", 1)[-1]
leaf = _GATEWAY_LEAF_PREFIX_RE.sub("", leaf, count=1)
return _ANTHROPIC_BEDROCK_PREFIX_RE.sub("", leaf, count=1)
return _BEDROCK_VENDOR_PREFIX_RE.sub("", leaf, count=1)


def _claude_version(model: str) -> tuple[int, int] | None:
Expand Down Expand Up @@ -692,6 +692,14 @@ def _environment(environ: Mapping[str, str] | None) -> Mapping[str, str]:
return os.environ if environ is None else environ


def has_bedrock_bearer_token(environ: Mapping[str, str] | None = None) -> bool:
"""Return whether AWS_BEARER_TOKEN_BEDROCK holds a real token.

An unset, empty, or whitespace-only value means no token, so Bedrock calls use IAM credentials.
"""
return bool(_environment(environ).get("AWS_BEARER_TOKEN_BEDROCK", "").strip())


def _required(environ: Mapping[str, str], variable: str) -> str:
value = environ.get(variable, "").strip()
if not value:
Expand Down
32 changes: 22 additions & 10 deletions src/skillevaluator/tier3/harbor/runtime_preflight.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ class CredentialProbeDisposition(StrEnum):
for _error_name, _target in (
("LoginError", "authentication"),
("InvalidChecksumConfigError", "configuration"),
("InvalidEndpointConfigurationError", "configuration"),
("UnknownTokenProviderError", "configuration"),
("UnsupportedServiceProtocolsError", "configuration"),
):
Expand Down Expand Up @@ -752,6 +753,7 @@ def _catalog_listing_is_authoritative(provider: ProviderConfig) -> bool:
_get_google_access_token,
_is_vertex_openapi_endpoint,
_parse_vertex_openapi_metadata,
has_bedrock_bearer_token,
)


Expand Down Expand Up @@ -1290,14 +1292,11 @@ def _probe_bedrock_model(provider: ProviderConfig, *, timeout_seconds: float) ->
)
session = boto3.session.Session()
_validate_bedrock_local_sdk_configuration(session)
bearer_token = os.environ.get("AWS_BEARER_TOKEN_BEDROCK")
if (
isinstance(bearer_token, str)
and bearer_token.strip()
and any(not 0x21 <= ord(character) <= 0x7E for character in bearer_token)
):
bearer_token = os.environ.get("AWS_BEARER_TOKEN_BEDROCK", "")
has_bearer_token = has_bedrock_bearer_token()
if has_bearer_token and any(not 0x21 <= ord(character) <= 0x7E for character in bearer_token):
raise InvalidConfigError(error_msg="Bedrock bearer token contains invalid characters")
if not isinstance(bearer_token, str) or not bearer_token.strip():
if not has_bearer_token:
metadata_unavailable = _monitor_bedrock_metadata_unavailability(session)
get_credentials = getattr(session, "get_credentials", None)
if callable(get_credentials):
Expand All @@ -1313,6 +1312,9 @@ def _probe_bedrock_model(provider: ProviderConfig, *, timeout_seconds: float) ->
)
raise NoCredentialsError
credentials.get_frozen_credentials()
# Botocore treats any set bearer variable, even a blank one, as a token.
# Pin SigV4 so the clients use the credentials checked above.
request_config = request_config.merge(BotoConfig(signature_version="v4"))
bedrock = session.client(
"bedrock",
region_name=provider.region or "us-west-2",
Expand All @@ -1323,9 +1325,19 @@ def _probe_bedrock_model(provider: ProviderConfig, *, timeout_seconds: float) ->
region_name=provider.region or "us-west-2",
config=request_config,
)
if (_bedrock_client_uses_tls(bedrock) or _bedrock_client_uses_tls(bedrock_runtime)) and (
_is_invalid_bedrock_ca_bundle(session)
):
catalog_uses_tls = _bedrock_client_uses_tls(bedrock)
runtime_uses_tls = _bedrock_client_uses_tls(bedrock_runtime)
if has_bearer_token and not (catalog_uses_tls and runtime_uses_tls):
# A constant detail names the cause and keeps the token and endpoint out of the output.
return ModelProbeResult(
False,
provider.provider,
provider.model,
"Bedrock bearer authentication (AWS_BEARER_TOKEN_BEDROCK) requires https:// Bedrock endpoints; "
"use an HTTPS endpoint override or unset the token",
failure_kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,
)
if (catalog_uses_tls or runtime_uses_tls) and _is_invalid_bedrock_ca_bundle(session):
raise InvalidConfigError(error_msg="configured AWS CA bundle cannot be loaded")
region_name = provider.region or "us-west-2"
catalog_authoritative = _is_native_bedrock_endpoint(
Expand Down
38 changes: 38 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,54 @@
from __future__ import annotations

import importlib.util
import ipaddress
import json
import ssl
import sys
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import ModuleType
from typing import Any

import pytest


@pytest.fixture
def loopback_tls(tmp_path: Path) -> tuple[ssl.SSLContext, Path]:
"""Create a loopback TLS context and the certificate clients can trust."""
x509 = pytest.importorskip("cryptography.x509")
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID

key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")])
certificate = (
x509.CertificateBuilder()
.subject_name(name)
.issuer_name(name)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.now(UTC) - timedelta(days=1))
.not_valid_after(datetime.now(UTC) + timedelta(days=1))
.add_extension(x509.SubjectAlternativeName([x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), False)
.sign(key, hashes.SHA256())
)
cert_path, key_path = tmp_path / "certificate.pem", tmp_path / "key.pem"
cert_path.write_bytes(certificate.public_bytes(serialization.Encoding.PEM))
key_path.write_bytes(
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
)
)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert_path, key_path)
return context, cert_path


@pytest.fixture(autouse=True)
def _isolate_output_provenance_key(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Keep every test away from the developer's persistent provenance key."""
Expand Down
Loading
Loading