From 765ae96e62663776a958a0b36001b6a367d86652 Mon Sep 17 00:00:00 2001 From: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:10:34 -0500 Subject: [PATCH] fix(tee/nras): validate endpoint ports and timeout range, require the 128-char report_data nonce, string EAR status, and finite EAR JSON numbers (#814) - Parse the endpoint with httpx.URL in NRASClient.__init__ and require HTTPS, a hostname and a port in 1-65535, so a malformed endpoint such as https://example.com:not-a-port/v1 raises ValueError at construction instead of httpx.InvalidURL at appraise time. An InvalidURL raised by an injected transport is also reported as NRASError. - Validate timeout with a chained comparison (0 < timeout <= 3600) instead of math.isfinite, so NaN, infinity and oversized ints such as 10**1000 raise ValueError rather than OverflowError, and no value that overflows a socket timeout reaches httpx. - Accept only the 128-character lowercase hex form of the 64-byte nonce as report.report_data (docs/spec/attestation.md section 3.3). Every provider emits nonce.hex() of that nonce, so the 64-character form had no producer. - Reject duplicate keys, non-finite constants, and exponent-overflow floats (parse_float with math.isfinite) in _post, and require string EAR status in _parse_ear. - Handle blank/whitespace CMCP_NRAS_API_KEY and invalid client/EAR payloads non-fatally in try_appraise. - Add regressions for malformed and out-of-range ports, oversized timeouts, the 128-character nonce contract and the real-client timeout path, and drop the extra blank line at the end of the test file. Signed-off-by: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> --- src/cmcp_runtime/tee/nras.py | 99 ++++++++++++-- tests/unit/test_nras_client.py | 232 ++++++++++++++++++++++++++++++++- 2 files changed, 317 insertions(+), 14 deletions(-) diff --git a/src/cmcp_runtime/tee/nras.py b/src/cmcp_runtime/tee/nras.py index 9735db28..bf527b5f 100644 --- a/src/cmcp_runtime/tee/nras.py +++ b/src/cmcp_runtime/tee/nras.py @@ -15,8 +15,11 @@ from __future__ import annotations import base64 +import json import logging +import math import os +import re from dataclasses import dataclass from datetime import UTC, datetime from typing import Any @@ -29,8 +32,13 @@ NRAS_ENDPOINT: str = "https://nras.nvidia.com/v1/attestation/gpu" _DEFAULT_TIMEOUT_SECONDS: float = 10.0 +# Socket timeouts overflow past the platform's time range, so cap well below it. +_MAX_TIMEOUT_SECONDS: float = 3600.0 _ENV_API_KEY: str = "CMCP_NRAS_API_KEY" _VALID_STATUSES: frozenset[str] = frozenset({"affirming", "warning", "contraindicated"}) +# docs/spec/attestation.md section 3.3: every provider signs a 64-byte nonce and +# reports it as nonce.hex(), i.e. 128 lowercase hex characters. +_REPORT_DATA_RE = re.compile(r"[0-9a-f]{128}") @dataclass @@ -74,8 +82,12 @@ class NRASClient: Args: api_key: NVIDIA developer API key (CMCP_NRAS_API_KEY). endpoint: NRAS appraisal endpoint URL. Override for testing only. - timeout: HTTP request timeout in seconds. + timeout: HTTP request timeout in seconds, greater than 0 and at most 3600. http_client: Optional pre-built httpx.Client; injected in tests. + + Raises: + ValueError: api_key is blank, endpoint is not a well-formed HTTPS URL with a + hostname and a port in 1-65535, or timeout is outside the accepted range. """ def __init__( @@ -86,6 +98,33 @@ def __init__( timeout: float = _DEFAULT_TIMEOUT_SECONDS, http_client: httpx.Client | None = None, ) -> None: + if not isinstance(api_key, str) or not api_key.strip(): + raise ValueError("api_key must be a non-empty string") + # Parse with httpx so init validates exactly what the request will use; its + # parser rejects a non-numeric port but accepts 0, negative and >65535 ports. + try: + url = httpx.URL(endpoint) if isinstance(endpoint, str) else None + except httpx.InvalidURL as exc: + raise ValueError(f"endpoint is not a valid URL: {exc}") from exc + if ( + url is None + or url.scheme != "https" + or not url.host + or (url.port is not None and not 1 <= url.port <= 65535) + ): + raise ValueError( + "endpoint must be a valid HTTPS URL with a hostname and a port in 1-65535" + ) + # Chained comparison, not math.isfinite: it is False for NaN and infinity and + # never converts an int, so an oversized int cannot raise OverflowError. + if ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not 0 < timeout <= _MAX_TIMEOUT_SECONDS + ): + raise ValueError( + f"timeout must be a number greater than 0 and at most {_MAX_TIMEOUT_SECONDS:g}" + ) self._api_key = api_key self._endpoint = endpoint self._timeout = timeout @@ -94,16 +133,25 @@ def __init__( def appraise(self, report: AttestationReport) -> AppraisalResult: """Submit attestation evidence to NRAS and return the EAR result. - The nonce field is taken from report.report_data (hex-encoded SHA-256 nonce). + The nonce field is taken from report.report_data, the 64-byte attestation nonce + every provider emits as ``nonce.hex()`` (128 lowercase hex characters, see + docs/spec/attestation.md section 3.3). Any other length or form is rejected. attestation_report is the base64-encoded raw_evidence blob; if raw_evidence is None (software-only dev mode) the measurement bytes are encoded instead. Raises: NRASAuthError: HTTP 401 from NRAS. NRASAppraisalError: Any other 4xx response. - NRASError: Network / timeout errors or unexpected response. + NRASError: Malformed report_data, network / timeout errors or + unexpected response. """ - nonce_b64 = base64.b64encode(bytes.fromhex(report.report_data)).decode() + rd = getattr(report, "report_data", None) + if not isinstance(rd, str) or _REPORT_DATA_RE.fullmatch(rd) is None: + raise NRASError( + "report.report_data must be a 128-character lowercase hex string " + "(the 64-byte attestation nonce)" + ) + nonce_b64 = base64.b64encode(bytes.fromhex(rd)).decode() if report.raw_evidence is not None: evidence_b64 = base64.b64encode(report.raw_evidence).decode() @@ -126,7 +174,7 @@ def appraise(self, report: AttestationReport) -> AppraisalResult: raise except httpx.TimeoutException as exc: raise NRASError(f"NRAS request timed out after {self._timeout}s") from exc - except httpx.HTTPError as exc: + except (httpx.HTTPError, httpx.InvalidURL) as exc: raise NRASError(f"NRAS HTTP transport error: {exc}") from exc return self._parse_ear(ear) @@ -145,15 +193,43 @@ def _post(self, payload: dict[str, Any], headers: dict[str, str]) -> dict[str, A if response.status_code >= 400: raise NRASAppraisalError(response.status_code, response.text) + def _no_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise ValueError(f"duplicate JSON object key: {key!r}") + out[key] = value + return out + + def _no_nonfinite(token: str) -> Any: + raise ValueError(f"non-finite JSON constant: {token}") + + def _finite_float(token: str) -> float: + value = float(token) + if not math.isfinite(value): + raise ValueError(f"non-finite JSON number: {token}") + return value + try: - return response.json() + parsed = json.loads( + response.text, + object_pairs_hook=_no_duplicate_keys, + parse_constant=_no_nonfinite, + parse_float=_finite_float, + ) except Exception as exc: raise NRASError(f"NRAS response is not valid JSON: {exc}") from exc + if not isinstance(parsed, dict): + raise NRASError("NRAS response must be a JSON object") + return parsed + @staticmethod def _parse_ear(ear: dict[str, Any]) -> AppraisalResult: """Validate and extract fields from a raw EAR JSON payload.""" + if not isinstance(ear, dict): + raise NRASError("EAR payload must be a JSON object") status = ear.get("status", "") - if status not in _VALID_STATUSES: + if not isinstance(status, str) or status not in _VALID_STATUSES: raise NRASError( f"NRAS returned unrecognised EAR status {status!r}. Expected one of {sorted(_VALID_STATUSES)}." ) @@ -192,7 +268,7 @@ def try_appraise(report: AttestationReport) -> AppraisalResult | None: Phase 2 / v0.2 -- implements issue #125. """ api_key = os.environ.get(_ENV_API_KEY) - if not api_key: + if not api_key or not api_key.strip(): logger.warning( "CMCP_NRAS_API_KEY is not set -- skipping NRAS post-attestation appraisal. " "The TRACE Trust Record appraisal field will be empty. " @@ -200,8 +276,8 @@ def try_appraise(report: AttestationReport) -> AppraisalResult | None: ) return None - client = NRASClient(api_key=api_key) try: + client = NRASClient(api_key=api_key) result = client.appraise(report) logger.info( "NRAS appraisal complete: status=%s verifier=%s", @@ -211,11 +287,10 @@ def try_appraise(report: AttestationReport) -> AppraisalResult | None: return result except NRASAuthError: logger.warning( - "NRAS appraisal skipped: API key was rejected (HTTP 401). " - "Check CMCP_NRAS_API_KEY." + "NRAS appraisal skipped: API key was rejected (HTTP 401). Check CMCP_NRAS_API_KEY." ) except NRASAppraisalError as exc: logger.warning("NRAS appraisal rejected evidence: %s", exc) - except NRASError as exc: + except (NRASError, ValueError) as exc: logger.warning("NRAS appraisal failed (network/timeout): %s", exc) return None diff --git a/tests/unit/test_nras_client.py b/tests/unit/test_nras_client.py index 0bea1e8e..6006f2be 100644 --- a/tests/unit/test_nras_client.py +++ b/tests/unit/test_nras_client.py @@ -28,7 +28,7 @@ def sw_report() -> AttestationReport: return AttestationReport( provider="software-only", measurement="DEVELOPMENT_ONLY_NOT_FOR_PRODUCTION", - report_data="aa" * 32, + report_data="aa" * 64, raw_evidence=None, attestation_generated_at=datetime.now(tz=UTC), attestation_validity_seconds=86400, @@ -40,7 +40,7 @@ def hw_report() -> AttestationReport: return AttestationReport( provider="software-only", measurement="sha256:" + "ab" * 32, - report_data="cd" * 32, + report_data="cd" * 64, raw_evidence=bytes.fromhex("deadbeef") * 64, attestation_generated_at=datetime.now(tz=UTC), attestation_validity_seconds=86400, @@ -289,8 +289,182 @@ def timeout_handler(request: httpx.Request) -> httpx.Response: assert result is None +@pytest.mark.parametrize( + ("api_key", "endpoint", "timeout"), + [ + ("", NRAS_ENDPOINT, 10.0), + (" ", NRAS_ENDPOINT, 10.0), + ("k", "http://nras.nvidia.com/v1", 10.0), + ("k", "ftp://nras.nvidia.com/v1", 10.0), + ("k", "https://", 10.0), + ("k", "https://:443/v1", 10.0), + ("k", None, 10.0), + ("k", "https://example.com:not-a-port/v1", 10.0), + ("k", "https://example.com:99999/v1", 10.0), + ("k", "https://example.com:65536/v1", 10.0), + ("k", "https://example.com:0/v1", 10.0), + ("k", "https://example.com:-1/v1", 10.0), + ("k", "https://exa\nmple.com/v1", 10.0), + ("k", NRAS_ENDPOINT, True), + ("k", NRAS_ENDPOINT, "10"), + ("k", NRAS_ENDPOINT, 0), + ("k", NRAS_ENDPOINT, -1.0), + ("k", NRAS_ENDPOINT, float("nan")), + ("k", NRAS_ENDPOINT, float("inf")), + ("k", NRAS_ENDPOINT, 1e308), + ("k", NRAS_ENDPOINT, 3600.5), + ("k", NRAS_ENDPOINT, 10**1000), + ("k", NRAS_ENDPOINT, -(10**1000)), + ], +) +def test_nras_client_init_validates_parameters(api_key, endpoint, timeout): + with pytest.raises(ValueError): + NRASClient(api_key=api_key, endpoint=endpoint, timeout=timeout) + + +@pytest.mark.parametrize( + ("endpoint", "timeout"), + [ + (NRAS_ENDPOINT, 10), + ("https://example.com:443/v1", 0.5), + ("https://example.com:8443/v1", 3600), + ("https://example.com:1/v1", 10.0), + ("https://example.com:65535/v1", 10.0), + ("https://[::1]:8443/v1", 10.0), + ], +) +def test_nras_client_init_accepts_valid_endpoint_and_timeout(endpoint, timeout): + assert NRASClient(api_key="k", endpoint=endpoint, timeout=timeout)._timeout == timeout + + +def test_appraise_without_injected_client_applies_configured_timeout(sw_report): + real_client = httpx.Client + seen: dict[str, float] = {} + + def factory(*, timeout: float) -> httpx.Client: + seen["timeout"] = timeout + return real_client( + transport=httpx.MockTransport( + lambda request: httpx.Response(200, content=json.dumps(_make_ear()).encode()) + ) + ) + + client = NRASClient(api_key="k", timeout=3600) + with patch("cmcp_runtime.tee.nras.httpx.Client", side_effect=factory): + assert client.appraise(sw_report).status == "affirming" + assert seen["timeout"] == 3600 + + +def test_appraise_converts_invalid_url_from_transport_to_nras_error(sw_report): + def handler(request: httpx.Request) -> httpx.Response: + raise httpx.InvalidURL("Invalid port: 'not-a-port'") + + http = httpx.Client(transport=httpx.MockTransport(handler)) + client = NRASClient(api_key="k", http_client=http) + with pytest.raises(NRASError, match="transport error"): + client.appraise(sw_report) + + +@pytest.mark.parametrize( + "bad_response_text", + [ + "[1, 2]", + '{"status": "contraindicated", "status": "affirming"}', + '{"status": "affirming", "score": NaN}', + '{"status": []}', + '{"status": {}}', + ], +) +def test_nras_rejects_non_dict_duplicate_keys_and_nonfinite_json(sw_report, bad_response_text): + client = NRASClient(api_key="k", http_client=_mock_text_client(200, bad_response_text)) + with pytest.raises(NRASError): + client.appraise(sw_report) + + +def _report_with(report_data: object) -> AttestationReport: + return AttestationReport( + provider="software-only", + measurement="DEVELOPMENT_ONLY_NOT_FOR_PRODUCTION", + report_data=report_data, # type: ignore[arg-type] + raw_evidence=None, + attestation_generated_at=datetime.now(tz=UTC), + attestation_validity_seconds=86400, + ) + + +def test_nras_accepts_64_byte_nonce_as_128_char_lowercase_hex(): + import base64 + + nonce = bytes(range(64)) + captured: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured.append(request) + return httpx.Response(200, content=json.dumps(_make_ear("affirming")).encode()) + + client = NRASClient( + api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)) + ) + assert client.appraise(_report_with(nonce.hex())).status == "affirming" + assert json.loads(captured[0].content)["nonce"] == base64.b64encode(nonce).decode() + + +BAD_REPORT_DATA = [ + "not-valid-hex", + "", + "aa", + "a" * 62, + "a" * 64, + "a" * 66, + "a" * 126, + "a" * 130, + "A" * 128, + "g" * 128, + "a" * 127 + "\n", + None, + b"a" * 128, +] + + +@pytest.mark.parametrize("bad_report_data", BAD_REPORT_DATA) +def test_appraise_rejects_report_data_that_is_not_a_128_char_lowercase_nonce(bad_report_data): + called = False + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal called + called = True + return httpx.Response(200, content=json.dumps(_make_ear()).encode()) + + client = NRASClient( + api_key="k", http_client=httpx.Client(transport=httpx.MockTransport(handler)) + ) + with pytest.raises(NRASError, match="report_data"): + client.appraise(_report_with(bad_report_data)) + assert not called + + +@pytest.mark.parametrize("bad_report_data", BAD_REPORT_DATA) +def test_try_appraise_handles_malformed_report_data_without_raising(bad_report_data, monkeypatch): + monkeypatch.setenv("CMCP_NRAS_API_KEY", "k") + assert try_appraise(_report_with(bad_report_data)) is None + + +def test_try_appraise_handles_whitespace_api_key_and_unhashable_ear_status(sw_report, monkeypatch): + monkeypatch.setenv("CMCP_NRAS_API_KEY", " ") + assert try_appraise(sw_report) is None + + monkeypatch.setenv("CMCP_NRAS_API_KEY", "valid-key") + mock_instance = NRASClient( + api_key="valid-key", + http_client=_mock_text_client(200, '{"status": []}'), + ) + with patch("cmcp_runtime.tee.nras.NRASClient", return_value=mock_instance): + assert try_appraise(sw_report) is None + + def test_try_appraise_logs_warning_when_no_key(sw_report, monkeypatch, caplog): import logging + monkeypatch.delenv("CMCP_NRAS_API_KEY", raising=False) with caplog.at_level(logging.WARNING, logger="cmcp_runtime.tee.nras"): try_appraise(sw_report) @@ -304,4 +478,58 @@ def test_try_appraise_logs_warning_when_no_key(sw_report, monkeypatch, caplog): def test_gateway_context_nras_appraisal_defaults_none(): from cmcp_runtime.startup import RuntimeContext + assert RuntimeContext.__dataclass_fields__["nras_appraisal"].default is None + + +@pytest.mark.parametrize( + "raw_json", + [ + '{"status":"affirming","score":1e1000}', + '{"status":"affirming","score":-1e1000}', + '{"status":"affirming","submods":{"gpu":{"score":-1e1000}}}', + '{"status":"affirming","score":{"nested":[1e1000]}}', + '{"status":"affirming","score":{"nested":[-1e1000]}}', + ], +) +def test_appraise_rejects_exponent_overflow(sw_report, raw_json): + client = NRASClient( + api_key="synthetic-key", + http_client=_mock_text_client(200, raw_json), + ) + with pytest.raises(NRASError, match="non-finite JSON number"): + client.appraise(sw_report) + + +@pytest.mark.parametrize( + "raw_json", + [ + '{"status":"affirming","score":1e1000}', + '{"status":"affirming","score":-1e1000}', + '{"status":"affirming","submods":{"gpu":{"score":-1e1000}}}', + '{"status":"affirming","score":{"nested":[1e1000]}}', + '{"status":"affirming","score":{"nested":[-1e1000]}}', + ], +) +def test_try_appraise_controls_exponent_overflow(sw_report, monkeypatch, raw_json): + monkeypatch.setenv("CMCP_NRAS_API_KEY", "synthetic-key") + client = NRASClient( + api_key="synthetic-key", + http_client=_mock_text_client(200, raw_json), + ) + with patch("cmcp_runtime.tee.nras.NRASClient", return_value=client): + assert try_appraise(sw_report) is None + + +@pytest.mark.parametrize("score", ["1e308", "-1e308", '{"nested":[1e308,-1e308,0.0]}']) +def test_appraise_preserves_finite_exponents(sw_report, score): + text = '{"status":"affirming","score":' + score + "}" + client = NRASClient(api_key="synthetic-key", http_client=_mock_text_client(200, text)) + result = client.appraise(sw_report) + assert result.status == "affirming" + assert result.ear_raw == json.loads(text) + + +def test_parse_ear_rejects_non_dict_payload(): + with pytest.raises(NRASError, match="EAR payload must be a JSON object"): + NRASClient._parse_ear(["not", "a", "dict"]) # type: ignore[arg-type]