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
7 changes: 5 additions & 2 deletions gateway/app/routers/mcp_public.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
import logging
import sys
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any

import mcp.types as mcp_types
from fastapi import APIRouter, HTTPException, Request
Expand All @@ -59,6 +59,9 @@
get_signing_key_service,
)

if TYPE_CHECKING:
from b2a_sdk.receipt_verifier import VerificationKey


# Image layout: both Dockerfiles copy the in-repo SDK to /sdk/python, install
# it, and set PYTHONPATH=/sdk/python/src. From /app/app/routers/mcp_public.py,
Expand Down Expand Up @@ -384,7 +387,7 @@ def _mcp_error(code: int, message: str) -> McpError:
return McpError(mcp_types.ErrorData(code=code, message=message))


async def _published_key_set() -> dict[str, bytes] | None:
async def _published_key_set() -> dict[str, bytes | VerificationKey] | None:
"""Load the same key set a verifier gets from trust-keys.json.

``None`` means "no usable keys right now" — the tool-level analogue of
Expand Down
6 changes: 4 additions & 2 deletions gateway/docs/key-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,10 @@ the choice is per-deployment.

The receipt format does not change. `alg` stays `Ed25519` for Vault and GCP
KMS. For AWS KMS until Ed25519 is native, the `alg` field becomes
`ECDSA-P256-SHA256` and verification code must accept both algorithms keyed
by the receipt's `alg` field.
`ECDSA-P256-SHA256`. Offline verifiers can check that algorithm using the
published key's `alg`, but receipt v0.1 still classifies a genuine P-256
receipt as `unsupported`. Enabling that KMS signing path also requires an
explicit receipt-format policy update.

### Concrete code changes

Expand Down
72 changes: 53 additions & 19 deletions gateway/failure_lab/verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
----------------

``SIGNATURE_VALID``
The Ed25519 signature verifies over the exact ``signing_input`` bytes,
The signature verifies over the exact ``signing_input`` bytes,
under the key named *inside* those signed bytes. This says the holder of
that private key signed this statement. Nothing more.

Expand Down Expand Up @@ -53,7 +53,9 @@
from enum import Enum
from typing import Any

from cryptography.exceptions import InvalidSignature
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

ED25519_RAW_LENGTH = 32
Expand All @@ -75,6 +77,11 @@ class KeySource(str, Enum):
OUT_OF_BAND_PIN = "out_of_band_pin"


@dataclass(frozen=True)
class _P256Key:
public_key: ec.EllipticCurvePublicKey


@dataclass(frozen=True)
class Claim:
name: str
Expand Down Expand Up @@ -138,8 +145,8 @@ def _b64(value: Any, *, urlsafe: bool = False) -> bytes | None:
return None


def parse_key_document(document: Any) -> dict[str, bytes]:
"""Read ``/.well-known/trust-keys.json`` into ``{kid: raw_public_key}``.
def parse_key_document(document: Any) -> dict[str, bytes | _P256Key]:
"""Read raw Ed25519 or DER SPKI P-256 keys from ``trust-keys.json``.

Keys the issuing plane marks disabled are dropped: a revoked key must not
keep validating receipts because a cached document still lists it.
Expand All @@ -149,7 +156,7 @@ def parse_key_document(document: Any) -> dict[str, bytes]:
entries = document.get("keys")
if not isinstance(entries, list):
raise ValueError("key document has no 'keys' list")
keys: dict[str, bytes] = {}
keys: dict[str, bytes | _P256Key] = {}
for entry in entries:
if not isinstance(entry, dict):
continue
Expand All @@ -158,6 +165,20 @@ def parse_key_document(document: Any) -> dict[str, bytes]:
continue
if entry.get("status") == "disabled":
continue
if entry.get("alg") == "ECDSA-P256-SHA256":
der = _b64(entry.get("public_key_b64", ""))
if der is None:
continue
try:
public_key = serialization.load_der_public_key(der)
except (ValueError, UnsupportedAlgorithm):
continue
if not isinstance(public_key, ec.EllipticCurvePublicKey) or not isinstance(
public_key.curve, ec.SECP256R1
):
continue
keys[kid] = _P256Key(public_key)
continue
if entry.get("alg") not in (None, "Ed25519"):
continue
raw = _b64(entry.get("public_key_b64", ""))
Expand Down Expand Up @@ -215,7 +236,7 @@ def field_coverage(bundle: dict[str, Any]) -> dict[str, str]:

def verify(
bundle: Any,
keys: dict[str, bytes],
keys: dict[str, bytes | _P256Key],
*,
key_source: KeySource = KeySource.ISSUER_ORIGIN,
expected_issuer: str | None = None,
Expand Down Expand Up @@ -287,32 +308,45 @@ def fail(reason: str, *, key_id: str | None = None) -> VerificationReport:
return fail("signed payload names no key", key_id=None)

algorithm = payload.get("alg", "Ed25519")
if algorithm != "Ed25519":
return fail(f"unsupported signature algorithm {algorithm!r}", key_id=key_id)

signature = _b64(signature_b64)
if signature is None or len(signature) != ED25519_SIGNATURE_LENGTH:
return fail("signature is not a 64-byte Ed25519 signature", key_id=key_id)
if signature is None:
return fail("signature is not valid base64", key_id=key_id)

raw_key = keys.get(key_id)
if raw_key is None:
key = keys.get(key_id)
if key is None:
return fail(f"no published key for kid {key_id!r}", key_id=key_id)
if len(raw_key) != ED25519_RAW_LENGTH:
return fail(f"key {key_id!r} is not a 32-byte Ed25519 key", key_id=key_id)

try:
Ed25519PublicKey.from_public_bytes(raw_key).verify(
signature, signing_input.encode("utf-8")
)
signing_bytes = signing_input.encode("utf-8")
if isinstance(key, _P256Key):
key_algorithm = "ECDSA-P256-SHA256"
key.public_key.verify(signature, signing_bytes, ec.ECDSA(hashes.SHA256()))
else:
key_algorithm = "Ed25519"
if len(signature) != ED25519_SIGNATURE_LENGTH:
return fail(
"signature is not a 64-byte Ed25519 signature", key_id=key_id
)
if len(key) != ED25519_RAW_LENGTH:
return fail(
f"key {key_id!r} is not a 32-byte Ed25519 key", key_id=key_id
)
Ed25519PublicKey.from_public_bytes(key).verify(signature, signing_bytes)
except InvalidSignature:
return fail("signature does not verify over signing_input", key_id=key_id)
except (ValueError, UnicodeEncodeError) as exc:
return fail(f"signature could not be checked: {exc}", key_id=key_id)

if algorithm != key_algorithm:
return fail(
f"signed algorithm {algorithm!r} does not match published key algorithm {key_algorithm!r}",
key_id=key_id,
)

signature_claim = Claim(
"SIGNATURE_VALID",
ClaimStatus.ESTABLISHED,
f"Ed25519 signature verifies over signing_input under kid {key_id!r}",
f"{key_algorithm} signature verifies over signing_input under kid {key_id!r}",
)

# Envelope/payload disagreement: the signature still verifies, so this is
Expand Down
132 changes: 132 additions & 0 deletions gateway/tests/test_failure_lab_verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from pathlib import Path

import pytest
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

from failure_lab.verifier import (
Expand All @@ -29,6 +31,7 @@

REPO_ROOT = Path(__file__).resolve().parents[1]
KEY_ID = "lab-test-ed25519"
P256_KEY_ID = "lab-test-p256"


@pytest.fixture
Expand Down Expand Up @@ -66,6 +69,135 @@ def signed_bundle() -> tuple[dict, dict[str, bytes]]:
return bundle, {KEY_ID: raw_public}


@pytest.fixture
def p256_signed_bundle():
private = ec.generate_private_key(ec.SECP256R1())
public_der = private.public_key().public_bytes(
serialization.Encoding.DER,
serialization.PublicFormat.SubjectPublicKeyInfo,
)
payload = {
"kid": P256_KEY_ID,
"alg": "ECDSA-P256-SHA256",
"receipt_id": "rcpt-p256",
}
signing_input = json.dumps(payload, sort_keys=True, separators=(",", ":"))
bundle = {
"kid": P256_KEY_ID,
"alg": "ECDSA-P256-SHA256",
"receipt_id": "rcpt-p256",
"signing_input": signing_input,
"signature": base64.b64encode(
private.sign(signing_input.encode(), ec.ECDSA(hashes.SHA256()))
).decode(),
}
document = {
"keys": [
{
"kid": P256_KEY_ID,
"alg": "ECDSA-P256-SHA256",
"status": "active",
"public_key_b64": base64.b64encode(public_der).decode(),
}
]
}
return bundle, document, private


def test_genuine_p256_receipt_establishes_only_signature(p256_signed_bundle):
bundle, document, _ = p256_signed_bundle
report = verify(bundle, parse_key_document(document))

assert report.signature.status is ClaimStatus.ESTABLISHED
assert "ECDSA-P256-SHA256" in report.signature.reason
assert report.issuer_trust.status is ClaimStatus.NOT_ESTABLISHED
assert report.downstream_execution.status is ClaimStatus.NOT_ESTABLISHED


@pytest.mark.parametrize(
"signing_input",
[
lambda text: text.replace("rcpt-p256", "rcpt-other"),
lambda text: text.replace("ECDSA-P256-SHA256", "Ed25519"),
],
)
def test_p256_signed_byte_edit_fails_signature(p256_signed_bundle, signing_input):
bundle, document, _ = p256_signed_bundle
changed = {**bundle, "signing_input": signing_input(bundle["signing_input"])}

report = verify(changed, parse_key_document(document))

assert report.signature.status is ClaimStatus.FAILED
assert report.signature.reason == "signature does not verify over signing_input"


def test_p256_invalid_signature_and_unknown_key_fail(p256_signed_bundle):
bundle, document, _ = p256_signed_bundle
keys = parse_key_document(document)
malformed_signature = {
**bundle,
"signature": base64.b64encode(b"\x30\x00").decode(),
}

assert verify(malformed_signature, keys).signature.status is ClaimStatus.FAILED
assert verify(bundle, {}).signature.status is ClaimStatus.FAILED


def test_p256_signed_algorithm_must_match_published_key(p256_signed_bundle):
bundle, document, private = p256_signed_bundle
payload = json.loads(bundle["signing_input"])
payload["alg"] = "Ed25519"
signing_input = json.dumps(payload, sort_keys=True, separators=(",", ":"))
mislabeled = {
**bundle,
"signing_input": signing_input,
"signature": base64.b64encode(
private.sign(signing_input.encode(), ec.ECDSA(hashes.SHA256()))
).decode(),
}

report = verify(mislabeled, parse_key_document(document))

assert report.signature.status is ClaimStatus.FAILED
assert "does not match published key algorithm" in report.signature.reason


def test_p256_key_document_rejects_disabled_wrong_curve_and_invalid_der(
p256_signed_bundle,
):
bundle, document, _ = p256_signed_bundle
valid = document["keys"][0]
wrong_curve = (
ec.generate_private_key(ec.SECP384R1())
.public_key()
.public_bytes(
serialization.Encoding.DER,
serialization.PublicFormat.SubjectPublicKeyInfo,
)
)
document = {
"keys": [
{**valid, "kid": "disabled", "status": "disabled"},
{
**valid,
"kid": "wrong-curve",
"public_key_b64": base64.b64encode(wrong_curve).decode(),
},
{
**valid,
"kid": "invalid-der",
"public_key_b64": base64.b64encode(b"bad").decode(),
},
valid,
]
}

keys = parse_key_document(document)

assert set(keys) == {P256_KEY_ID}
assert verify(bundle, keys).signature.status is ClaimStatus.ESTABLISHED


def test_verifier_imports_neither_the_app_nor_the_product_sdk():
"""A verifier that shares code with the signer cannot catch a shared bug."""
probe = (
Expand Down
5 changes: 3 additions & 2 deletions sdk/python/src/b2a_sdk/edge_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
from .errors import PermitDeniedError
from .receipt_verifier import (
VerificationError,
VerificationKey,
canonical_json,
key_set_from_document,
verify_ed25519,
Expand Down Expand Up @@ -299,7 +300,7 @@ class LocalPermitValidator:
session do not silently overrun the cached budget.
"""

def __init__(self, permit: dict[str, Any], key_set: dict[str, bytes]) -> None:
def __init__(self, permit: dict[str, Any], key_set: dict[str, bytes | VerificationKey]) -> None:
self._permit = dict(permit)
self._key_set = dict(key_set)
# Locally reserved credits and per-tool call counts, advanced by
Expand Down Expand Up @@ -471,7 +472,7 @@ def verify_permit(self, permit: dict[str, Any] | None = None) -> bool:
except (KeyError, TypeError, ValueError, ArithmeticError):
return False
raw_public_key = self._key_set.get(payload["kid"])
if raw_public_key is None or len(raw_public_key) != 32:
if not isinstance(raw_public_key, bytes) or len(raw_public_key) != 32:
return False
if len(signature) != 64:
return False
Expand Down
Loading
Loading