|
| 1 | +import json |
| 2 | + |
| 3 | +from collections.abc import Callable |
| 4 | +from typing import Any |
| 5 | + |
| 6 | + |
| 7 | +try: |
| 8 | + from jose import jws |
| 9 | + from jose.backends.base import Key |
| 10 | + from jose.exceptions import JOSEError |
| 11 | + from jose.utils import base64url_decode, base64url_encode |
| 12 | +except ImportError as e: |
| 13 | + raise ImportError( |
| 14 | + 'A2AUtilsSigning requires python-jose to be installed. ' |
| 15 | + 'Install with: ' |
| 16 | + "'pip install a2a-sdk[signing]'" |
| 17 | + ) from e |
| 18 | + |
| 19 | +from a2a.types import AgentCard, AgentCardSignature |
| 20 | + |
| 21 | + |
| 22 | +def clean_empty(d: Any) -> Any: |
| 23 | + """Recursively remove empty lists, dicts, strings, and None values from a dictionary.""" |
| 24 | + if isinstance(d, dict): |
| 25 | + cleaned = {k: clean_empty(v) for k, v in d.items()} |
| 26 | + return { |
| 27 | + k: v |
| 28 | + for k, v in cleaned.items() |
| 29 | + if v is not None and (isinstance(v, (bool, int, float)) or v) |
| 30 | + } |
| 31 | + if isinstance(d, list): |
| 32 | + cleaned = [clean_empty(v) for v in d] |
| 33 | + return [ |
| 34 | + v |
| 35 | + for v in cleaned |
| 36 | + if v is not None and (isinstance(v, (bool, int, float)) or v) |
| 37 | + ] |
| 38 | + return d if d not in [None, '', [], {}] else None |
| 39 | + |
| 40 | + |
| 41 | +def canonicalize_agent_card(agent_card: AgentCard) -> str: |
| 42 | + """Canonicalizes the Agent Card JSON according to RFC 8785 (JCS).""" |
| 43 | + card_dict = agent_card.model_dump( |
| 44 | + exclude={'signatures'}, |
| 45 | + exclude_defaults=True, |
| 46 | + by_alias=True, |
| 47 | + ) |
| 48 | + # Ensure 'protocol_version' is always included |
| 49 | + protocol_version_alias = ( |
| 50 | + AgentCard.model_fields['protocol_version'].alias or 'protocol_version' |
| 51 | + ) |
| 52 | + if protocol_version_alias not in card_dict: |
| 53 | + card_dict[protocol_version_alias] = agent_card.protocol_version |
| 54 | + |
| 55 | + # Recursively remove empty/None values |
| 56 | + cleaned_dict = clean_empty(card_dict) |
| 57 | + |
| 58 | + return json.dumps(cleaned_dict, separators=(',', ':'), sort_keys=True) |
| 59 | + |
| 60 | + |
| 61 | +def create_agent_card_signer( |
| 62 | + signing_key: str | bytes | dict[str, Any] | Key, |
| 63 | + kid: str, |
| 64 | + alg: str = 'HS256', |
| 65 | + jku: str | None = None, |
| 66 | +) -> Callable[[AgentCard], AgentCard]: |
| 67 | + """Creates a function that signs an AgentCard and adds the signature. |
| 68 | +
|
| 69 | + Args: |
| 70 | + signing_key: The private key for signing. |
| 71 | + kid: Key ID for the signing key. |
| 72 | + alg: The algorithm to use (e.g., "ES256", "RS256"). |
| 73 | + jku: Optional URL to the JWKS. |
| 74 | +
|
| 75 | + Returns: |
| 76 | + A callable that takes an AgentCard and returns the modified AgentCard with a signature. |
| 77 | + """ |
| 78 | + |
| 79 | + def agent_card_signer(agent_card: AgentCard) -> AgentCard: |
| 80 | + """The actual card_modifier function.""" |
| 81 | + canonical_payload = canonicalize_agent_card(agent_card) |
| 82 | + |
| 83 | + headers = {'kid': kid, 'typ': 'JOSE'} |
| 84 | + if jku: |
| 85 | + headers['jku'] = jku |
| 86 | + |
| 87 | + jws_string = jws.sign( |
| 88 | + payload=canonical_payload.encode('utf-8'), |
| 89 | + key=signing_key, |
| 90 | + headers=headers, |
| 91 | + algorithm=alg, |
| 92 | + ) |
| 93 | + |
| 94 | + # The result of jws.sign is a compact serialization: HEADER.PAYLOAD.SIGNATURE |
| 95 | + protected_header, _, signature = jws_string.split('.') |
| 96 | + |
| 97 | + agent_card_signature = AgentCardSignature( |
| 98 | + protected=protected_header, |
| 99 | + signature=signature, |
| 100 | + ) |
| 101 | + |
| 102 | + agent_card.signatures = (agent_card.signatures or []) + [ |
| 103 | + agent_card_signature |
| 104 | + ] |
| 105 | + return agent_card |
| 106 | + |
| 107 | + return agent_card_signer |
| 108 | + |
| 109 | + |
| 110 | +def create_signature_verifier( |
| 111 | + key_provider: Callable[ |
| 112 | + [str | None, str | None], str | bytes | dict[str, Any] | Key |
| 113 | + ], |
| 114 | +) -> Callable[[AgentCard], None]: |
| 115 | + """Creates a function that verifies AgentCard signatures. |
| 116 | +
|
| 117 | + Args: |
| 118 | + key_provider: A callable that takes key-id (kid) and JSON web key url (jku) and returns the verification key. |
| 119 | +
|
| 120 | + Returns: |
| 121 | + A callable that takes an AgentCard, and raises an error if none of the signatures are valid. |
| 122 | + """ |
| 123 | + |
| 124 | + def signature_verifier( |
| 125 | + agent_card: AgentCard, |
| 126 | + ) -> None: |
| 127 | + """The actual signature_verifier function.""" |
| 128 | + if not agent_card.signatures: |
| 129 | + raise JOSEError('No signatures found on AgentCard') |
| 130 | + |
| 131 | + last_error = None |
| 132 | + for agent_card_signature in agent_card.signatures: |
| 133 | + try: |
| 134 | + # fetch kid and jku from protected header |
| 135 | + protected_header_json = base64url_decode( |
| 136 | + agent_card_signature.protected.encode('utf-8') |
| 137 | + ).decode('utf-8') |
| 138 | + protected_header = json.loads(protected_header_json) |
| 139 | + kid = protected_header.get('kid') |
| 140 | + jku = protected_header.get('jku') |
| 141 | + verification_key = key_provider(kid, jku) |
| 142 | + |
| 143 | + canonical_payload = canonicalize_agent_card(agent_card) |
| 144 | + encoded_payload = base64url_encode( |
| 145 | + canonical_payload.encode('utf-8') |
| 146 | + ).decode('utf-8') |
| 147 | + token = f'{agent_card_signature.protected}.{encoded_payload}.{agent_card_signature.signature}' |
| 148 | + |
| 149 | + jws.verify( |
| 150 | + token=token, |
| 151 | + key=verification_key, |
| 152 | + algorithms=None, |
| 153 | + ) |
| 154 | + return # Found a valid signature |
| 155 | + |
| 156 | + except JOSEError as e: |
| 157 | + last_error = e |
| 158 | + continue |
| 159 | + raise JOSEError('No valid signature found') from last_error |
| 160 | + |
| 161 | + return signature_verifier |
0 commit comments