From b541e087431c44d6bfeda2011cfb273ba8ca9bfd Mon Sep 17 00:00:00 2001 From: Sneha Edula Date: Thu, 19 Nov 2026 18:04:21 -0500 Subject: [PATCH 1/6] Support RS256 --- ce/commands/iir_sign_challenge.py | 279 +++++++++--- tests/test_sign_single_challenge.py | 668 ++++++++++++++++++++++------ 2 files changed, 760 insertions(+), 187 deletions(-) diff --git a/ce/commands/iir_sign_challenge.py b/ce/commands/iir_sign_challenge.py index 3b79521..3d1cb78 100644 --- a/ce/commands/iir_sign_challenge.py +++ b/ce/commands/iir_sign_challenge.py @@ -1,28 +1,52 @@ """`ce iir challenge sign` - sign and verify a Proof JWT for a single CE challenge. -Reads a challenge JSON file produced by CE, signs it with an Ed25519 private key -(alg=EdDSA), and verifies the resulting JWT against the public key resolved from -the DID (did:key or did:web). No login required. +Reads a challenge JSON file produced by CE, signs it with a private key and +verifies the resulting JWT against the public key resolved from the DID +(did:key or did:web). No login required. + +Supported keys (the algorithm follows the key type): + - Ed25519 -> alg=EdDSA + - RSA -> alg=RS256 (2048 bits or more) """ from __future__ import annotations +import base64 +import binascii import json -from typing import Any, Dict, Tuple +from typing import Any, Dict, Tuple, Union import base58 import click import jwt import requests +from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import ( Ed25519PrivateKey, Ed25519PublicKey, ) +from cryptography.hazmat.primitives.asymmetric.rsa import ( + RSAPrivateKey, + RSAPublicKey, +) +from jwt.algorithms import RSAAlgorithm from rich.console import Console console = Console() err_console = Console(stderr=True) +ALG_EDDSA = "EdDSA" +ALG_RS256 = "RS256" + +MULTICODEC_ED25519_PUB = 0xED +MULTICODEC_ED25519_PRIV = 0x1300 +MULTICODEC_RSA_PUB = 0x1205 + +MIN_RSA_KEY_SIZE_BITS = 2048 + +PrivateKey = Union[Ed25519PrivateKey, RSAPrivateKey] +PublicKey = Union[Ed25519PublicKey, RSAPublicKey] + # Multibase + multicodec helpers @@ -45,8 +69,7 @@ def _decode_multibase_base58btc(z_value: str) -> bytes: -# Private key to Ed25519 seed - +# Private key def _extract_ed25519_seed_from_private_key(private_key_multibase: str) -> bytes: raw = _decode_multibase_base58btc(private_key_multibase.strip()) @@ -59,16 +82,87 @@ def _extract_ed25519_seed_from_private_key(private_key_multibase: str) -> bytes: return raw[2:] code, n = _parse_uvarint(raw) - if code == 0x1300 and len(raw) - n == 32: + if code == MULTICODEC_ED25519_PRIV and len(raw) - n == 32: return raw[n:] raise ValueError("Unrecognized privateKey encoding") +def _load_private_key_bytes(data: bytes) -> PrivateKey: + """Load a PEM or DER private key (PKCS#8, or PKCS#1 for RSA). Unencrypted only.""" + try: + if b"-----BEGIN" in data: + key = serialization.load_pem_private_key(data, password=None) + else: + key = serialization.load_der_private_key(data, password=None) + except TypeError as e: + raise ValueError(f"Private key could not be loaded: {e}") from e + + if isinstance(key, (Ed25519PrivateKey, RSAPrivateKey)): + return key + + raise ValueError( + f"Unsupported private key type {type(key).__name__}. Expected RSA or Ed25519." + ) + + +def _load_private_key_from_text(text: str) -> PrivateKey: + """Pasted key: full PEM (real newlines or literal \\n), or just the base64 body.""" + cleaned = text.strip().replace("\\n", "\n") + + if "-----BEGIN" in cleaned: + return _load_private_key_bytes(cleaned.encode("ascii")) + + body = "".join(cleaned.split()) + try: + der = base64.b64decode(body, validate=True) + except (binascii.Error, ValueError) as e: + raise ValueError("Pasted key is neither PEM nor base64 DER.") from e + + return _load_private_key_bytes(der) + + +def _load_signing_key( + private_key_mb: str | None, + private_key_file: str | None, + private_key_pem: str | None, +) -> Tuple[PrivateKey, str]: + """Return the private key and the JWT alg that goes with it.""" + given = [ + v for v in (private_key_mb, private_key_file, private_key_pem) if v + ] + if len(given) != 1: + raise click.ClickException( + "Give exactly one of --private-key, --private-key-file or --private-key-pem." + ) + + try: + if private_key_mb: + seed = _extract_ed25519_seed_from_private_key(private_key_mb) + key: PrivateKey = Ed25519PrivateKey.from_private_bytes(seed) + elif private_key_file: + with open(private_key_file, "rb") as f: + key = _load_private_key_bytes(f.read()) + else: + key = _load_private_key_from_text(private_key_pem or "") + except ValueError as e: + raise click.ClickException(f"Could not load private key: {e}") + + if isinstance(key, RSAPrivateKey): + if key.key_size < MIN_RSA_KEY_SIZE_BITS: + raise click.ClickException( + f"RSA key is {key.key_size} bits; at least " + f"{MIN_RSA_KEY_SIZE_BITS} bits are required." + ) + return key, ALG_RS256 + + return key, ALG_EDDSA + + # did:key resolution (offline) -def _extract_ed25519_pub_from_did_key(did_or_kid: str) -> bytes: +def _public_key_from_did_key(did_or_kid: str) -> PublicKey: base = did_or_kid.split("#", 1)[0].strip() if not base.startswith("did:key:"): raise ValueError("Not a did:key DID") @@ -77,13 +171,24 @@ def _extract_ed25519_pub_from_did_key(did_or_kid: str) -> bytes: raw = _decode_multibase_base58btc(mb) if len(raw) == 32: - return raw + return Ed25519PublicKey.from_public_bytes(raw) code, n = _parse_uvarint(raw) - if code == 0xED and (len(raw) - n) == 32: - return raw[n:] + key_bytes = raw[n:] - raise ValueError("Invalid did:key encoding (expected Ed25519 public key)") + if code == MULTICODEC_ED25519_PUB and len(key_bytes) == 32: + return Ed25519PublicKey.from_public_bytes(key_bytes) + + if code == MULTICODEC_RSA_PUB: + # did:key RSA keys are PKCS#1 RSAPublicKey DER. + key = serialization.load_der_public_key(key_bytes) + if isinstance(key, RSAPublicKey): + return key + raise ValueError("did:key RSA payload is not an RSA public key") + + raise ValueError( + f"Unsupported did:key multicodec 0x{code:X} (expected Ed25519 or RSA)" + ) @@ -120,7 +225,45 @@ def _fetch_did_json(did_web_base: str) -> Dict[str, Any]: return doc -def _public_key_from_did_doc(*, kid: str, did_doc: Dict[str, Any]) -> bytes: +def _public_key_from_verification_method(vm: Dict[str, Any]) -> PublicKey: + jwk = vm.get("publicKeyJwk") + if isinstance(jwk, dict) and jwk.get("kty") == "RSA": + if vm.get("type") != "JsonWebKey2020": + raise ValueError( + f"RSA verification method type is '{vm.get('type')}', " + "expected 'JsonWebKey2020'" + ) + if "d" in jwk: + raise ValueError("publicKeyJwk contains private key material ('d')") + + key = RSAAlgorithm.from_jwk(jwk) + if isinstance(key, RSAPublicKey): + return key + raise ValueError("publicKeyJwk is not an RSA public key") + + # Ed25519: publicKeyMultibase. + pkmb = vm.get("publicKeyMultibase") + if not isinstance(pkmb, str) or not pkmb.startswith("z"): + raise ValueError( + "Verification method has neither an RSA publicKeyJwk " + "nor a valid publicKeyMultibase" + ) + + raw = _decode_multibase_base58btc(pkmb) + + if len(raw) == 32: + return Ed25519PublicKey.from_public_bytes(raw) + + code, n = _parse_uvarint(raw) + if code == MULTICODEC_ED25519_PUB and (len(raw) - n) == 32: + return Ed25519PublicKey.from_public_bytes(raw[n:]) + + raise ValueError( + "publicKeyMultibase is not an Ed25519 key encoding we recognize" + ) + + +def _public_key_from_did_doc(*, kid: str, did_doc: Dict[str, Any]) -> PublicKey: did_base = kid.split("#", 1)[0].strip() kid = kid.strip() @@ -141,31 +284,16 @@ def normalize(vm_id: str) -> str: if normalize(vm_id) != kid: continue - pkmb = vm.get("publicKeyMultibase") - if not isinstance(pkmb, str) or not pkmb.startswith("z"): - raise ValueError("Invalid publicKeyMultibase") - - raw = _decode_multibase_base58btc(pkmb) - - if len(raw) == 32: - return raw - - code, n = _parse_uvarint(raw) - if code == 0xED and (len(raw) - n) == 32: - return raw[n:] - - raise ValueError( - "publicKeyMultibase is not an Ed25519 key encoding we recognize" - ) + return _public_key_from_verification_method(vm) raise ValueError(f"kid not found in did.json: {kid}") -def _resolve_public_key_bytes_for_kid(kid: str) -> bytes: +def _resolve_public_key_for_kid(kid: str) -> PublicKey: base = kid.split("#", 1)[0].strip() if base.startswith("did:key:"): - return _extract_ed25519_pub_from_did_key(kid) + return _public_key_from_did_key(kid) if base.startswith("did:web:"): did_doc = _fetch_did_json(base) @@ -177,16 +305,18 @@ def _resolve_public_key_bytes_for_kid(kid: str) -> bytes: # Signing + verification -def _sign_payload(private_key_mb: str, kid: str, payload_obj: Dict[str, Any]) -> str: - seed = _extract_ed25519_seed_from_private_key(private_key_mb) - private_key = Ed25519PrivateKey.from_private_bytes(seed) - - headers = {"typ": "JWT", "alg": "EdDSA", "kid": kid} +def _sign_payload( + private_key: PrivateKey, + alg: str, + kid: str, + payload_obj: Dict[str, Any], +) -> str: + headers = {"typ": "JWT", "alg": alg, "kid": kid} token = jwt.encode( payload=payload_obj, key=private_key, - algorithm="EdDSA", + algorithm=alg, headers=headers, ) @@ -196,11 +326,11 @@ def _sign_payload(private_key_mb: str, kid: str, payload_obj: Dict[str, Any]) -> return token -def _verify_signature_only(token: str, public_key: Ed25519PublicKey) -> None: +def _verify_signature_only(token: str, public_key: PublicKey, alg: str) -> None: jwt.decode( token, key=public_key, - algorithms=["EdDSA"], + algorithms=[alg], options={ "verify_signature": True, "verify_aud": False, @@ -212,12 +342,21 @@ def _verify_signature_only(token: str, public_key: Ed25519PublicKey) -> None: ) -def _assert_signature_verifiable(token: str, kid: str) -> None: - pub_bytes = _resolve_public_key_bytes_for_kid(kid) - pub_key = Ed25519PublicKey.from_public_bytes(pub_bytes) +def _assert_signature_verifiable(token: str, kid: str, alg: str) -> None: + pub_key = _resolve_public_key_for_kid(kid) + + if alg == ALG_RS256 and not isinstance(pub_key, RSAPublicKey): + raise click.ClickException( + "Signed with an RSA key, but the DID resolves to an Ed25519 key." + ) + + if alg == ALG_EDDSA and not isinstance(pub_key, Ed25519PublicKey): + raise click.ClickException( + "Signed with an Ed25519 key, but the DID resolves to an RSA key." + ) try: - _verify_signature_only(token, pub_key) + _verify_signature_only(token, pub_key, alg) except jwt.exceptions.InvalidSignatureError as e: raise click.ClickException( "Signature verification failed (token does not match DID public key)." @@ -226,7 +365,7 @@ def _assert_signature_verifiable(token: str, kid: str) -> None: raise click.ClickException(f"JWT verification error: {e}") from e err_console.print( - "[green]Signature verification: OK[/green] (matches DID public key)" + f"[green]Signature verification: OK[/green] ({alg}, matches DID public key)" ) @@ -237,10 +376,28 @@ def _assert_signature_verifiable(token: str, kid: str) -> None: @click.option( "--private-key", "private_key", - required=True, + default=None, metavar="MULTIBASE", help="Ed25519 private seed (multibase base58btc, starts with 'z').", ) +@click.option( + "--private-key-file", + "private_key_file", + default=None, + type=click.Path(exists=True, dir_okay=False, readable=True), + metavar="PATH", + help="PEM or DER private key file (RSA -> RS256, Ed25519 -> EdDSA). Unencrypted.", +) +@click.option( + "--private-key-pem", + "private_key_pem", + default=None, + metavar="TEXT", + help=( + "Pasted private key: full PEM (newlines or literal \\n) or just the " + "base64 body. RSA -> RS256, Ed25519 -> EdDSA." + ), +) @click.option( "--challenge-file", "challenge_file", @@ -258,23 +415,35 @@ def _assert_signature_verifiable(token: str, kid: str) -> None: help="Write JWT to this file (otherwise printed to stdout).", ) def sign_individual_challenge( - private_key: str, + private_key: str | None, + private_key_file: str | None, + private_key_pem: str | None, challenge_file: str, out_path: str | None, ) -> None: - """Sign a single CE challenge JSON file and produce a Proof JWT (EdDSA/Ed25519). + """Sign a single CE challenge JSON file and produce a Proof JWT. \b + The algorithm follows the key: Ed25519 -> EdDSA, RSA -> RS256. + Give exactly one of --private-key, --private-key-file, --private-key-pem. The challenge JSON must include: did, challenge, aud, iat, exp. Signature verification uses did:key (offline) or did:web (HTTPS). \b - Example: - ce iir challenge sign \\ - --private-key zABC... \\ - --challenge-file challenge.json \\ - --output signed-challenge.jwt + Examples: + ce iir challenge sign --private-key zABC... \\ + --challenge-file challenge.json -o signed-challenge.jwt + + \b + ce iir challenge sign --private-key-file rsa-key.pem \\ + --challenge-file challenge.json -o signed-challenge.jwt """ + signing_key, alg = _load_signing_key( + private_key, + private_key_file, + private_key_pem, + ) + try: with open(challenge_file, "r", encoding="utf-8") as f: payload_obj = json.load(f) @@ -300,12 +469,12 @@ def sign_individual_challenge( kid = did_value.strip() try: - token = _sign_payload(private_key, kid, payload_obj) - except ValueError as e: + token = _sign_payload(signing_key, alg, kid, payload_obj) + except (ValueError, jwt.PyJWTError) as e: raise click.ClickException(f"Signing failed: {e}") try: - _assert_signature_verifiable(token, kid) + _assert_signature_verifiable(token, kid, alg) except requests.RequestException as e: raise click.ClickException(f"Failed to fetch did.json: {e}") except ValueError as e: diff --git a/tests/test_sign_single_challenge.py b/tests/test_sign_single_challenge.py index e64633b..d954b04 100644 --- a/tests/test_sign_single_challenge.py +++ b/tests/test_sign_single_challenge.py @@ -14,6 +14,7 @@ import click import pytest import requests +from click.testing import CliRunner @@ -24,23 +25,82 @@ _assert_signature_verifiable, _decode_multibase_base58btc, _did_web_to_url, - _extract_ed25519_pub_from_did_key, _extract_ed25519_seed_from_private_key, _fetch_did_json, + _load_private_key_bytes, + _load_private_key_from_text, + _load_signing_key, _parse_uvarint, _public_key_from_did_doc, - _resolve_public_key_bytes_for_kid, + _public_key_from_did_key, + _resolve_public_key_for_kid, _sign_payload, _verify_signature_only, + sign_individual_challenge, ) +MODULE = "ce.commands.iir_sign_challenge" CHALLENGE_UUID = "11111111-2222-3333-4444-555555555555" CTID = "ce-12345678-1234-1234-1234-123456789abc" ED25519_DID_KEY = "did:key:z6MkhaXgBZDvf7gKKWXjGmgkbQXyrXYY4uZmTaTzPhRgg9Wm" ED25519_KID = f"{ED25519_DID_KEY}#{ED25519_DID_KEY[len('did:key:'):]}" +RSA_MULTICODEC_PREFIX = bytes([0x85, 0x24]) # varint of 0x1205 + + + +# Helpers + +def _raw_ed25519(public_key) -> bytes: + from cryptography.hazmat.primitives import serialization + + return public_key.public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + + +def _b64url_uint(value: int) -> str: + raw = value.to_bytes((value.bit_length() + 7) // 8, "big") + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + +def _rsa_jwk(public_key, **extra): + numbers = public_key.public_numbers() + jwk = {"kty": "RSA", "n": _b64url_uint(numbers.n), "e": _b64url_uint(numbers.e)} + jwk.update(extra) + return jwk + + +def _decode_segment(token: str, index: int) -> dict: + segment = token.split(".")[index] + padded = segment + "=" * (-len(segment) % 4) + return json.loads(base64.urlsafe_b64decode(padded)) + + +def _tamper_signature(token: str) -> str: + parts = token.split(".") + first = parts[2][0] + parts[2] = ("B" if first != "B" else "C") + parts[2][1:] + return ".".join(parts) + + +def _mock_did_json(doc): + mock_resp = MagicMock() + mock_resp.json.return_value = doc + mock_resp.raise_for_status = MagicMock() + return patch(f"{MODULE}.requests.get", return_value=mock_resp) + + +def _write_json(path: Path, obj) -> Path: + path.write_text(json.dumps(obj), encoding="utf-8") + return path + + + +# Fixtures @pytest.fixture(scope="session") def ed25519_keypair(): @@ -80,6 +140,54 @@ def ed25519_keypair(): return priv_multibase, did_key, kid +@pytest.fixture(scope="session") +def ed25519_signing_key(ed25519_keypair): + """The Ed25519 private key object for the session keypair.""" + priv, _, _ = ed25519_keypair + key, alg = _load_signing_key(priv, None, None) + assert alg == "EdDSA" + return key + + +@pytest.fixture(scope="session") +def rsa_keypair(): + """Generate an RSA 2048 keypair and its did:key. + + Returns a dict with: key, pem_pkcs8, pem_pkcs1, did_key, kid. + """ + import base58 + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import rsa + + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + + pem_pkcs8 = key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + pem_pkcs1 = key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=serialization.NoEncryption(), + ) + pub_pkcs1 = key.public_key().public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.PKCS1, + ) + + did_key = "did:key:z" + base58.b58encode(RSA_MULTICODEC_PREFIX + pub_pkcs1).decode() + kid = f"{did_key}#{did_key[len('did:key:'):]}" + + return { + "key": key, + "pem_pkcs8": pem_pkcs8, + "pem_pkcs1": pem_pkcs1, + "did_key": did_key, + "kid": kid, + } + + @pytest.fixture def valid_challenge_payload(): return { @@ -92,11 +200,6 @@ def valid_challenge_payload(): } -def _write_json(path: Path, obj) -> Path: - path.write_text(json.dumps(obj), encoding="utf-8") - return path - - class TestParseUvarint: def test_single_byte_value(self): @@ -107,6 +210,10 @@ def test_two_byte_continuation(self): value, used = _parse_uvarint(bytes([0x80, 0x01])) assert value == 128 and used == 2 + def test_rsa_multicodec(self): + value, used = _parse_uvarint(RSA_MULTICODEC_PREFIX) + assert value == 0x1205 and used == 2 + def test_consumes_only_the_varint_bytes(self): value, used = _parse_uvarint(bytes([0x7F, 0xAA, 0xBB])) assert value == 0x7F and used == 1 @@ -178,30 +285,167 @@ def test_non_multibase_input_raises(self): -class TestExtractEd25519PubFromDidKey: - def test_returns_32_bytes(self): - pub = _extract_ed25519_pub_from_did_key(ED25519_DID_KEY) - assert isinstance(pub, bytes) and len(pub) == 32 +class TestLoadPrivateKey: + def test_pkcs8_pem_bytes_is_rsa(self, rsa_keypair): + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + key = _load_private_key_bytes(rsa_keypair["pem_pkcs8"]) + assert isinstance(key, RSAPrivateKey) + + def test_pkcs1_pem_bytes_is_rsa(self, rsa_keypair): + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + key = _load_private_key_bytes(rsa_keypair["pem_pkcs1"]) + assert isinstance(key, RSAPrivateKey) + + def test_der_bytes_is_rsa(self, rsa_keypair): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + der = rsa_keypair["key"].private_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + assert isinstance(_load_private_key_bytes(der), RSAPrivateKey) + + def test_ed25519_pem_bytes_is_ed25519(self): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + pem = Ed25519PrivateKey.generate().private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + assert isinstance(_load_private_key_bytes(pem), Ed25519PrivateKey) + + def test_encrypted_pem_raises(self, rsa_keypair): + from cryptography.hazmat.primitives import serialization + pem = rsa_keypair["key"].private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.BestAvailableEncryption(b"secret"), + ) + with pytest.raises(ValueError, match="could not be loaded"): + _load_private_key_bytes(pem) + + def test_unsupported_key_type_raises(self): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec + pem = ec.generate_private_key(ec.SECP256R1()).private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + with pytest.raises(ValueError, match="Unsupported private key type"): + _load_private_key_bytes(pem) + + def test_text_with_real_newlines(self, rsa_keypair): + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + key = _load_private_key_from_text(rsa_keypair["pem_pkcs8"].decode()) + assert isinstance(key, RSAPrivateKey) + + def test_text_with_literal_backslash_n(self, rsa_keypair): + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + text = rsa_keypair["pem_pkcs8"].decode().replace("\n", "\\n") + assert isinstance(_load_private_key_from_text(text), RSAPrivateKey) + + def test_text_bare_base64_body(self, rsa_keypair): + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + body = "".join( + line + for line in rsa_keypair["pem_pkcs8"].decode().splitlines() + if "-----" not in line + ) + assert isinstance(_load_private_key_from_text(body), RSAPrivateKey) + + def test_text_garbage_raises(self): + with pytest.raises(ValueError, match="neither PEM nor base64"): + _load_private_key_from_text("this is not a key!") + + +class TestLoadSigningKey: + def test_multibase_is_eddsa(self, ed25519_keypair): + priv, _, _ = ed25519_keypair + _, alg = _load_signing_key(priv, None, None) + assert alg == "EdDSA" + + def test_rsa_file_is_rs256(self, rsa_keypair, tmp_path): + path = tmp_path / "rsa.pem" + path.write_bytes(rsa_keypair["pem_pkcs8"]) + _, alg = _load_signing_key(None, str(path), None) + assert alg == "RS256" + + def test_rsa_text_is_rs256(self, rsa_keypair): + _, alg = _load_signing_key(None, None, rsa_keypair["pem_pkcs1"].decode()) + assert alg == "RS256" + + def test_small_rsa_key_rejected(self, tmp_path): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import rsa + small = rsa.generate_private_key(public_exponent=65537, key_size=1024) + path = tmp_path / "small.pem" + path.write_bytes( + small.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + with pytest.raises(click.ClickException, match="2048"): + _load_signing_key(None, str(path), None) + + def test_no_key_option_rejected(self): + with pytest.raises(click.ClickException, match="exactly one"): + _load_signing_key(None, None, None) + + def test_two_key_options_rejected(self, ed25519_keypair, rsa_keypair): + priv, _, _ = ed25519_keypair + with pytest.raises(click.ClickException, match="exactly one"): + _load_signing_key(priv, None, rsa_keypair["pem_pkcs8"].decode()) + + def test_bad_multibase_raises(self): + with pytest.raises(click.ClickException, match="Could not load private key"): + _load_signing_key("zNOT-A-REAL-KEY", None, None) + + + +class TestPublicKeyFromDidKey: + def test_ed25519_returns_32_bytes(self): + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + pub = _public_key_from_did_key(ED25519_DID_KEY) + assert isinstance(pub, Ed25519PublicKey) + assert len(_raw_ed25519(pub)) == 32 def test_accepts_kid_with_fragment(self): - from_base = _extract_ed25519_pub_from_did_key(ED25519_DID_KEY) - from_kid = _extract_ed25519_pub_from_did_key(ED25519_KID) + from_base = _raw_ed25519(_public_key_from_did_key(ED25519_DID_KEY)) + from_kid = _raw_ed25519(_public_key_from_did_key(ED25519_KID)) assert from_base == from_kid def test_strips_whitespace(self): - pub = _extract_ed25519_pub_from_did_key(" " + ED25519_DID_KEY + " ") - assert len(pub) == 32 + pub = _public_key_from_did_key(" " + ED25519_DID_KEY + " ") + assert len(_raw_ed25519(pub)) == 32 + + def test_rsa_did_key(self, rsa_keypair): + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey + pub = _public_key_from_did_key(rsa_keypair["did_key"]) + assert isinstance(pub, RSAPublicKey) + assert pub.public_numbers() == rsa_keypair["key"].public_key().public_numbers() + + def test_rsa_kid_with_fragment(self, rsa_keypair): + pub = _public_key_from_did_key(rsa_keypair["kid"]) + assert pub.public_numbers() == rsa_keypair["key"].public_key().public_numbers() + + def test_rsa_did_key_starts_with_z4mx(self, rsa_keypair): + assert rsa_keypair["did_key"].startswith("did:key:z4MX") def test_non_did_key_raises(self): with pytest.raises(ValueError, match="did:key"): - _extract_ed25519_pub_from_did_key("did:web:example.com") + _public_key_from_did_key("did:web:example.com") - def test_invalid_multicodec_raises(self): + def test_unsupported_multicodec_raises(self): import base58 - raw = bytes([0x80, 0x24]) + (b"\x00" * 32) + raw = bytes([0x80, 0x24]) + (b"\x00" * 32) # 0x1200 (P-256), not supported here bad_did = "did:key:z" + base58.b58encode(raw).decode() - with pytest.raises(ValueError, match="Invalid did:key"): - _extract_ed25519_pub_from_did_key(bad_did) + with pytest.raises(ValueError, match="Unsupported did:key multicodec"): + _public_key_from_did_key(bad_did) class TestDidWebToUrl: @@ -230,14 +474,7 @@ def test_non_did_web_raises(self): class TestFetchDidJson: def test_returns_parsed_json_on_200(self): doc = {"id": "did:web:example.com", "verificationMethod": []} - mock_resp = MagicMock() - mock_resp.json.return_value = doc - mock_resp.raise_for_status = MagicMock() - - with patch( - "ce.commands.iir_sign_challenge.requests.get", - return_value=mock_resp, - ) as mock_get: + with _mock_did_json(doc) as mock_get: result = _fetch_did_json("did:web:example.com") assert result == doc @@ -249,34 +486,17 @@ def test_http_error_propagates(self): mock_resp = MagicMock() mock_resp.raise_for_status.side_effect = requests.HTTPError("404 Not Found") - with patch( - "ce.commands.iir_sign_challenge.requests.get", - return_value=mock_resp, - ): + with patch(f"{MODULE}.requests.get", return_value=mock_resp): with pytest.raises(requests.HTTPError): _fetch_did_json("did:web:example.com") def test_non_object_response_raises(self): - mock_resp = MagicMock() - mock_resp.json.return_value = ["not", "an", "object"] - mock_resp.raise_for_status = MagicMock() - - with patch( - "ce.commands.iir_sign_challenge.requests.get", - return_value=mock_resp, - ): + with _mock_did_json(["not", "an", "object"]): with pytest.raises(ValueError, match="must be a JSON object"): _fetch_did_json("did:web:example.com") def test_passes_through_path_segments_in_url(self): - mock_resp = MagicMock() - mock_resp.json.return_value = {"verificationMethod": []} - mock_resp.raise_for_status = MagicMock() - - with patch( - "ce.commands.iir_sign_challenge.requests.get", - return_value=mock_resp, - ) as mock_get: + with _mock_did_json({"verificationMethod": []}) as mock_get: _fetch_did_json("did:web:example.com:users:alice") args, _ = mock_get.call_args @@ -297,6 +517,20 @@ def _doc(self, did, vm_id, pub_multibase): ], } + def _rsa_doc(self, did, vm_id, jwk, vm_type="JsonWebKey2020"): + return { + "id": did, + "verificationMethod": [ + { + "id": vm_id, + "type": vm_type, + "controller": did, + "publicKeyJwk": jwk, + } + ], + "authentication": [vm_id], + } + def _did_web_keypair(self): """Generate a real Ed25519 public key for did:web tests.""" import base58 @@ -318,7 +552,7 @@ def test_finds_key_by_absolute_kid(self): doc = self._doc(did, kid, pub_mb) result = _public_key_from_did_doc(kid=kid, did_doc=doc) - assert result == pub + assert _raw_ed25519(result) == pub def test_finds_key_when_vm_id_is_relative(self): pub, pub_mb = self._did_web_keypair() @@ -327,18 +561,18 @@ def test_finds_key_when_vm_id_is_relative(self): doc = self._doc(did, "#key-1", pub_mb) result = _public_key_from_did_doc(kid=kid, did_doc=doc) - assert result == pub + assert _raw_ed25519(result) == pub def test_raw_32_byte_pub_multibase_accepted(self): import base58 - pub = b"\x05" * 32 + pub, _ = self._did_web_keypair() pub_mb = "z" + base58.b58encode(pub).decode() did = "did:web:example.com" kid = f"{did}#key-1" doc = self._doc(did, kid, pub_mb) result = _public_key_from_did_doc(kid=kid, did_doc=doc) - assert result == pub + assert _raw_ed25519(result) == pub def test_kid_not_in_doc_raises(self): _, pub_mb = self._did_web_keypair() @@ -365,7 +599,7 @@ def test_skips_non_dict_entries(self): {"id": kid, "publicKeyMultibase": pub_mb}, ], } - assert _public_key_from_did_doc(kid=kid, did_doc=doc) == pub + assert _raw_ed25519(_public_key_from_did_doc(kid=kid, did_doc=doc)) == pub def test_skips_entries_without_id(self): pub, pub_mb = self._did_web_keypair() @@ -374,26 +608,26 @@ def test_skips_entries_without_id(self): doc = { "id": did, "verificationMethod": [ - {"publicKeyMultibase": "zSomething"}, + {"publicKeyMultibase": "zSomething"}, {"id": kid, "publicKeyMultibase": pub_mb}, ], } - assert _public_key_from_did_doc(kid=kid, did_doc=doc) == pub + assert _raw_ed25519(_public_key_from_did_doc(kid=kid, did_doc=doc)) == pub def test_invalid_public_key_multibase_raises(self): did = "did:web:example.com" kid = f"{did}#key-1" doc = self._doc(did, kid, "NOT-Z-PREFIXED") - with pytest.raises(ValueError, match="Invalid publicKeyMultibase"): + with pytest.raises(ValueError, match="publicKeyMultibase"): _public_key_from_did_doc(kid=kid, did_doc=doc) - def test_missing_public_key_multibase_raises(self): + def test_missing_public_key_raises(self): did = "did:web:example.com" kid = f"{did}#key-1" doc = {"id": did, "verificationMethod": [{"id": kid}]} - with pytest.raises(ValueError, match="Invalid publicKeyMultibase"): + with pytest.raises(ValueError, match="neither an RSA publicKeyJwk"): _public_key_from_did_doc(kid=kid, did_doc=doc) def test_unrecognized_pub_key_encoding_raises(self): @@ -407,11 +641,70 @@ def test_unrecognized_pub_key_encoding_raises(self): with pytest.raises(ValueError, match="Ed25519"): _public_key_from_did_doc(kid=kid, did_doc=doc) + def test_rsa_json_web_key_2020(self, rsa_keypair): + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey + public_key = rsa_keypair["key"].public_key() + did = "did:web:example.com" + kid = f"{did}#key-2" + doc = self._rsa_doc(did, kid, _rsa_jwk(public_key, alg="RS256", use="sig")) + + result = _public_key_from_did_doc(kid=kid, did_doc=doc) + assert isinstance(result, RSAPublicKey) + assert result.public_numbers() == public_key.public_numbers() + + def test_rsa_relative_vm_id(self, rsa_keypair): + public_key = rsa_keypair["key"].public_key() + did = "did:web:example.com" + doc = self._rsa_doc(did, "#key-2", _rsa_jwk(public_key)) + + result = _public_key_from_did_doc(kid=f"{did}#key-2", did_doc=doc) + assert result.public_numbers() == public_key.public_numbers() + + def test_rsa_wrong_vm_type_raises(self, rsa_keypair): + did = "did:web:example.com" + kid = f"{did}#key-2" + doc = self._rsa_doc( + did, + kid, + _rsa_jwk(rsa_keypair["key"].public_key()), + vm_type="RsaVerificationKey2018", + ) + + with pytest.raises(ValueError, match="JsonWebKey2020"): + _public_key_from_did_doc(kid=kid, did_doc=doc) + + def test_rsa_jwk_with_private_part_raises(self, rsa_keypair): + did = "did:web:example.com" + kid = f"{did}#key-2" + doc = self._rsa_doc(did, kid, _rsa_jwk(rsa_keypair["key"].public_key(), d="AAAA")) + + with pytest.raises(ValueError, match="private key material"): + _public_key_from_did_doc(kid=kid, did_doc=doc) + + def test_picks_rsa_key_from_mixed_doc(self, rsa_keypair): + _, ed_mb = self._did_web_keypair() + public_key = rsa_keypair["key"].public_key() + did = "did:web:example.com" + doc = { + "id": did, + "verificationMethod": [ + {"id": f"{did}#key-1", "type": "Ed25519VerificationKey2020", "publicKeyMultibase": ed_mb}, + {"id": f"{did}#key-2", "type": "JsonWebKey2020", "publicKeyJwk": _rsa_jwk(public_key)}, + ], + } + + result = _public_key_from_did_doc(kid=f"{did}#key-2", did_doc=doc) + assert result.public_numbers() == public_key.public_numbers() -class TestResolvePublicKeyBytesForKid: + +class TestResolvePublicKeyForKid: def test_did_key_path(self): - pub = _resolve_public_key_bytes_for_kid(ED25519_KID) - assert len(pub) == 32 + pub = _resolve_public_key_for_kid(ED25519_KID) + assert len(_raw_ed25519(pub)) == 32 + + def test_rsa_did_key_path(self, rsa_keypair): + pub = _resolve_public_key_for_kid(rsa_keypair["kid"]) + assert pub.public_numbers() == rsa_keypair["key"].public_key().public_numbers() def test_did_web_path_fetches_doc(self): import base58 @@ -432,86 +725,71 @@ def test_did_web_path_fetches_doc(self): "verificationMethod": [{"id": kid, "publicKeyMultibase": pub_mb}], } - mock_resp = MagicMock() - mock_resp.json.return_value = doc - mock_resp.raise_for_status = MagicMock() - with patch( - "ce.commands.iir_sign_challenge.requests.get", - return_value=mock_resp, - ): - result = _resolve_public_key_bytes_for_kid(kid) - assert result == pub + with _mock_did_json(doc): + result = _resolve_public_key_for_kid(kid) + assert _raw_ed25519(result) == pub def test_unsupported_did_method_raises(self): with pytest.raises(ValueError, match="Unsupported DID method"): - _resolve_public_key_bytes_for_kid("did:ethr:0x123#key-1") + _resolve_public_key_for_kid("did:ethr:0x123#key-1") class TestSignPayload: - def test_returns_three_part_jwt_string(self, ed25519_keypair, valid_challenge_payload): - priv, _, kid = ed25519_keypair - token = _sign_payload(priv, kid, valid_challenge_payload) + def test_returns_three_part_jwt_string(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): + _, _, kid = ed25519_keypair + token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) assert isinstance(token, str) assert token.count(".") == 2 - def test_header_includes_alg_typ_kid(self, ed25519_keypair, valid_challenge_payload): - priv, _, kid = ed25519_keypair - token = _sign_payload(priv, kid, valid_challenge_payload) - header_b64 = token.split(".")[0] - padded = header_b64 + "=" * (-len(header_b64) % 4) - header = json.loads(base64.urlsafe_b64decode(padded)) + def test_header_includes_alg_typ_kid(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): + _, _, kid = ed25519_keypair + token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) + header = _decode_segment(token, 0) assert header["alg"] == "EdDSA" assert header["typ"] == "JWT" assert header["kid"] == kid - def test_payload_round_trips(self, ed25519_keypair, valid_challenge_payload): - priv, _, kid = ed25519_keypair - token = _sign_payload(priv, kid, valid_challenge_payload) - payload_b64 = token.split(".")[1] - padded = payload_b64 + "=" * (-len(payload_b64) % 4) - decoded = json.loads(base64.urlsafe_b64decode(padded)) - assert decoded == valid_challenge_payload + def test_payload_round_trips(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): + _, _, kid = ed25519_keypair + token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) + assert _decode_segment(token, 1) == valid_challenge_payload + + def test_rs256_header(self, rsa_keypair, valid_challenge_payload): + payload = dict(valid_challenge_payload, did=rsa_keypair["kid"]) + token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], payload) + header = _decode_segment(token, 0) + assert header["alg"] == "RS256" + assert header["typ"] == "JWT" + assert header["kid"] == rsa_keypair["kid"] - def test_bad_private_key_raises(self, valid_challenge_payload): - with pytest.raises(ValueError): - _sign_payload("zNOT-A-REAL-KEY", ED25519_KID, valid_challenge_payload) + def test_rs256_signature_is_modulus_length(self, rsa_keypair, valid_challenge_payload): + token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) + segment = token.split(".")[2] + signature = base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)) + assert len(signature) == 256 # 2048-bit key -class TestVerifySignatureOnly: - def test_valid_signature_returns_none(self, ed25519_keypair, valid_challenge_payload): - from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey - priv, _, kid = ed25519_keypair - token = _sign_payload(priv, kid, valid_challenge_payload) - pub_bytes = _extract_ed25519_pub_from_did_key(kid) - pub_key = Ed25519PublicKey.from_public_bytes(pub_bytes) - - _verify_signature_only(token, pub_key) +class TestVerifySignatureOnly: + def test_valid_signature_returns_none(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): + _, _, kid = ed25519_keypair + token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) + _verify_signature_only(token, _public_key_from_did_key(kid), "EdDSA") - def test_tampered_signature_raises(self, ed25519_keypair, valid_challenge_payload): + def test_tampered_signature_raises(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): import jwt - from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey - - priv, _, kid = ed25519_keypair - token = _sign_payload(priv, kid, valid_challenge_payload) - parts = token.split(".") - first = parts[2][0] - parts[2] = ("B" if first != "B" else "C") + parts[2][1:] - tampered = ".".join(parts) - pub_bytes = _extract_ed25519_pub_from_did_key(kid) - pub_key = Ed25519PublicKey.from_public_bytes(pub_bytes) + _, _, kid = ed25519_keypair + token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) with pytest.raises(jwt.exceptions.InvalidSignatureError): - _verify_signature_only(tampered, pub_key) + _verify_signature_only(_tamper_signature(token), _public_key_from_did_key(kid), "EdDSA") - def test_does_not_check_expiry(self, ed25519_keypair): + def test_does_not_check_expiry(self, ed25519_keypair, ed25519_signing_key): """Even with iat/exp in the past, verification must pass — the function exists specifically to verify the signature only.""" - from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey - - priv, _, kid = ed25519_keypair + _, _, kid = ed25519_keypair payload = { "did": ED25519_DID_KEY, "challenge": CHALLENGE_UUID, @@ -519,34 +797,160 @@ def test_does_not_check_expiry(self, ed25519_keypair): "iat": 1, "exp": 2, } - token = _sign_payload(priv, kid, payload) - pub_bytes = _extract_ed25519_pub_from_did_key(kid) - pub_key = Ed25519PublicKey.from_public_bytes(pub_bytes) + token = _sign_payload(ed25519_signing_key, "EdDSA", kid, payload) + _verify_signature_only(token, _public_key_from_did_key(kid), "EdDSA") - _verify_signature_only(token, pub_key) + def test_rs256_valid(self, rsa_keypair, valid_challenge_payload): + token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) + _verify_signature_only(token, _public_key_from_did_key(rsa_keypair["kid"]), "RS256") + + def test_rs256_tampered_raises(self, rsa_keypair, valid_challenge_payload): + import jwt + + token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) + with pytest.raises(jwt.exceptions.InvalidSignatureError): + _verify_signature_only( + _tamper_signature(token), + _public_key_from_did_key(rsa_keypair["kid"]), + "RS256", + ) + + def test_rs256_token_rejected_when_only_eddsa_allowed(self, rsa_keypair, valid_challenge_payload): + import jwt + + token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) + with pytest.raises(jwt.PyJWTError): + _verify_signature_only(token, _public_key_from_did_key(rsa_keypair["kid"]), "EdDSA") class TestAssertSignatureVerifiable: - def test_passes_for_valid_token(self, ed25519_keypair, valid_challenge_payload): - priv, _, kid = ed25519_keypair - token = _sign_payload(priv, kid, valid_challenge_payload) - _assert_signature_verifiable(token, kid) + def test_passes_for_valid_token(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): + _, _, kid = ed25519_keypair + token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) + _assert_signature_verifiable(token, kid, "EdDSA") def test_tampered_token_raises_click_exception( - self, ed25519_keypair, valid_challenge_payload + self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload ): - priv, _, kid = ed25519_keypair - token = _sign_payload(priv, kid, valid_challenge_payload) - parts = token.split(".") - first = parts[2][0] - parts[2] = ("B" if first != "B" else "C") + parts[2][1:] - tampered = ".".join(parts) + _, _, kid = ed25519_keypair + token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) with pytest.raises(click.ClickException, match="Signature verification failed"): - _assert_signature_verifiable(tampered, kid) + _assert_signature_verifiable(_tamper_signature(token), kid, "EdDSA") def test_malformed_token_raises_click_exception(self, ed25519_keypair): _, _, kid = ed25519_keypair with pytest.raises(click.ClickException, match="JWT verification error"): - _assert_signature_verifiable("not.a.real.jwt", kid) + _assert_signature_verifiable("not.a.real.jwt", kid, "EdDSA") + + def test_rs256_passes_for_valid_token(self, rsa_keypair, valid_challenge_payload): + token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) + _assert_signature_verifiable(token, rsa_keypair["kid"], "RS256") + + def test_rs256_against_ed25519_did_raises(self, rsa_keypair, valid_challenge_payload): + token = _sign_payload(rsa_keypair["key"], "RS256", ED25519_KID, valid_challenge_payload) + with pytest.raises(click.ClickException, match="resolves to an Ed25519 key"): + _assert_signature_verifiable(token, ED25519_KID, "RS256") + + def test_eddsa_against_rsa_did_raises(self, ed25519_signing_key, rsa_keypair, valid_challenge_payload): + token = _sign_payload(ed25519_signing_key, "EdDSA", rsa_keypair["kid"], valid_challenge_payload) + with pytest.raises(click.ClickException, match="resolves to an RSA key"): + _assert_signature_verifiable(token, rsa_keypair["kid"], "EdDSA") + + def test_rs256_did_web(self, rsa_keypair, valid_challenge_payload): + did = "did:web:example.com" + kid = f"{did}#key-2" + doc = { + "id": did, + "verificationMethod": [ + { + "id": kid, + "type": "JsonWebKey2020", + "publicKeyJwk": _rsa_jwk(rsa_keypair["key"].public_key(), alg="RS256"), + } + ], + "authentication": [kid], + } + token = _sign_payload(rsa_keypair["key"], "RS256", kid, valid_challenge_payload) + + with _mock_did_json(doc): + _assert_signature_verifiable(token, kid, "RS256") + + + +class TestSignCommand: + """End-to-end through the click command.""" + + def _run(self, args): + result = CliRunner().invoke(sign_individual_challenge, args) + return result.exit_code, result.output + + def test_rsa_key_file_signs_rs256(self, rsa_keypair, tmp_path, valid_challenge_payload): + key_path = tmp_path / "rsa.pem" + key_path.write_bytes(rsa_keypair["pem_pkcs8"]) + challenge = _write_json( + tmp_path / "challenge.json", + dict(valid_challenge_payload, did=rsa_keypair["kid"]), + ) + out_path = tmp_path / "signed.jwt" + + code, output = self._run( + ["--private-key-file", str(key_path), "--challenge-file", str(challenge), "-o", str(out_path)] + ) + + assert code == 0, output + token = out_path.read_text(encoding="utf-8") + header = _decode_segment(token, 0) + assert header["alg"] == "RS256" + assert header["kid"] == rsa_keypair["kid"] + + def test_rsa_key_pem_text_signs_rs256(self, rsa_keypair, tmp_path, valid_challenge_payload): + challenge = _write_json( + tmp_path / "challenge.json", + dict(valid_challenge_payload, did=rsa_keypair["kid"]), + ) + + code, output = self._run( + ["--private-key-pem", rsa_keypair["pem_pkcs8"].decode(), "--challenge-file", str(challenge)] + ) + + assert code == 0, output + + def test_ed25519_multibase_still_signs_eddsa(self, ed25519_keypair, tmp_path, valid_challenge_payload): + priv, _, kid = ed25519_keypair + challenge = _write_json(tmp_path / "challenge.json", dict(valid_challenge_payload, did=kid)) + out_path = tmp_path / "signed.jwt" + + code, output = self._run( + ["--private-key", priv, "--challenge-file", str(challenge), "-o", str(out_path)] + ) + + assert code == 0, output + assert _decode_segment(out_path.read_text(encoding="utf-8"), 0)["alg"] == "EdDSA" + + def test_two_key_options_fail(self, ed25519_keypair, rsa_keypair, tmp_path, valid_challenge_payload): + priv, _, _ = ed25519_keypair + challenge = _write_json(tmp_path / "challenge.json", valid_challenge_payload) + + code, output = self._run( + [ + "--private-key", priv, + "--private-key-pem", rsa_keypair["pem_pkcs8"].decode(), + "--challenge-file", str(challenge), + ] + ) + + assert code != 0 + assert "exactly one" in output + + def test_missing_required_field_fails(self, rsa_keypair, tmp_path, valid_challenge_payload): + payload = dict(valid_challenge_payload, did=rsa_keypair["kid"]) + del payload["exp"] + challenge = _write_json(tmp_path / "challenge.json", payload) + + code, output = self._run( + ["--private-key-pem", rsa_keypair["pem_pkcs8"].decode(), "--challenge-file", str(challenge)] + ) + assert code != 0 + assert "exp" in output \ No newline at end of file From cf7e31a7a19a2186e2161b241afd64fef8f11e52 Mon Sep 17 00:00:00 2001 From: Sneha Edula Date: Thu, 19 Nov 2026 19:22:11 -0500 Subject: [PATCH 2/6] update --- ce/commands/iir.py | 9 +- ce/commands/iir_sign_challenge.py | 279 ++-------- ce/commands/iir_sign_challenge_rs256.py | 465 +++++++++++++++++ tests/test_iir_sign_challenge_rs256.py | 604 +++++++++++++++++++++ tests/test_sign_single_challenge.py | 668 +++++------------------- 5 files changed, 1264 insertions(+), 761 deletions(-) create mode 100644 ce/commands/iir_sign_challenge_rs256.py create mode 100644 tests/test_iir_sign_challenge_rs256.py diff --git a/ce/commands/iir.py b/ce/commands/iir.py index 60428a6..5f6ccbe 100644 --- a/ce/commands/iir.py +++ b/ce/commands/iir.py @@ -1,6 +1,7 @@ """IIR command group: - ce iir challenge sign # single challenge + ce iir challenge sign # single challenge (Ed25519, EdDSA) + ce iir challenge sign-rs256 # single challenge (RSA, RS256) ce iir challenge bulk-sign # bulk DID challenge signing ce iir issuer-did publish # publish signed challenges to IIR """ @@ -14,6 +15,7 @@ from rich.console import Console from ce.commands.iir_sign_challenge import sign_individual_challenge +from ce.commands.iir_sign_challenge_rs256 import sign_rs256_challenge from ce.auth.token_manager import require_login from ce.config.context import require_environment @@ -49,6 +51,11 @@ def issuer_did_group() -> None: challenge_group.add_command(sign_individual_challenge, name="sign") +# ce iir challenge sign-rs256 (single, RSA) + +challenge_group.add_command(sign_rs256_challenge, name="sign-rs256") + + # ce iir challenge bulk-sign @challenge_group.command("bulk-sign") diff --git a/ce/commands/iir_sign_challenge.py b/ce/commands/iir_sign_challenge.py index 3d1cb78..3b79521 100644 --- a/ce/commands/iir_sign_challenge.py +++ b/ce/commands/iir_sign_challenge.py @@ -1,52 +1,28 @@ """`ce iir challenge sign` - sign and verify a Proof JWT for a single CE challenge. -Reads a challenge JSON file produced by CE, signs it with a private key and -verifies the resulting JWT against the public key resolved from the DID -(did:key or did:web). No login required. - -Supported keys (the algorithm follows the key type): - - Ed25519 -> alg=EdDSA - - RSA -> alg=RS256 (2048 bits or more) +Reads a challenge JSON file produced by CE, signs it with an Ed25519 private key +(alg=EdDSA), and verifies the resulting JWT against the public key resolved from +the DID (did:key or did:web). No login required. """ from __future__ import annotations -import base64 -import binascii import json -from typing import Any, Dict, Tuple, Union +from typing import Any, Dict, Tuple import base58 import click import jwt import requests -from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import ( Ed25519PrivateKey, Ed25519PublicKey, ) -from cryptography.hazmat.primitives.asymmetric.rsa import ( - RSAPrivateKey, - RSAPublicKey, -) -from jwt.algorithms import RSAAlgorithm from rich.console import Console console = Console() err_console = Console(stderr=True) -ALG_EDDSA = "EdDSA" -ALG_RS256 = "RS256" - -MULTICODEC_ED25519_PUB = 0xED -MULTICODEC_ED25519_PRIV = 0x1300 -MULTICODEC_RSA_PUB = 0x1205 - -MIN_RSA_KEY_SIZE_BITS = 2048 - -PrivateKey = Union[Ed25519PrivateKey, RSAPrivateKey] -PublicKey = Union[Ed25519PublicKey, RSAPublicKey] - # Multibase + multicodec helpers @@ -69,7 +45,8 @@ def _decode_multibase_base58btc(z_value: str) -> bytes: -# Private key +# Private key to Ed25519 seed + def _extract_ed25519_seed_from_private_key(private_key_multibase: str) -> bytes: raw = _decode_multibase_base58btc(private_key_multibase.strip()) @@ -82,87 +59,16 @@ def _extract_ed25519_seed_from_private_key(private_key_multibase: str) -> bytes: return raw[2:] code, n = _parse_uvarint(raw) - if code == MULTICODEC_ED25519_PRIV and len(raw) - n == 32: + if code == 0x1300 and len(raw) - n == 32: return raw[n:] raise ValueError("Unrecognized privateKey encoding") -def _load_private_key_bytes(data: bytes) -> PrivateKey: - """Load a PEM or DER private key (PKCS#8, or PKCS#1 for RSA). Unencrypted only.""" - try: - if b"-----BEGIN" in data: - key = serialization.load_pem_private_key(data, password=None) - else: - key = serialization.load_der_private_key(data, password=None) - except TypeError as e: - raise ValueError(f"Private key could not be loaded: {e}") from e - - if isinstance(key, (Ed25519PrivateKey, RSAPrivateKey)): - return key - - raise ValueError( - f"Unsupported private key type {type(key).__name__}. Expected RSA or Ed25519." - ) - - -def _load_private_key_from_text(text: str) -> PrivateKey: - """Pasted key: full PEM (real newlines or literal \\n), or just the base64 body.""" - cleaned = text.strip().replace("\\n", "\n") - - if "-----BEGIN" in cleaned: - return _load_private_key_bytes(cleaned.encode("ascii")) - - body = "".join(cleaned.split()) - try: - der = base64.b64decode(body, validate=True) - except (binascii.Error, ValueError) as e: - raise ValueError("Pasted key is neither PEM nor base64 DER.") from e - - return _load_private_key_bytes(der) - - -def _load_signing_key( - private_key_mb: str | None, - private_key_file: str | None, - private_key_pem: str | None, -) -> Tuple[PrivateKey, str]: - """Return the private key and the JWT alg that goes with it.""" - given = [ - v for v in (private_key_mb, private_key_file, private_key_pem) if v - ] - if len(given) != 1: - raise click.ClickException( - "Give exactly one of --private-key, --private-key-file or --private-key-pem." - ) - - try: - if private_key_mb: - seed = _extract_ed25519_seed_from_private_key(private_key_mb) - key: PrivateKey = Ed25519PrivateKey.from_private_bytes(seed) - elif private_key_file: - with open(private_key_file, "rb") as f: - key = _load_private_key_bytes(f.read()) - else: - key = _load_private_key_from_text(private_key_pem or "") - except ValueError as e: - raise click.ClickException(f"Could not load private key: {e}") - - if isinstance(key, RSAPrivateKey): - if key.key_size < MIN_RSA_KEY_SIZE_BITS: - raise click.ClickException( - f"RSA key is {key.key_size} bits; at least " - f"{MIN_RSA_KEY_SIZE_BITS} bits are required." - ) - return key, ALG_RS256 - - return key, ALG_EDDSA - - # did:key resolution (offline) -def _public_key_from_did_key(did_or_kid: str) -> PublicKey: +def _extract_ed25519_pub_from_did_key(did_or_kid: str) -> bytes: base = did_or_kid.split("#", 1)[0].strip() if not base.startswith("did:key:"): raise ValueError("Not a did:key DID") @@ -171,24 +77,13 @@ def _public_key_from_did_key(did_or_kid: str) -> PublicKey: raw = _decode_multibase_base58btc(mb) if len(raw) == 32: - return Ed25519PublicKey.from_public_bytes(raw) + return raw code, n = _parse_uvarint(raw) - key_bytes = raw[n:] - - if code == MULTICODEC_ED25519_PUB and len(key_bytes) == 32: - return Ed25519PublicKey.from_public_bytes(key_bytes) - - if code == MULTICODEC_RSA_PUB: - # did:key RSA keys are PKCS#1 RSAPublicKey DER. - key = serialization.load_der_public_key(key_bytes) - if isinstance(key, RSAPublicKey): - return key - raise ValueError("did:key RSA payload is not an RSA public key") + if code == 0xED and (len(raw) - n) == 32: + return raw[n:] - raise ValueError( - f"Unsupported did:key multicodec 0x{code:X} (expected Ed25519 or RSA)" - ) + raise ValueError("Invalid did:key encoding (expected Ed25519 public key)") @@ -225,45 +120,7 @@ def _fetch_did_json(did_web_base: str) -> Dict[str, Any]: return doc -def _public_key_from_verification_method(vm: Dict[str, Any]) -> PublicKey: - jwk = vm.get("publicKeyJwk") - if isinstance(jwk, dict) and jwk.get("kty") == "RSA": - if vm.get("type") != "JsonWebKey2020": - raise ValueError( - f"RSA verification method type is '{vm.get('type')}', " - "expected 'JsonWebKey2020'" - ) - if "d" in jwk: - raise ValueError("publicKeyJwk contains private key material ('d')") - - key = RSAAlgorithm.from_jwk(jwk) - if isinstance(key, RSAPublicKey): - return key - raise ValueError("publicKeyJwk is not an RSA public key") - - # Ed25519: publicKeyMultibase. - pkmb = vm.get("publicKeyMultibase") - if not isinstance(pkmb, str) or not pkmb.startswith("z"): - raise ValueError( - "Verification method has neither an RSA publicKeyJwk " - "nor a valid publicKeyMultibase" - ) - - raw = _decode_multibase_base58btc(pkmb) - - if len(raw) == 32: - return Ed25519PublicKey.from_public_bytes(raw) - - code, n = _parse_uvarint(raw) - if code == MULTICODEC_ED25519_PUB and (len(raw) - n) == 32: - return Ed25519PublicKey.from_public_bytes(raw[n:]) - - raise ValueError( - "publicKeyMultibase is not an Ed25519 key encoding we recognize" - ) - - -def _public_key_from_did_doc(*, kid: str, did_doc: Dict[str, Any]) -> PublicKey: +def _public_key_from_did_doc(*, kid: str, did_doc: Dict[str, Any]) -> bytes: did_base = kid.split("#", 1)[0].strip() kid = kid.strip() @@ -284,16 +141,31 @@ def normalize(vm_id: str) -> str: if normalize(vm_id) != kid: continue - return _public_key_from_verification_method(vm) + pkmb = vm.get("publicKeyMultibase") + if not isinstance(pkmb, str) or not pkmb.startswith("z"): + raise ValueError("Invalid publicKeyMultibase") + + raw = _decode_multibase_base58btc(pkmb) + + if len(raw) == 32: + return raw + + code, n = _parse_uvarint(raw) + if code == 0xED and (len(raw) - n) == 32: + return raw[n:] + + raise ValueError( + "publicKeyMultibase is not an Ed25519 key encoding we recognize" + ) raise ValueError(f"kid not found in did.json: {kid}") -def _resolve_public_key_for_kid(kid: str) -> PublicKey: +def _resolve_public_key_bytes_for_kid(kid: str) -> bytes: base = kid.split("#", 1)[0].strip() if base.startswith("did:key:"): - return _public_key_from_did_key(kid) + return _extract_ed25519_pub_from_did_key(kid) if base.startswith("did:web:"): did_doc = _fetch_did_json(base) @@ -305,18 +177,16 @@ def _resolve_public_key_for_kid(kid: str) -> PublicKey: # Signing + verification -def _sign_payload( - private_key: PrivateKey, - alg: str, - kid: str, - payload_obj: Dict[str, Any], -) -> str: - headers = {"typ": "JWT", "alg": alg, "kid": kid} +def _sign_payload(private_key_mb: str, kid: str, payload_obj: Dict[str, Any]) -> str: + seed = _extract_ed25519_seed_from_private_key(private_key_mb) + private_key = Ed25519PrivateKey.from_private_bytes(seed) + + headers = {"typ": "JWT", "alg": "EdDSA", "kid": kid} token = jwt.encode( payload=payload_obj, key=private_key, - algorithm=alg, + algorithm="EdDSA", headers=headers, ) @@ -326,11 +196,11 @@ def _sign_payload( return token -def _verify_signature_only(token: str, public_key: PublicKey, alg: str) -> None: +def _verify_signature_only(token: str, public_key: Ed25519PublicKey) -> None: jwt.decode( token, key=public_key, - algorithms=[alg], + algorithms=["EdDSA"], options={ "verify_signature": True, "verify_aud": False, @@ -342,21 +212,12 @@ def _verify_signature_only(token: str, public_key: PublicKey, alg: str) -> None: ) -def _assert_signature_verifiable(token: str, kid: str, alg: str) -> None: - pub_key = _resolve_public_key_for_kid(kid) - - if alg == ALG_RS256 and not isinstance(pub_key, RSAPublicKey): - raise click.ClickException( - "Signed with an RSA key, but the DID resolves to an Ed25519 key." - ) - - if alg == ALG_EDDSA and not isinstance(pub_key, Ed25519PublicKey): - raise click.ClickException( - "Signed with an Ed25519 key, but the DID resolves to an RSA key." - ) +def _assert_signature_verifiable(token: str, kid: str) -> None: + pub_bytes = _resolve_public_key_bytes_for_kid(kid) + pub_key = Ed25519PublicKey.from_public_bytes(pub_bytes) try: - _verify_signature_only(token, pub_key, alg) + _verify_signature_only(token, pub_key) except jwt.exceptions.InvalidSignatureError as e: raise click.ClickException( "Signature verification failed (token does not match DID public key)." @@ -365,7 +226,7 @@ def _assert_signature_verifiable(token: str, kid: str, alg: str) -> None: raise click.ClickException(f"JWT verification error: {e}") from e err_console.print( - f"[green]Signature verification: OK[/green] ({alg}, matches DID public key)" + "[green]Signature verification: OK[/green] (matches DID public key)" ) @@ -376,28 +237,10 @@ def _assert_signature_verifiable(token: str, kid: str, alg: str) -> None: @click.option( "--private-key", "private_key", - default=None, + required=True, metavar="MULTIBASE", help="Ed25519 private seed (multibase base58btc, starts with 'z').", ) -@click.option( - "--private-key-file", - "private_key_file", - default=None, - type=click.Path(exists=True, dir_okay=False, readable=True), - metavar="PATH", - help="PEM or DER private key file (RSA -> RS256, Ed25519 -> EdDSA). Unencrypted.", -) -@click.option( - "--private-key-pem", - "private_key_pem", - default=None, - metavar="TEXT", - help=( - "Pasted private key: full PEM (newlines or literal \\n) or just the " - "base64 body. RSA -> RS256, Ed25519 -> EdDSA." - ), -) @click.option( "--challenge-file", "challenge_file", @@ -415,35 +258,23 @@ def _assert_signature_verifiable(token: str, kid: str, alg: str) -> None: help="Write JWT to this file (otherwise printed to stdout).", ) def sign_individual_challenge( - private_key: str | None, - private_key_file: str | None, - private_key_pem: str | None, + private_key: str, challenge_file: str, out_path: str | None, ) -> None: - """Sign a single CE challenge JSON file and produce a Proof JWT. + """Sign a single CE challenge JSON file and produce a Proof JWT (EdDSA/Ed25519). \b - The algorithm follows the key: Ed25519 -> EdDSA, RSA -> RS256. - Give exactly one of --private-key, --private-key-file, --private-key-pem. The challenge JSON must include: did, challenge, aud, iat, exp. Signature verification uses did:key (offline) or did:web (HTTPS). \b - Examples: - ce iir challenge sign --private-key zABC... \\ - --challenge-file challenge.json -o signed-challenge.jwt - - \b - ce iir challenge sign --private-key-file rsa-key.pem \\ - --challenge-file challenge.json -o signed-challenge.jwt + Example: + ce iir challenge sign \\ + --private-key zABC... \\ + --challenge-file challenge.json \\ + --output signed-challenge.jwt """ - signing_key, alg = _load_signing_key( - private_key, - private_key_file, - private_key_pem, - ) - try: with open(challenge_file, "r", encoding="utf-8") as f: payload_obj = json.load(f) @@ -469,12 +300,12 @@ def sign_individual_challenge( kid = did_value.strip() try: - token = _sign_payload(signing_key, alg, kid, payload_obj) - except (ValueError, jwt.PyJWTError) as e: + token = _sign_payload(private_key, kid, payload_obj) + except ValueError as e: raise click.ClickException(f"Signing failed: {e}") try: - _assert_signature_verifiable(token, kid, alg) + _assert_signature_verifiable(token, kid) except requests.RequestException as e: raise click.ClickException(f"Failed to fetch did.json: {e}") except ValueError as e: diff --git a/ce/commands/iir_sign_challenge_rs256.py b/ce/commands/iir_sign_challenge_rs256.py new file mode 100644 index 0000000..3c956ce --- /dev/null +++ b/ce/commands/iir_sign_challenge_rs256.py @@ -0,0 +1,465 @@ +"""`ce iir challenge sign-rs256` - sign and verify a Proof JWT for a CE challenge with RSA (RS256). + +Reads a challenge JSON file produced by CE, signs it with an RSA private key +(alg=RS256), and verifies the resulting JWT against the public key resolved from +the DID (did:key or did:web). No login required. + +Ed25519 keys are handled by `ce iir challenge sign` (alg=EdDSA). + +Key resolution: + - did:key : multicodec 0x1205 (rsa-pub), PKCS#1 RSAPublicKey DER, base58btc. + https://github.com/multiformats/multicodec + - did:web : a JsonWebKey2020 verification method with an RSA publicKeyJwk, + listed under "authentication" (the same rules the IIR API applies). +""" + +from __future__ import annotations + +import base64 +import binascii +import json +from typing import Any, Dict, Tuple +from urllib.parse import quote, unquote + +import base58 +import click +import jwt +import requests +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey +from jwt.algorithms import RSAAlgorithm +from rich.console import Console + +console = Console() +err_console = Console(stderr=True) + +ALG = "RS256" +MULTICODEC_RSA_PUB = 0x1205 +MIN_RSA_KEY_SIZE_BITS = 2048 +VERIFICATION_METHOD_TYPE = "JsonWebKey2020" + + +ACCEPTED_RELATIONSHIPS = ("authentication",) + +def _parse_uvarint(data: bytes) -> Tuple[int, int]: + x = 0 + s = 0 + for i, b in enumerate(data): + x |= (b & 0x7F) << s + if (b & 0x80) == 0: + return x, i + 1 + s += 7 + raise ValueError("Invalid varint") + + +def _decode_multibase_base58btc(z_value: str) -> bytes: + if not z_value.startswith("z"): + raise ValueError("Expected multibase base58btc string starting with 'z'") + return base58.b58decode(z_value[1:]) + + +def _split_did_url(did_url: str) -> Tuple[str, str]: + """Return (did, fragment) for 'did:...#fragment'; fragment is '' when absent.""" + did_url = did_url.strip() + did, _, fragment = did_url.partition("#") + return did, fragment + + + +# Private key loading + +def _load_private_key_bytes(data: bytes) -> RSAPrivateKey: + """Load an unencrypted PEM or DER RSA private key (PKCS#8 or PKCS#1).""" + try: + if b"-----BEGIN" in data: + key = serialization.load_pem_private_key(data, password=None) + else: + key = serialization.load_der_private_key(data, password=None) + except TypeError as e: + # Raised by cryptography when the key is encrypted and no password was given. + raise ValueError(f"Private key could not be loaded: {e}") from e + + if not isinstance(key, RSAPrivateKey): + raise ValueError( + f"Expected an RSA private key, got {type(key).__name__}. " + "Use `ce iir challenge sign` for Ed25519 keys." + ) + + return key + + +def _load_private_key_from_text(text: str) -> RSAPrivateKey: + """Pasted key: full PEM (real newlines or literal \\n), or just the base64 body.""" + cleaned = text.strip().replace("\\n", "\n") + + if "-----BEGIN" in cleaned: + return _load_private_key_bytes(cleaned.encode("ascii")) + + body = "".join(cleaned.split()) + try: + der = base64.b64decode(body, validate=True) + except (binascii.Error, ValueError) as e: + raise ValueError("Pasted key is neither PEM nor base64 DER.") from e + + return _load_private_key_bytes(der) + + +def _load_signing_key(private_key_file: str | None, private_key_pem: str | None) -> RSAPrivateKey: + if bool(private_key_file) == bool(private_key_pem): + raise click.ClickException( + "Give exactly one of --private-key-file or --private-key-pem." + ) + + try: + if private_key_file: + with open(private_key_file, "rb") as f: + key = _load_private_key_bytes(f.read()) + else: + key = _load_private_key_from_text(private_key_pem or "") + except ValueError as e: + raise click.ClickException(f"Could not load private key: {e}") + + if key.key_size < MIN_RSA_KEY_SIZE_BITS: + raise click.ClickException( + f"RSA key is {key.key_size} bits; at least {MIN_RSA_KEY_SIZE_BITS} bits are required." + ) + + return key + + + +# did:key resolution (offline) + +def _public_key_from_did_key(did_or_kid: str) -> RSAPublicKey: + did, fragment = _split_did_url(did_or_kid) + if not did.startswith("did:key:"): + raise ValueError("Not a did:key DID") + + identifier = did[len("did:key:"):] + if fragment and fragment != identifier: + raise ValueError("did:key fragment must equal the key identifier") + + raw = _decode_multibase_base58btc(identifier) + code, n = _parse_uvarint(raw) + + if code != MULTICODEC_RSA_PUB: + raise ValueError( + f"did:key multicodec 0x{code:X} is not an RSA public key " + f"(expected 0x{MULTICODEC_RSA_PUB:X})" + ) + + key_bytes = raw[n:] + if not key_bytes: + raise ValueError("did:key has no RSA key bytes") + + try: + key = serialization.load_der_public_key(key_bytes) + except ValueError as e: + raise ValueError(f"did:key RSA key is not valid PKCS#1 DER: {e}") from e + + if not isinstance(key, RSAPublicKey): + raise ValueError("did:key RSA payload is not an RSA public key") + + # PKCS#1 is required; SubjectPublicKeyInfo would also load, so check the round trip. + pkcs1 = key.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1) + if pkcs1 != key_bytes: + raise ValueError("did:key RSA key must be PKCS#1 RSAPublicKey DER") + + return key + + + +# did:web resolution (HTTPS using OS trust) + +def _did_web_to_url(did_web: str) -> str: + """did:web:host[:path...] -> https URL. A percent-encoded port (%3A) is decoded.""" + if not did_web.startswith("did:web:"): + raise ValueError("Not a did:web DID") + + parts = did_web[len("did:web:"):].split(":") + host = unquote(parts[0]) + if not host or any(c in host for c in "/?#@"): + raise ValueError("Invalid did:web host") + + path_parts = [quote(unquote(p), safe="") for p in parts[1:]] + if any(not p for p in path_parts): + raise ValueError("Invalid did:web path") + + if not path_parts: + return f"https://{host}/.well-known/did.json" + + return f"https://{host}/{'/'.join(path_parts)}/did.json" + + +def _fetch_did_json(did_web: str) -> Dict[str, Any]: + url = _did_web_to_url(did_web) + + r = requests.get( + url, + headers={"Accept": "application/did+json, application/json"}, + timeout=15, + ) + r.raise_for_status() + + doc = r.json() + if not isinstance(doc, dict): + raise ValueError("did.json must be a JSON object") + return doc + + +def _normalize(vm_id: str, did: str) -> str: + return did + vm_id if vm_id.startswith("#") else vm_id + + +def _find_verification_method( + did_doc: Dict[str, Any], did: str, kid: str +) -> Tuple[Dict[str, Any] | None, bool]: + """Return (verification method, listed in an accepted relationship).""" + found: Dict[str, Any] | None = None + in_relationship = False + + for relationship in ACCEPTED_RELATIONSHIPS: + entries = did_doc.get(relationship, []) + if not isinstance(entries, list): + continue + for entry in entries: + if isinstance(entry, str) and _normalize(entry, did) == kid: + in_relationship = True + elif isinstance(entry, dict) and isinstance(entry.get("id"), str): + if _normalize(entry["id"], did) == kid: + in_relationship = True + found = entry + + if found is None: + vms = did_doc.get("verificationMethod", []) + if not isinstance(vms, list): + raise ValueError("verificationMethod must be a list") + for vm in vms: + if isinstance(vm, dict) and isinstance(vm.get("id"), str): + if _normalize(vm["id"], did) == kid: + found = vm + break + + return found, in_relationship + + +def _public_key_from_verification_method(vm: Dict[str, Any]) -> RSAPublicKey: + vm_type = vm.get("type") + if vm_type != VERIFICATION_METHOD_TYPE: + raise ValueError( + f"Verification method type is '{vm_type}', expected '{VERIFICATION_METHOD_TYPE}'" + ) + + jwk = vm.get("publicKeyJwk") + if not isinstance(jwk, dict): + raise ValueError("Verification method has no publicKeyJwk") + + if jwk.get("kty") != "RSA": + raise ValueError(f"publicKeyJwk 'kty' is '{jwk.get('kty')}', expected 'RSA'") + + if "d" in jwk: + raise ValueError("publicKeyJwk contains private key material ('d')") + + if "alg" in jwk and jwk["alg"] != ALG: + raise ValueError(f"publicKeyJwk 'alg' is '{jwk['alg']}', expected '{ALG}'") + + if "use" in jwk and jwk["use"] != "sig": + raise ValueError(f"publicKeyJwk 'use' is '{jwk['use']}', expected 'sig'") + + key = RSAAlgorithm.from_jwk(jwk) + if not isinstance(key, RSAPublicKey): + raise ValueError("publicKeyJwk is not an RSA public key") + + return key + + +def _public_key_from_did_doc(*, kid: str, did_doc: Dict[str, Any]) -> RSAPublicKey: + did, _ = _split_did_url(kid) + kid = kid.strip() + + if did_doc.get("id") != did: + raise ValueError("DID document 'id' does not match the DID") + + vm, in_relationship = _find_verification_method(did_doc, did, kid) + + if vm is None: + raise ValueError(f"kid not found in did.json: {kid}") + + if not in_relationship: + raise ValueError( + f"Verification method '{kid}' is not listed under " + f"{' or '.join(repr(r) for r in ACCEPTED_RELATIONSHIPS)}" + ) + + return _public_key_from_verification_method(vm) + + +def _resolve_public_key_for_kid(kid: str) -> RSAPublicKey: + did, _ = _split_did_url(kid) + + if did.startswith("did:key:"): + return _public_key_from_did_key(kid) + + if did.startswith("did:web:"): + return _public_key_from_did_doc(kid=kid, did_doc=_fetch_did_json(did)) + + raise ValueError(f"Unsupported DID method: {did}") + + + +# Signing + verification + +def _sign_payload(private_key: RSAPrivateKey, kid: str, payload_obj: Dict[str, Any]) -> str: + headers = {"typ": "JWT", "alg": ALG, "kid": kid} + + token = jwt.encode( + payload=payload_obj, + key=private_key, + algorithm=ALG, + headers=headers, + ) + + if isinstance(token, bytes): + token = token.decode("utf-8") + + return token + + +def _verify_signature_only(token: str, public_key: RSAPublicKey) -> None: + jwt.decode( + token, + key=public_key, + algorithms=[ALG], + options={ + "verify_signature": True, + "verify_aud": False, + "verify_exp": False, + "verify_iat": False, + "verify_nbf": False, + "verify_iss": False, + }, + ) + + +def _assert_signature_verifiable(token: str, kid: str) -> None: + pub_key = _resolve_public_key_for_kid(kid) + + if pub_key.key_size < MIN_RSA_KEY_SIZE_BITS: + raise click.ClickException( + f"DID RSA key is {pub_key.key_size} bits; at least " + f"{MIN_RSA_KEY_SIZE_BITS} bits are required." + ) + + try: + _verify_signature_only(token, pub_key) + except jwt.exceptions.InvalidSignatureError as e: + raise click.ClickException( + "Signature verification failed (token does not match DID public key)." + ) from e + except jwt.PyJWTError as e: + raise click.ClickException(f"JWT verification error: {e}") from e + + err_console.print( + "[green]Signature verification: OK[/green] (RS256, matches DID public key)" + ) + + + +# Click command + +@click.command("sign-rs256") +@click.option( + "--private-key-file", + "private_key_file", + default=None, + type=click.Path(exists=True, dir_okay=False, readable=True), + metavar="PATH", + help="RSA private key file, PEM or DER (PKCS#8 or PKCS#1), unencrypted.", +) +@click.option( + "--private-key-pem", + "private_key_pem", + default=None, + metavar="TEXT", + help="Pasted RSA private key: full PEM (newlines or literal \\n) or just the base64 body.", +) +@click.option( + "--challenge-file", + "challenge_file", + required=True, + type=click.Path(exists=True, dir_okay=False, readable=True), + metavar="PATH", + help="Path to CE-generated challenge JSON file.", +) +@click.option( + "--output", "-o", + "out_path", + default=None, + type=click.Path(dir_okay=False, writable=True), + metavar="PATH", + help="Write JWT to this file (otherwise printed to stdout).", +) +def sign_rs256_challenge( + private_key_file: str | None, + private_key_pem: str | None, + challenge_file: str, + out_path: str | None, +) -> None: + """Sign a single CE challenge JSON file with an RSA key and produce a Proof JWT (RS256). + + \b + Give exactly one of --private-key-file or --private-key-pem. + The challenge JSON must include: did, challenge, aud, iat, exp. + Signature verification uses did:key (offline) or did:web (HTTPS). + + \b + Example: + ce iir challenge sign-rs256 \\ + --private-key-file rsa-key.pem \\ + --challenge-file challenge.json \\ + --output signed-challenge.jwt + """ + signing_key = _load_signing_key(private_key_file, private_key_pem) + + try: + with open(challenge_file, "r", encoding="utf-8") as f: + payload_obj = json.load(f) + except json.JSONDecodeError as e: + raise click.ClickException(f"Challenge file is not valid JSON: {e}") + + if not isinstance(payload_obj, dict): + raise click.ClickException("Challenge payload must be a JSON object.") + + required_fields = ["did", "challenge", "aud", "iat", "exp"] + missing = [k for k in required_fields if k not in payload_obj] + if missing: + raise click.ClickException( + f"Challenge JSON missing required field(s): {', '.join(missing)}" + ) + + did_value = payload_obj.get("did") + if not isinstance(did_value, str) or not did_value.strip(): + raise click.ClickException( + 'Challenge JSON must include a non-empty string field "did".' + ) + + kid = did_value.strip() + + try: + token = _sign_payload(signing_key, kid, payload_obj) + except (ValueError, jwt.PyJWTError) as e: + raise click.ClickException(f"Signing failed: {e}") + + try: + _assert_signature_verifiable(token, kid) + except requests.RequestException as e: + raise click.ClickException(f"Failed to fetch did.json: {e}") + except ValueError as e: + raise click.ClickException(f"DID resolution error: {e}") + + if out_path: + with open(out_path, "w", encoding="utf-8") as f: + f.write(token) + err_console.print(f"Wrote Proof JWT to: [cyan]{out_path}[/cyan]") + else: + click.echo(token) diff --git a/tests/test_iir_sign_challenge_rs256.py b/tests/test_iir_sign_challenge_rs256.py new file mode 100644 index 0000000..85807e6 --- /dev/null +++ b/tests/test_iir_sign_challenge_rs256.py @@ -0,0 +1,604 @@ +""" +Unit tests for ce.commands.iir_sign_challenge_rs256. +Run with: + pytest -m unit -s +""" + +from __future__ import annotations + +import base64 +import json +from pathlib import Path +from unittest.mock import MagicMock, patch + +import click +import pytest +import requests +from click.testing import CliRunner + + + +pytestmark = pytest.mark.unit + + +from ce.commands.iir_sign_challenge_rs256 import ( + _assert_signature_verifiable, + _did_web_to_url, + _fetch_did_json, + _load_private_key_bytes, + _load_private_key_from_text, + _load_signing_key, + _parse_uvarint, + _public_key_from_did_doc, + _public_key_from_did_key, + _resolve_public_key_for_kid, + _sign_payload, + _verify_signature_only, + sign_rs256_challenge, +) + + +MODULE = "ce.commands.iir_sign_challenge_rs256" + +CHALLENGE_UUID = "11111111-2222-3333-4444-555555555555" +CTID = "ce-12345678-1234-1234-1234-123456789abc" +ED25519_DID_KEY = "did:key:z6MkhaXgBZDvf7gKKWXjGmgkbQXyrXYY4uZmTaTzPhRgg9Wm" +RSA_MULTICODEC_PREFIX = bytes([0x85, 0x24]) # varint of 0x1205 (rsa-pub) + +DID_WEB = "did:web:example.com" +DID_WEB_KID = f"{DID_WEB}#key-1" + + + +# Helpers + +def _pem(key, fmt) -> bytes: + from cryptography.hazmat.primitives import serialization + + return key.private_bytes( + encoding=serialization.Encoding.PEM, + format=fmt, + encryption_algorithm=serialization.NoEncryption(), + ) + + +def _rsa_did_key(public_key) -> str: + import base58 + from cryptography.hazmat.primitives import serialization + + pkcs1 = public_key.public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.PKCS1, + ) + return "did:key:z" + base58.b58encode(RSA_MULTICODEC_PREFIX + pkcs1).decode() + + +def _kid_for_did_key(did_key: str) -> str: + return f"{did_key}#{did_key[len('did:key:'):]}" + + +def _b64url_uint(value: int) -> str: + raw = value.to_bytes((value.bit_length() + 7) // 8, "big") + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + +def _rsa_jwk(public_key, **extra): + numbers = public_key.public_numbers() + jwk = {"kty": "RSA", "n": _b64url_uint(numbers.n), "e": _b64url_uint(numbers.e)} + jwk.update(extra) + return jwk + + +def _did_web_doc(public_key, *, did=DID_WEB, vm_id=DID_WEB_KID, auth=None, vm_type="JsonWebKey2020", jwk=None): + return { + "id": did, + "verificationMethod": [ + { + "id": vm_id, + "type": vm_type, + "controller": did, + "publicKeyJwk": jwk if jwk is not None else _rsa_jwk(public_key, alg="RS256"), + } + ], + "authentication": [vm_id] if auth is None else auth, + } + + +def _decode_segment(token: str, index: int) -> dict: + segment = token.split(".")[index] + return json.loads(base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))) + + +def _tamper_signature(token: str) -> str: + parts = token.split(".") + first = parts[2][0] + parts[2] = ("B" if first != "B" else "C") + parts[2][1:] + return ".".join(parts) + + +def _mock_did_json(doc): + mock_resp = MagicMock() + mock_resp.json.return_value = doc + mock_resp.raise_for_status = MagicMock() + return patch(f"{MODULE}.requests.get", return_value=mock_resp) + + +def _write_json(path: Path, obj) -> Path: + path.write_text(json.dumps(obj), encoding="utf-8") + return path + + + +# Fixtures + +@pytest.fixture(scope="session") +def rsa_key(): + from cryptography.hazmat.primitives.asymmetric import rsa + + return rsa.generate_private_key(public_exponent=65537, key_size=2048) + + +@pytest.fixture(scope="session") +def other_rsa_key(): + from cryptography.hazmat.primitives.asymmetric import rsa + + return rsa.generate_private_key(public_exponent=65537, key_size=2048) + + +@pytest.fixture(scope="session") +def rsa_kid(rsa_key): + return _kid_for_did_key(_rsa_did_key(rsa_key.public_key())) + + +@pytest.fixture +def challenge_payload(rsa_kid): + return { + "did": rsa_kid, + "challenge": CHALLENGE_UUID, + "aud": "ce-api", + "iat": 1700000000, + "exp": 1700003600, + "ctid": CTID, + } + + + +class TestParseUvarint: + def test_rsa_multicodec(self): + value, used = _parse_uvarint(RSA_MULTICODEC_PREFIX) + assert value == 0x1205 and used == 2 + + def test_invalid_varint_raises(self): + with pytest.raises(ValueError, match="Invalid varint"): + _parse_uvarint(bytes([0x80, 0x80, 0x80])) + + + +class TestLoadPrivateKey: + def test_pkcs8_pem(self, rsa_key): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + key = _load_private_key_bytes(_pem(rsa_key, serialization.PrivateFormat.PKCS8)) + assert isinstance(key, RSAPrivateKey) + + def test_pkcs1_pem(self, rsa_key): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + key = _load_private_key_bytes(_pem(rsa_key, serialization.PrivateFormat.TraditionalOpenSSL)) + assert isinstance(key, RSAPrivateKey) + + def test_der(self, rsa_key): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + der = rsa_key.private_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + assert isinstance(_load_private_key_bytes(der), RSAPrivateKey) + + def test_ed25519_key_rejected_with_hint(self): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + pem = _pem(Ed25519PrivateKey.generate(), serialization.PrivateFormat.PKCS8) + with pytest.raises(ValueError, match="ce iir challenge sign"): + _load_private_key_bytes(pem) + + def test_encrypted_pem_rejected(self, rsa_key): + from cryptography.hazmat.primitives import serialization + pem = rsa_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.BestAvailableEncryption(b"secret"), + ) + with pytest.raises(ValueError, match="could not be loaded"): + _load_private_key_bytes(pem) + + def test_text_with_real_newlines(self, rsa_key): + from cryptography.hazmat.primitives import serialization + text = _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode() + assert _load_private_key_from_text(text).key_size == 2048 + + def test_text_with_literal_backslash_n(self, rsa_key): + from cryptography.hazmat.primitives import serialization + text = _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode().replace("\n", "\\n") + assert _load_private_key_from_text(text).key_size == 2048 + + def test_text_bare_base64_body(self, rsa_key): + from cryptography.hazmat.primitives import serialization + body = "".join( + line + for line in _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode().splitlines() + if "-----" not in line + ) + assert _load_private_key_from_text(body).key_size == 2048 + + def test_text_garbage_rejected(self): + with pytest.raises(ValueError, match="neither PEM nor base64"): + _load_private_key_from_text("this is not a key!") + + +class TestLoadSigningKey: + def test_file(self, rsa_key, tmp_path): + from cryptography.hazmat.primitives import serialization + path = tmp_path / "rsa.pem" + path.write_bytes(_pem(rsa_key, serialization.PrivateFormat.PKCS8)) + assert _load_signing_key(str(path), None).key_size == 2048 + + def test_text(self, rsa_key): + from cryptography.hazmat.primitives import serialization + text = _pem(rsa_key, serialization.PrivateFormat.TraditionalOpenSSL).decode() + assert _load_signing_key(None, text).key_size == 2048 + + def test_small_key_rejected(self, tmp_path): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import rsa + small = rsa.generate_private_key(public_exponent=65537, key_size=1024) + path = tmp_path / "small.pem" + path.write_bytes(_pem(small, serialization.PrivateFormat.PKCS8)) + with pytest.raises(click.ClickException, match="2048"): + _load_signing_key(str(path), None) + + def test_no_option_rejected(self): + with pytest.raises(click.ClickException, match="exactly one"): + _load_signing_key(None, None) + + def test_both_options_rejected(self, rsa_key, tmp_path): + from cryptography.hazmat.primitives import serialization + pem = _pem(rsa_key, serialization.PrivateFormat.PKCS8) + path = tmp_path / "rsa.pem" + path.write_bytes(pem) + with pytest.raises(click.ClickException, match="exactly one"): + _load_signing_key(str(path), pem.decode()) + + + +class TestPublicKeyFromDidKey: + def test_bare_did(self, rsa_key): + did = _rsa_did_key(rsa_key.public_key()) + assert _public_key_from_did_key(did).public_numbers() == rsa_key.public_key().public_numbers() + + def test_kid_with_fragment(self, rsa_key, rsa_kid): + assert _public_key_from_did_key(rsa_kid).public_numbers() == rsa_key.public_key().public_numbers() + + def test_did_starts_with_z4mx(self, rsa_key): + assert _rsa_did_key(rsa_key.public_key()).startswith("did:key:z4MX") + + def test_wrong_fragment_rejected(self, rsa_key): + did = _rsa_did_key(rsa_key.public_key()) + with pytest.raises(ValueError, match="fragment must equal"): + _public_key_from_did_key(f"{did}#key-1") + + def test_ed25519_did_key_rejected(self): + with pytest.raises(ValueError, match="0xED is not an RSA public key"): + _public_key_from_did_key(ED25519_DID_KEY) + + def test_spki_instead_of_pkcs1_rejected(self, rsa_key): + import base58 + from cryptography.hazmat.primitives import serialization + spki = rsa_key.public_key().public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + did = "did:key:z" + base58.b58encode(RSA_MULTICODEC_PREFIX + spki).decode() + with pytest.raises(ValueError, match="PKCS#1"): + _public_key_from_did_key(did) + + def test_garbage_key_bytes_rejected(self): + import base58 + did = "did:key:z" + base58.b58encode(RSA_MULTICODEC_PREFIX + b"\x01" * 32).decode() + with pytest.raises(ValueError, match="not valid PKCS#1"): + _public_key_from_did_key(did) + + def test_non_did_key_rejected(self): + with pytest.raises(ValueError, match="did:key"): + _public_key_from_did_key(DID_WEB) + + + +class TestDidWebToUrl: + def test_host_only_uses_well_known(self): + assert _did_web_to_url(DID_WEB) == "https://example.com/.well-known/did.json" + + def test_with_path_segments(self): + assert ( + _did_web_to_url("did:web:example.com:issuers:test") + == "https://example.com/issuers/test/did.json" + ) + + def test_port_is_decoded(self): + assert ( + _did_web_to_url("did:web:example.com%3A8443") + == "https://example.com:8443/.well-known/did.json" + ) + + def test_non_did_web_rejected(self): + with pytest.raises(ValueError, match="did:web"): + _did_web_to_url("did:key:z4MX...") + + def test_host_with_slash_rejected(self): + with pytest.raises(ValueError, match="host"): + _did_web_to_url("did:web:example.com%2Fevil") + + +class TestFetchDidJson: + def test_returns_parsed_json(self): + doc = {"id": DID_WEB, "verificationMethod": []} + with _mock_did_json(doc) as mock_get: + assert _fetch_did_json(DID_WEB) == doc + + args, kwargs = mock_get.call_args + assert args[0] == "https://example.com/.well-known/did.json" + assert "Accept" in kwargs["headers"] + + def test_http_error_propagates(self): + mock_resp = MagicMock() + mock_resp.raise_for_status.side_effect = requests.HTTPError("404 Not Found") + with patch(f"{MODULE}.requests.get", return_value=mock_resp): + with pytest.raises(requests.HTTPError): + _fetch_did_json(DID_WEB) + + def test_non_object_rejected(self): + with _mock_did_json(["not", "an", "object"]): + with pytest.raises(ValueError, match="must be a JSON object"): + _fetch_did_json(DID_WEB) + + +class TestPublicKeyFromDidDoc: + def test_absolute_ids(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key()) + key = _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + assert key.public_numbers() == rsa_key.public_key().public_numbers() + + def test_relative_ids(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), vm_id="#key-1", auth=["#key-1"]) + key = _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + assert key.public_numbers() == rsa_key.public_key().public_numbers() + + def test_embedded_authentication_method(self, rsa_key): + doc = { + "id": DID_WEB, + "authentication": [ + {"id": DID_WEB_KID, "type": "JsonWebKey2020", "publicKeyJwk": _rsa_jwk(rsa_key.public_key())} + ], + } + key = _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + assert key.public_numbers() == rsa_key.public_key().public_numbers() + + def test_picks_rsa_key_from_mixed_doc(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), vm_id=f"{DID_WEB}#key-2", auth=[f"{DID_WEB}#key-1", f"{DID_WEB}#key-2"]) + doc["verificationMethod"].insert( + 0, + {"id": f"{DID_WEB}#key-1", "type": "Ed25519VerificationKey2020", "publicKeyMultibase": "z6Mk..."}, + ) + key = _public_key_from_did_doc(kid=f"{DID_WEB}#key-2", did_doc=doc) + assert key.public_numbers() == rsa_key.public_key().public_numbers() + + def test_document_id_mismatch_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key()) + doc["id"] = "did:web:other.example.com" + with pytest.raises(ValueError, match="'id' does not match"): + _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + + def test_kid_not_found_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key()) + with pytest.raises(ValueError, match="kid not found"): + _public_key_from_did_doc(kid=f"{DID_WEB}#key-MISSING", did_doc=doc) + + def test_not_in_authentication_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), auth=[]) + with pytest.raises(ValueError, match="not listed under 'authentication'"): + _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + + def test_assertion_method_only_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), auth=[]) + doc["assertionMethod"] = [DID_WEB_KID] + with pytest.raises(ValueError, match="not listed under 'authentication'"): + _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + + def test_wrong_type_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), vm_type="RsaVerificationKey2018") + with pytest.raises(ValueError, match="expected 'JsonWebKey2020'"): + _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + + def test_non_rsa_jwk_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), jwk={"kty": "OKP", "crv": "Ed25519", "x": "AAAA"}) + with pytest.raises(ValueError, match="'kty' is 'OKP'"): + _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + + def test_private_part_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), jwk=_rsa_jwk(rsa_key.public_key(), d="AAAA")) + with pytest.raises(ValueError, match="private key material"): + _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + + def test_wrong_jwk_alg_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), jwk=_rsa_jwk(rsa_key.public_key(), alg="PS256")) + with pytest.raises(ValueError, match="'alg' is 'PS256'"): + _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + + def test_wrong_jwk_use_rejected(self, rsa_key): + doc = _did_web_doc(rsa_key.public_key(), jwk=_rsa_jwk(rsa_key.public_key(), use="enc")) + with pytest.raises(ValueError, match="'use' is 'enc'"): + _public_key_from_did_doc(kid=DID_WEB_KID, did_doc=doc) + + +class TestResolvePublicKeyForKid: + def test_did_key(self, rsa_key, rsa_kid): + assert _resolve_public_key_for_kid(rsa_kid).public_numbers() == rsa_key.public_key().public_numbers() + + def test_did_web_fetches_doc(self, rsa_key): + with _mock_did_json(_did_web_doc(rsa_key.public_key())) as mock_get: + key = _resolve_public_key_for_kid(DID_WEB_KID) + assert key.public_numbers() == rsa_key.public_key().public_numbers() + assert mock_get.call_args[0][0] == "https://example.com/.well-known/did.json" + + def test_unsupported_method_rejected(self): + with pytest.raises(ValueError, match="Unsupported DID method"): + _resolve_public_key_for_kid("did:ethr:0x123#key-1") + + + +class TestSignPayload: + def test_header(self, rsa_key, rsa_kid, challenge_payload): + header = _decode_segment(_sign_payload(rsa_key, rsa_kid, challenge_payload), 0) + assert header == {"typ": "JWT", "alg": "RS256", "kid": rsa_kid} + + def test_payload_round_trips(self, rsa_key, rsa_kid, challenge_payload): + token = _sign_payload(rsa_key, rsa_kid, challenge_payload) + assert _decode_segment(token, 1) == challenge_payload + + def test_signature_is_modulus_length(self, rsa_key, rsa_kid, challenge_payload): + segment = _sign_payload(rsa_key, rsa_kid, challenge_payload).split(".")[2] + signature = base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)) + assert len(signature) == 256 + + +class TestVerifySignatureOnly: + def test_valid(self, rsa_key, rsa_kid, challenge_payload): + token = _sign_payload(rsa_key, rsa_kid, challenge_payload) + _verify_signature_only(token, rsa_key.public_key()) + + def test_tampered_rejected(self, rsa_key, rsa_kid, challenge_payload): + import jwt + token = _sign_payload(rsa_key, rsa_kid, challenge_payload) + with pytest.raises(jwt.exceptions.InvalidSignatureError): + _verify_signature_only(_tamper_signature(token), rsa_key.public_key()) + + def test_does_not_check_expiry(self, rsa_key, rsa_kid): + payload = {"did": rsa_kid, "challenge": CHALLENGE_UUID, "aud": "ce-api", "iat": 1, "exp": 2} + token = _sign_payload(rsa_key, rsa_kid, payload) + _verify_signature_only(token, rsa_key.public_key()) + + +class TestAssertSignatureVerifiable: + def test_did_key_ok(self, rsa_key, rsa_kid, challenge_payload): + _assert_signature_verifiable(_sign_payload(rsa_key, rsa_kid, challenge_payload), rsa_kid) + + def test_did_web_ok(self, rsa_key, challenge_payload): + token = _sign_payload(rsa_key, DID_WEB_KID, challenge_payload) + with _mock_did_json(_did_web_doc(rsa_key.public_key())): + _assert_signature_verifiable(token, DID_WEB_KID) + + def test_wrong_key_rejected(self, rsa_key, other_rsa_key, rsa_kid, challenge_payload): + token = _sign_payload(other_rsa_key, rsa_kid, challenge_payload) + with pytest.raises(click.ClickException, match="Signature verification failed"): + _assert_signature_verifiable(token, rsa_kid) + + def test_tampered_rejected(self, rsa_key, rsa_kid, challenge_payload): + token = _sign_payload(rsa_key, rsa_kid, challenge_payload) + with pytest.raises(click.ClickException, match="Signature verification failed"): + _assert_signature_verifiable(_tamper_signature(token), rsa_kid) + + def test_malformed_token_rejected(self, rsa_kid): + with pytest.raises(click.ClickException, match="JWT verification error"): + _assert_signature_verifiable("not.a.real.jwt", rsa_kid) + + + +class TestSignRs256Command: + """End-to-end through the click command.""" + + def _run(self, args): + result = CliRunner().invoke(sign_rs256_challenge, args) + return result.exit_code, result.output + + def _key_file(self, rsa_key, tmp_path) -> Path: + from cryptography.hazmat.primitives import serialization + path = tmp_path / "rsa.pem" + path.write_bytes(_pem(rsa_key, serialization.PrivateFormat.PKCS8)) + return path + + def test_key_file_did_key(self, rsa_key, rsa_kid, tmp_path, challenge_payload): + challenge = _write_json(tmp_path / "challenge.json", challenge_payload) + out_path = tmp_path / "signed.jwt" + + code, output = self._run( + [ + "--private-key-file", str(self._key_file(rsa_key, tmp_path)), + "--challenge-file", str(challenge), + "-o", str(out_path), + ] + ) + + assert code == 0, output + header = _decode_segment(out_path.read_text(encoding="utf-8"), 0) + assert header["alg"] == "RS256" + assert header["kid"] == rsa_kid + + def test_pasted_pem_did_web(self, rsa_key, tmp_path, challenge_payload): + from cryptography.hazmat.primitives import serialization + challenge = _write_json(tmp_path / "challenge.json", dict(challenge_payload, did=DID_WEB_KID)) + + with _mock_did_json(_did_web_doc(rsa_key.public_key())): + code, output = self._run( + [ + "--private-key-pem", _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode(), + "--challenge-file", str(challenge), + ] + ) + + assert code == 0, output + token = output.strip().splitlines()[-1] + assert _decode_segment(token, 0)["kid"] == DID_WEB_KID + + def test_ed25519_key_rejected(self, tmp_path, challenge_payload): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + key_path = tmp_path / "ed.pem" + key_path.write_bytes(_pem(Ed25519PrivateKey.generate(), serialization.PrivateFormat.PKCS8)) + challenge = _write_json(tmp_path / "challenge.json", challenge_payload) + + code, output = self._run(["--private-key-file", str(key_path), "--challenge-file", str(challenge)]) + + assert code != 0 + assert "ce iir challenge sign" in output + + def test_did_is_ed25519_rejected(self, rsa_key, tmp_path, challenge_payload): + challenge = _write_json(tmp_path / "challenge.json", dict(challenge_payload, did=ED25519_DID_KEY)) + + code, output = self._run( + ["--private-key-file", str(self._key_file(rsa_key, tmp_path)), "--challenge-file", str(challenge)] + ) + + assert code != 0 + assert "not an RSA public key" in output + + def test_missing_required_field_rejected(self, rsa_key, tmp_path, challenge_payload): + payload = dict(challenge_payload) + del payload["exp"] + challenge = _write_json(tmp_path / "challenge.json", payload) + + code, output = self._run( + ["--private-key-file", str(self._key_file(rsa_key, tmp_path)), "--challenge-file", str(challenge)] + ) + + assert code != 0 + assert "exp" in output + + def test_no_key_option_rejected(self, tmp_path, challenge_payload): + challenge = _write_json(tmp_path / "challenge.json", challenge_payload) + + code, output = self._run(["--challenge-file", str(challenge)]) + + assert code != 0 + assert "exactly one" in output diff --git a/tests/test_sign_single_challenge.py b/tests/test_sign_single_challenge.py index d954b04..e64633b 100644 --- a/tests/test_sign_single_challenge.py +++ b/tests/test_sign_single_challenge.py @@ -14,7 +14,6 @@ import click import pytest import requests -from click.testing import CliRunner @@ -25,82 +24,23 @@ _assert_signature_verifiable, _decode_multibase_base58btc, _did_web_to_url, + _extract_ed25519_pub_from_did_key, _extract_ed25519_seed_from_private_key, _fetch_did_json, - _load_private_key_bytes, - _load_private_key_from_text, - _load_signing_key, _parse_uvarint, _public_key_from_did_doc, - _public_key_from_did_key, - _resolve_public_key_for_kid, + _resolve_public_key_bytes_for_kid, _sign_payload, _verify_signature_only, - sign_individual_challenge, ) -MODULE = "ce.commands.iir_sign_challenge" CHALLENGE_UUID = "11111111-2222-3333-4444-555555555555" CTID = "ce-12345678-1234-1234-1234-123456789abc" ED25519_DID_KEY = "did:key:z6MkhaXgBZDvf7gKKWXjGmgkbQXyrXYY4uZmTaTzPhRgg9Wm" ED25519_KID = f"{ED25519_DID_KEY}#{ED25519_DID_KEY[len('did:key:'):]}" -RSA_MULTICODEC_PREFIX = bytes([0x85, 0x24]) # varint of 0x1205 - - - -# Helpers - -def _raw_ed25519(public_key) -> bytes: - from cryptography.hazmat.primitives import serialization - - return public_key.public_bytes( - encoding=serialization.Encoding.Raw, - format=serialization.PublicFormat.Raw, - ) - - -def _b64url_uint(value: int) -> str: - raw = value.to_bytes((value.bit_length() + 7) // 8, "big") - return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() - - -def _rsa_jwk(public_key, **extra): - numbers = public_key.public_numbers() - jwk = {"kty": "RSA", "n": _b64url_uint(numbers.n), "e": _b64url_uint(numbers.e)} - jwk.update(extra) - return jwk - - -def _decode_segment(token: str, index: int) -> dict: - segment = token.split(".")[index] - padded = segment + "=" * (-len(segment) % 4) - return json.loads(base64.urlsafe_b64decode(padded)) - - -def _tamper_signature(token: str) -> str: - parts = token.split(".") - first = parts[2][0] - parts[2] = ("B" if first != "B" else "C") + parts[2][1:] - return ".".join(parts) - - -def _mock_did_json(doc): - mock_resp = MagicMock() - mock_resp.json.return_value = doc - mock_resp.raise_for_status = MagicMock() - return patch(f"{MODULE}.requests.get", return_value=mock_resp) - - -def _write_json(path: Path, obj) -> Path: - path.write_text(json.dumps(obj), encoding="utf-8") - return path - - - -# Fixtures @pytest.fixture(scope="session") def ed25519_keypair(): @@ -140,54 +80,6 @@ def ed25519_keypair(): return priv_multibase, did_key, kid -@pytest.fixture(scope="session") -def ed25519_signing_key(ed25519_keypair): - """The Ed25519 private key object for the session keypair.""" - priv, _, _ = ed25519_keypair - key, alg = _load_signing_key(priv, None, None) - assert alg == "EdDSA" - return key - - -@pytest.fixture(scope="session") -def rsa_keypair(): - """Generate an RSA 2048 keypair and its did:key. - - Returns a dict with: key, pem_pkcs8, pem_pkcs1, did_key, kid. - """ - import base58 - from cryptography.hazmat.primitives import serialization - from cryptography.hazmat.primitives.asymmetric import rsa - - key = rsa.generate_private_key(public_exponent=65537, key_size=2048) - - pem_pkcs8 = key.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=serialization.NoEncryption(), - ) - pem_pkcs1 = key.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.TraditionalOpenSSL, - encryption_algorithm=serialization.NoEncryption(), - ) - pub_pkcs1 = key.public_key().public_bytes( - encoding=serialization.Encoding.DER, - format=serialization.PublicFormat.PKCS1, - ) - - did_key = "did:key:z" + base58.b58encode(RSA_MULTICODEC_PREFIX + pub_pkcs1).decode() - kid = f"{did_key}#{did_key[len('did:key:'):]}" - - return { - "key": key, - "pem_pkcs8": pem_pkcs8, - "pem_pkcs1": pem_pkcs1, - "did_key": did_key, - "kid": kid, - } - - @pytest.fixture def valid_challenge_payload(): return { @@ -200,6 +92,11 @@ def valid_challenge_payload(): } +def _write_json(path: Path, obj) -> Path: + path.write_text(json.dumps(obj), encoding="utf-8") + return path + + class TestParseUvarint: def test_single_byte_value(self): @@ -210,10 +107,6 @@ def test_two_byte_continuation(self): value, used = _parse_uvarint(bytes([0x80, 0x01])) assert value == 128 and used == 2 - def test_rsa_multicodec(self): - value, used = _parse_uvarint(RSA_MULTICODEC_PREFIX) - assert value == 0x1205 and used == 2 - def test_consumes_only_the_varint_bytes(self): value, used = _parse_uvarint(bytes([0x7F, 0xAA, 0xBB])) assert value == 0x7F and used == 1 @@ -285,167 +178,30 @@ def test_non_multibase_input_raises(self): -class TestLoadPrivateKey: - def test_pkcs8_pem_bytes_is_rsa(self, rsa_keypair): - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey - key = _load_private_key_bytes(rsa_keypair["pem_pkcs8"]) - assert isinstance(key, RSAPrivateKey) - - def test_pkcs1_pem_bytes_is_rsa(self, rsa_keypair): - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey - key = _load_private_key_bytes(rsa_keypair["pem_pkcs1"]) - assert isinstance(key, RSAPrivateKey) - - def test_der_bytes_is_rsa(self, rsa_keypair): - from cryptography.hazmat.primitives import serialization - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey - der = rsa_keypair["key"].private_bytes( - encoding=serialization.Encoding.DER, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=serialization.NoEncryption(), - ) - assert isinstance(_load_private_key_bytes(der), RSAPrivateKey) - - def test_ed25519_pem_bytes_is_ed25519(self): - from cryptography.hazmat.primitives import serialization - from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey - pem = Ed25519PrivateKey.generate().private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=serialization.NoEncryption(), - ) - assert isinstance(_load_private_key_bytes(pem), Ed25519PrivateKey) - - def test_encrypted_pem_raises(self, rsa_keypair): - from cryptography.hazmat.primitives import serialization - pem = rsa_keypair["key"].private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=serialization.BestAvailableEncryption(b"secret"), - ) - with pytest.raises(ValueError, match="could not be loaded"): - _load_private_key_bytes(pem) - - def test_unsupported_key_type_raises(self): - from cryptography.hazmat.primitives import serialization - from cryptography.hazmat.primitives.asymmetric import ec - pem = ec.generate_private_key(ec.SECP256R1()).private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=serialization.NoEncryption(), - ) - with pytest.raises(ValueError, match="Unsupported private key type"): - _load_private_key_bytes(pem) - - def test_text_with_real_newlines(self, rsa_keypair): - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey - key = _load_private_key_from_text(rsa_keypair["pem_pkcs8"].decode()) - assert isinstance(key, RSAPrivateKey) - - def test_text_with_literal_backslash_n(self, rsa_keypair): - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey - text = rsa_keypair["pem_pkcs8"].decode().replace("\n", "\\n") - assert isinstance(_load_private_key_from_text(text), RSAPrivateKey) - - def test_text_bare_base64_body(self, rsa_keypair): - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey - body = "".join( - line - for line in rsa_keypair["pem_pkcs8"].decode().splitlines() - if "-----" not in line - ) - assert isinstance(_load_private_key_from_text(body), RSAPrivateKey) - - def test_text_garbage_raises(self): - with pytest.raises(ValueError, match="neither PEM nor base64"): - _load_private_key_from_text("this is not a key!") - - -class TestLoadSigningKey: - def test_multibase_is_eddsa(self, ed25519_keypair): - priv, _, _ = ed25519_keypair - _, alg = _load_signing_key(priv, None, None) - assert alg == "EdDSA" - - def test_rsa_file_is_rs256(self, rsa_keypair, tmp_path): - path = tmp_path / "rsa.pem" - path.write_bytes(rsa_keypair["pem_pkcs8"]) - _, alg = _load_signing_key(None, str(path), None) - assert alg == "RS256" - - def test_rsa_text_is_rs256(self, rsa_keypair): - _, alg = _load_signing_key(None, None, rsa_keypair["pem_pkcs1"].decode()) - assert alg == "RS256" - - def test_small_rsa_key_rejected(self, tmp_path): - from cryptography.hazmat.primitives import serialization - from cryptography.hazmat.primitives.asymmetric import rsa - small = rsa.generate_private_key(public_exponent=65537, key_size=1024) - path = tmp_path / "small.pem" - path.write_bytes( - small.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=serialization.NoEncryption(), - ) - ) - with pytest.raises(click.ClickException, match="2048"): - _load_signing_key(None, str(path), None) - - def test_no_key_option_rejected(self): - with pytest.raises(click.ClickException, match="exactly one"): - _load_signing_key(None, None, None) - - def test_two_key_options_rejected(self, ed25519_keypair, rsa_keypair): - priv, _, _ = ed25519_keypair - with pytest.raises(click.ClickException, match="exactly one"): - _load_signing_key(priv, None, rsa_keypair["pem_pkcs8"].decode()) - - def test_bad_multibase_raises(self): - with pytest.raises(click.ClickException, match="Could not load private key"): - _load_signing_key("zNOT-A-REAL-KEY", None, None) - - - -class TestPublicKeyFromDidKey: - def test_ed25519_returns_32_bytes(self): - from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey - pub = _public_key_from_did_key(ED25519_DID_KEY) - assert isinstance(pub, Ed25519PublicKey) - assert len(_raw_ed25519(pub)) == 32 +class TestExtractEd25519PubFromDidKey: + def test_returns_32_bytes(self): + pub = _extract_ed25519_pub_from_did_key(ED25519_DID_KEY) + assert isinstance(pub, bytes) and len(pub) == 32 def test_accepts_kid_with_fragment(self): - from_base = _raw_ed25519(_public_key_from_did_key(ED25519_DID_KEY)) - from_kid = _raw_ed25519(_public_key_from_did_key(ED25519_KID)) + from_base = _extract_ed25519_pub_from_did_key(ED25519_DID_KEY) + from_kid = _extract_ed25519_pub_from_did_key(ED25519_KID) assert from_base == from_kid def test_strips_whitespace(self): - pub = _public_key_from_did_key(" " + ED25519_DID_KEY + " ") - assert len(_raw_ed25519(pub)) == 32 - - def test_rsa_did_key(self, rsa_keypair): - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey - pub = _public_key_from_did_key(rsa_keypair["did_key"]) - assert isinstance(pub, RSAPublicKey) - assert pub.public_numbers() == rsa_keypair["key"].public_key().public_numbers() - - def test_rsa_kid_with_fragment(self, rsa_keypair): - pub = _public_key_from_did_key(rsa_keypair["kid"]) - assert pub.public_numbers() == rsa_keypair["key"].public_key().public_numbers() - - def test_rsa_did_key_starts_with_z4mx(self, rsa_keypair): - assert rsa_keypair["did_key"].startswith("did:key:z4MX") + pub = _extract_ed25519_pub_from_did_key(" " + ED25519_DID_KEY + " ") + assert len(pub) == 32 def test_non_did_key_raises(self): with pytest.raises(ValueError, match="did:key"): - _public_key_from_did_key("did:web:example.com") + _extract_ed25519_pub_from_did_key("did:web:example.com") - def test_unsupported_multicodec_raises(self): + def test_invalid_multicodec_raises(self): import base58 - raw = bytes([0x80, 0x24]) + (b"\x00" * 32) # 0x1200 (P-256), not supported here + raw = bytes([0x80, 0x24]) + (b"\x00" * 32) bad_did = "did:key:z" + base58.b58encode(raw).decode() - with pytest.raises(ValueError, match="Unsupported did:key multicodec"): - _public_key_from_did_key(bad_did) + with pytest.raises(ValueError, match="Invalid did:key"): + _extract_ed25519_pub_from_did_key(bad_did) class TestDidWebToUrl: @@ -474,7 +230,14 @@ def test_non_did_web_raises(self): class TestFetchDidJson: def test_returns_parsed_json_on_200(self): doc = {"id": "did:web:example.com", "verificationMethod": []} - with _mock_did_json(doc) as mock_get: + mock_resp = MagicMock() + mock_resp.json.return_value = doc + mock_resp.raise_for_status = MagicMock() + + with patch( + "ce.commands.iir_sign_challenge.requests.get", + return_value=mock_resp, + ) as mock_get: result = _fetch_did_json("did:web:example.com") assert result == doc @@ -486,17 +249,34 @@ def test_http_error_propagates(self): mock_resp = MagicMock() mock_resp.raise_for_status.side_effect = requests.HTTPError("404 Not Found") - with patch(f"{MODULE}.requests.get", return_value=mock_resp): + with patch( + "ce.commands.iir_sign_challenge.requests.get", + return_value=mock_resp, + ): with pytest.raises(requests.HTTPError): _fetch_did_json("did:web:example.com") def test_non_object_response_raises(self): - with _mock_did_json(["not", "an", "object"]): + mock_resp = MagicMock() + mock_resp.json.return_value = ["not", "an", "object"] + mock_resp.raise_for_status = MagicMock() + + with patch( + "ce.commands.iir_sign_challenge.requests.get", + return_value=mock_resp, + ): with pytest.raises(ValueError, match="must be a JSON object"): _fetch_did_json("did:web:example.com") def test_passes_through_path_segments_in_url(self): - with _mock_did_json({"verificationMethod": []}) as mock_get: + mock_resp = MagicMock() + mock_resp.json.return_value = {"verificationMethod": []} + mock_resp.raise_for_status = MagicMock() + + with patch( + "ce.commands.iir_sign_challenge.requests.get", + return_value=mock_resp, + ) as mock_get: _fetch_did_json("did:web:example.com:users:alice") args, _ = mock_get.call_args @@ -517,20 +297,6 @@ def _doc(self, did, vm_id, pub_multibase): ], } - def _rsa_doc(self, did, vm_id, jwk, vm_type="JsonWebKey2020"): - return { - "id": did, - "verificationMethod": [ - { - "id": vm_id, - "type": vm_type, - "controller": did, - "publicKeyJwk": jwk, - } - ], - "authentication": [vm_id], - } - def _did_web_keypair(self): """Generate a real Ed25519 public key for did:web tests.""" import base58 @@ -552,7 +318,7 @@ def test_finds_key_by_absolute_kid(self): doc = self._doc(did, kid, pub_mb) result = _public_key_from_did_doc(kid=kid, did_doc=doc) - assert _raw_ed25519(result) == pub + assert result == pub def test_finds_key_when_vm_id_is_relative(self): pub, pub_mb = self._did_web_keypair() @@ -561,18 +327,18 @@ def test_finds_key_when_vm_id_is_relative(self): doc = self._doc(did, "#key-1", pub_mb) result = _public_key_from_did_doc(kid=kid, did_doc=doc) - assert _raw_ed25519(result) == pub + assert result == pub def test_raw_32_byte_pub_multibase_accepted(self): import base58 - pub, _ = self._did_web_keypair() + pub = b"\x05" * 32 pub_mb = "z" + base58.b58encode(pub).decode() did = "did:web:example.com" kid = f"{did}#key-1" doc = self._doc(did, kid, pub_mb) result = _public_key_from_did_doc(kid=kid, did_doc=doc) - assert _raw_ed25519(result) == pub + assert result == pub def test_kid_not_in_doc_raises(self): _, pub_mb = self._did_web_keypair() @@ -599,7 +365,7 @@ def test_skips_non_dict_entries(self): {"id": kid, "publicKeyMultibase": pub_mb}, ], } - assert _raw_ed25519(_public_key_from_did_doc(kid=kid, did_doc=doc)) == pub + assert _public_key_from_did_doc(kid=kid, did_doc=doc) == pub def test_skips_entries_without_id(self): pub, pub_mb = self._did_web_keypair() @@ -608,26 +374,26 @@ def test_skips_entries_without_id(self): doc = { "id": did, "verificationMethod": [ - {"publicKeyMultibase": "zSomething"}, + {"publicKeyMultibase": "zSomething"}, {"id": kid, "publicKeyMultibase": pub_mb}, ], } - assert _raw_ed25519(_public_key_from_did_doc(kid=kid, did_doc=doc)) == pub + assert _public_key_from_did_doc(kid=kid, did_doc=doc) == pub def test_invalid_public_key_multibase_raises(self): did = "did:web:example.com" kid = f"{did}#key-1" doc = self._doc(did, kid, "NOT-Z-PREFIXED") - with pytest.raises(ValueError, match="publicKeyMultibase"): + with pytest.raises(ValueError, match="Invalid publicKeyMultibase"): _public_key_from_did_doc(kid=kid, did_doc=doc) - def test_missing_public_key_raises(self): + def test_missing_public_key_multibase_raises(self): did = "did:web:example.com" kid = f"{did}#key-1" doc = {"id": did, "verificationMethod": [{"id": kid}]} - with pytest.raises(ValueError, match="neither an RSA publicKeyJwk"): + with pytest.raises(ValueError, match="Invalid publicKeyMultibase"): _public_key_from_did_doc(kid=kid, did_doc=doc) def test_unrecognized_pub_key_encoding_raises(self): @@ -641,70 +407,11 @@ def test_unrecognized_pub_key_encoding_raises(self): with pytest.raises(ValueError, match="Ed25519"): _public_key_from_did_doc(kid=kid, did_doc=doc) - def test_rsa_json_web_key_2020(self, rsa_keypair): - from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey - public_key = rsa_keypair["key"].public_key() - did = "did:web:example.com" - kid = f"{did}#key-2" - doc = self._rsa_doc(did, kid, _rsa_jwk(public_key, alg="RS256", use="sig")) - - result = _public_key_from_did_doc(kid=kid, did_doc=doc) - assert isinstance(result, RSAPublicKey) - assert result.public_numbers() == public_key.public_numbers() - - def test_rsa_relative_vm_id(self, rsa_keypair): - public_key = rsa_keypair["key"].public_key() - did = "did:web:example.com" - doc = self._rsa_doc(did, "#key-2", _rsa_jwk(public_key)) - - result = _public_key_from_did_doc(kid=f"{did}#key-2", did_doc=doc) - assert result.public_numbers() == public_key.public_numbers() - - def test_rsa_wrong_vm_type_raises(self, rsa_keypair): - did = "did:web:example.com" - kid = f"{did}#key-2" - doc = self._rsa_doc( - did, - kid, - _rsa_jwk(rsa_keypair["key"].public_key()), - vm_type="RsaVerificationKey2018", - ) - - with pytest.raises(ValueError, match="JsonWebKey2020"): - _public_key_from_did_doc(kid=kid, did_doc=doc) - - def test_rsa_jwk_with_private_part_raises(self, rsa_keypair): - did = "did:web:example.com" - kid = f"{did}#key-2" - doc = self._rsa_doc(did, kid, _rsa_jwk(rsa_keypair["key"].public_key(), d="AAAA")) - - with pytest.raises(ValueError, match="private key material"): - _public_key_from_did_doc(kid=kid, did_doc=doc) - - def test_picks_rsa_key_from_mixed_doc(self, rsa_keypair): - _, ed_mb = self._did_web_keypair() - public_key = rsa_keypair["key"].public_key() - did = "did:web:example.com" - doc = { - "id": did, - "verificationMethod": [ - {"id": f"{did}#key-1", "type": "Ed25519VerificationKey2020", "publicKeyMultibase": ed_mb}, - {"id": f"{did}#key-2", "type": "JsonWebKey2020", "publicKeyJwk": _rsa_jwk(public_key)}, - ], - } - - result = _public_key_from_did_doc(kid=f"{did}#key-2", did_doc=doc) - assert result.public_numbers() == public_key.public_numbers() - -class TestResolvePublicKeyForKid: +class TestResolvePublicKeyBytesForKid: def test_did_key_path(self): - pub = _resolve_public_key_for_kid(ED25519_KID) - assert len(_raw_ed25519(pub)) == 32 - - def test_rsa_did_key_path(self, rsa_keypair): - pub = _resolve_public_key_for_kid(rsa_keypair["kid"]) - assert pub.public_numbers() == rsa_keypair["key"].public_key().public_numbers() + pub = _resolve_public_key_bytes_for_kid(ED25519_KID) + assert len(pub) == 32 def test_did_web_path_fetches_doc(self): import base58 @@ -725,71 +432,86 @@ def test_did_web_path_fetches_doc(self): "verificationMethod": [{"id": kid, "publicKeyMultibase": pub_mb}], } - with _mock_did_json(doc): - result = _resolve_public_key_for_kid(kid) - assert _raw_ed25519(result) == pub + mock_resp = MagicMock() + mock_resp.json.return_value = doc + mock_resp.raise_for_status = MagicMock() + with patch( + "ce.commands.iir_sign_challenge.requests.get", + return_value=mock_resp, + ): + result = _resolve_public_key_bytes_for_kid(kid) + assert result == pub def test_unsupported_did_method_raises(self): with pytest.raises(ValueError, match="Unsupported DID method"): - _resolve_public_key_for_kid("did:ethr:0x123#key-1") + _resolve_public_key_bytes_for_kid("did:ethr:0x123#key-1") class TestSignPayload: - def test_returns_three_part_jwt_string(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): - _, _, kid = ed25519_keypair - token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) + def test_returns_three_part_jwt_string(self, ed25519_keypair, valid_challenge_payload): + priv, _, kid = ed25519_keypair + token = _sign_payload(priv, kid, valid_challenge_payload) assert isinstance(token, str) assert token.count(".") == 2 - def test_header_includes_alg_typ_kid(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): - _, _, kid = ed25519_keypair - token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) - header = _decode_segment(token, 0) + def test_header_includes_alg_typ_kid(self, ed25519_keypair, valid_challenge_payload): + priv, _, kid = ed25519_keypair + token = _sign_payload(priv, kid, valid_challenge_payload) + header_b64 = token.split(".")[0] + padded = header_b64 + "=" * (-len(header_b64) % 4) + header = json.loads(base64.urlsafe_b64decode(padded)) assert header["alg"] == "EdDSA" assert header["typ"] == "JWT" assert header["kid"] == kid - def test_payload_round_trips(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): - _, _, kid = ed25519_keypair - token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) - assert _decode_segment(token, 1) == valid_challenge_payload - - def test_rs256_header(self, rsa_keypair, valid_challenge_payload): - payload = dict(valid_challenge_payload, did=rsa_keypair["kid"]) - token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], payload) - header = _decode_segment(token, 0) - assert header["alg"] == "RS256" - assert header["typ"] == "JWT" - assert header["kid"] == rsa_keypair["kid"] - - def test_rs256_signature_is_modulus_length(self, rsa_keypair, valid_challenge_payload): - token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) - segment = token.split(".")[2] - signature = base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)) - assert len(signature) == 256 # 2048-bit key + def test_payload_round_trips(self, ed25519_keypair, valid_challenge_payload): + priv, _, kid = ed25519_keypair + token = _sign_payload(priv, kid, valid_challenge_payload) + payload_b64 = token.split(".")[1] + padded = payload_b64 + "=" * (-len(payload_b64) % 4) + decoded = json.loads(base64.urlsafe_b64decode(padded)) + assert decoded == valid_challenge_payload + def test_bad_private_key_raises(self, valid_challenge_payload): + with pytest.raises(ValueError): + _sign_payload("zNOT-A-REAL-KEY", ED25519_KID, valid_challenge_payload) class TestVerifySignatureOnly: - def test_valid_signature_returns_none(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): - _, _, kid = ed25519_keypair - token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) - _verify_signature_only(token, _public_key_from_did_key(kid), "EdDSA") + def test_valid_signature_returns_none(self, ed25519_keypair, valid_challenge_payload): + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + + priv, _, kid = ed25519_keypair + token = _sign_payload(priv, kid, valid_challenge_payload) + pub_bytes = _extract_ed25519_pub_from_did_key(kid) + pub_key = Ed25519PublicKey.from_public_bytes(pub_bytes) - def test_tampered_signature_raises(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): + _verify_signature_only(token, pub_key) + + def test_tampered_signature_raises(self, ed25519_keypair, valid_challenge_payload): import jwt + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey - _, _, kid = ed25519_keypair - token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) + priv, _, kid = ed25519_keypair + token = _sign_payload(priv, kid, valid_challenge_payload) + parts = token.split(".") + first = parts[2][0] + parts[2] = ("B" if first != "B" else "C") + parts[2][1:] + tampered = ".".join(parts) + + pub_bytes = _extract_ed25519_pub_from_did_key(kid) + pub_key = Ed25519PublicKey.from_public_bytes(pub_bytes) with pytest.raises(jwt.exceptions.InvalidSignatureError): - _verify_signature_only(_tamper_signature(token), _public_key_from_did_key(kid), "EdDSA") + _verify_signature_only(tampered, pub_key) - def test_does_not_check_expiry(self, ed25519_keypair, ed25519_signing_key): + def test_does_not_check_expiry(self, ed25519_keypair): """Even with iat/exp in the past, verification must pass — the function exists specifically to verify the signature only.""" - _, _, kid = ed25519_keypair + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + + priv, _, kid = ed25519_keypair payload = { "did": ED25519_DID_KEY, "challenge": CHALLENGE_UUID, @@ -797,160 +519,34 @@ def test_does_not_check_expiry(self, ed25519_keypair, ed25519_signing_key): "iat": 1, "exp": 2, } - token = _sign_payload(ed25519_signing_key, "EdDSA", kid, payload) - _verify_signature_only(token, _public_key_from_did_key(kid), "EdDSA") + token = _sign_payload(priv, kid, payload) + pub_bytes = _extract_ed25519_pub_from_did_key(kid) + pub_key = Ed25519PublicKey.from_public_bytes(pub_bytes) - def test_rs256_valid(self, rsa_keypair, valid_challenge_payload): - token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) - _verify_signature_only(token, _public_key_from_did_key(rsa_keypair["kid"]), "RS256") - - def test_rs256_tampered_raises(self, rsa_keypair, valid_challenge_payload): - import jwt - - token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) - with pytest.raises(jwt.exceptions.InvalidSignatureError): - _verify_signature_only( - _tamper_signature(token), - _public_key_from_did_key(rsa_keypair["kid"]), - "RS256", - ) - - def test_rs256_token_rejected_when_only_eddsa_allowed(self, rsa_keypair, valid_challenge_payload): - import jwt - - token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) - with pytest.raises(jwt.PyJWTError): - _verify_signature_only(token, _public_key_from_did_key(rsa_keypair["kid"]), "EdDSA") + _verify_signature_only(token, pub_key) class TestAssertSignatureVerifiable: - def test_passes_for_valid_token(self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload): - _, _, kid = ed25519_keypair - token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) - _assert_signature_verifiable(token, kid, "EdDSA") + def test_passes_for_valid_token(self, ed25519_keypair, valid_challenge_payload): + priv, _, kid = ed25519_keypair + token = _sign_payload(priv, kid, valid_challenge_payload) + _assert_signature_verifiable(token, kid) def test_tampered_token_raises_click_exception( - self, ed25519_keypair, ed25519_signing_key, valid_challenge_payload + self, ed25519_keypair, valid_challenge_payload ): - _, _, kid = ed25519_keypair - token = _sign_payload(ed25519_signing_key, "EdDSA", kid, valid_challenge_payload) + priv, _, kid = ed25519_keypair + token = _sign_payload(priv, kid, valid_challenge_payload) + parts = token.split(".") + first = parts[2][0] + parts[2] = ("B" if first != "B" else "C") + parts[2][1:] + tampered = ".".join(parts) with pytest.raises(click.ClickException, match="Signature verification failed"): - _assert_signature_verifiable(_tamper_signature(token), kid, "EdDSA") + _assert_signature_verifiable(tampered, kid) def test_malformed_token_raises_click_exception(self, ed25519_keypair): _, _, kid = ed25519_keypair with pytest.raises(click.ClickException, match="JWT verification error"): - _assert_signature_verifiable("not.a.real.jwt", kid, "EdDSA") - - def test_rs256_passes_for_valid_token(self, rsa_keypair, valid_challenge_payload): - token = _sign_payload(rsa_keypair["key"], "RS256", rsa_keypair["kid"], valid_challenge_payload) - _assert_signature_verifiable(token, rsa_keypair["kid"], "RS256") - - def test_rs256_against_ed25519_did_raises(self, rsa_keypair, valid_challenge_payload): - token = _sign_payload(rsa_keypair["key"], "RS256", ED25519_KID, valid_challenge_payload) - with pytest.raises(click.ClickException, match="resolves to an Ed25519 key"): - _assert_signature_verifiable(token, ED25519_KID, "RS256") - - def test_eddsa_against_rsa_did_raises(self, ed25519_signing_key, rsa_keypair, valid_challenge_payload): - token = _sign_payload(ed25519_signing_key, "EdDSA", rsa_keypair["kid"], valid_challenge_payload) - with pytest.raises(click.ClickException, match="resolves to an RSA key"): - _assert_signature_verifiable(token, rsa_keypair["kid"], "EdDSA") - - def test_rs256_did_web(self, rsa_keypair, valid_challenge_payload): - did = "did:web:example.com" - kid = f"{did}#key-2" - doc = { - "id": did, - "verificationMethod": [ - { - "id": kid, - "type": "JsonWebKey2020", - "publicKeyJwk": _rsa_jwk(rsa_keypair["key"].public_key(), alg="RS256"), - } - ], - "authentication": [kid], - } - token = _sign_payload(rsa_keypair["key"], "RS256", kid, valid_challenge_payload) - - with _mock_did_json(doc): - _assert_signature_verifiable(token, kid, "RS256") - - - -class TestSignCommand: - """End-to-end through the click command.""" - - def _run(self, args): - result = CliRunner().invoke(sign_individual_challenge, args) - return result.exit_code, result.output - - def test_rsa_key_file_signs_rs256(self, rsa_keypair, tmp_path, valid_challenge_payload): - key_path = tmp_path / "rsa.pem" - key_path.write_bytes(rsa_keypair["pem_pkcs8"]) - challenge = _write_json( - tmp_path / "challenge.json", - dict(valid_challenge_payload, did=rsa_keypair["kid"]), - ) - out_path = tmp_path / "signed.jwt" - - code, output = self._run( - ["--private-key-file", str(key_path), "--challenge-file", str(challenge), "-o", str(out_path)] - ) - - assert code == 0, output - token = out_path.read_text(encoding="utf-8") - header = _decode_segment(token, 0) - assert header["alg"] == "RS256" - assert header["kid"] == rsa_keypair["kid"] - - def test_rsa_key_pem_text_signs_rs256(self, rsa_keypair, tmp_path, valid_challenge_payload): - challenge = _write_json( - tmp_path / "challenge.json", - dict(valid_challenge_payload, did=rsa_keypair["kid"]), - ) - - code, output = self._run( - ["--private-key-pem", rsa_keypair["pem_pkcs8"].decode(), "--challenge-file", str(challenge)] - ) - - assert code == 0, output - - def test_ed25519_multibase_still_signs_eddsa(self, ed25519_keypair, tmp_path, valid_challenge_payload): - priv, _, kid = ed25519_keypair - challenge = _write_json(tmp_path / "challenge.json", dict(valid_challenge_payload, did=kid)) - out_path = tmp_path / "signed.jwt" - - code, output = self._run( - ["--private-key", priv, "--challenge-file", str(challenge), "-o", str(out_path)] - ) - - assert code == 0, output - assert _decode_segment(out_path.read_text(encoding="utf-8"), 0)["alg"] == "EdDSA" - - def test_two_key_options_fail(self, ed25519_keypair, rsa_keypair, tmp_path, valid_challenge_payload): - priv, _, _ = ed25519_keypair - challenge = _write_json(tmp_path / "challenge.json", valid_challenge_payload) - - code, output = self._run( - [ - "--private-key", priv, - "--private-key-pem", rsa_keypair["pem_pkcs8"].decode(), - "--challenge-file", str(challenge), - ] - ) - - assert code != 0 - assert "exactly one" in output - - def test_missing_required_field_fails(self, rsa_keypair, tmp_path, valid_challenge_payload): - payload = dict(valid_challenge_payload, did=rsa_keypair["kid"]) - del payload["exp"] - challenge = _write_json(tmp_path / "challenge.json", payload) - - code, output = self._run( - ["--private-key-pem", rsa_keypair["pem_pkcs8"].decode(), "--challenge-file", str(challenge)] - ) + _assert_signature_verifiable("not.a.real.jwt", kid) - assert code != 0 - assert "exp" in output \ No newline at end of file From 29906c50d964e2490e4c8db18dd8ae74a8f18f27 Mon Sep 17 00:00:00 2001 From: Sneha Edula Date: Thu, 19 Nov 2026 19:51:52 -0500 Subject: [PATCH 3/6] pass --algorithm --- ce/commands/iir.py | 9 +- ce/commands/iir_sign_challenge.py | 89 ++++++-- ce/commands/iir_sign_challenge_rs256.py | 135 ++++------- tests/test_iir_sign_challenge_rs256.py | 146 ++++++------ tests/test_sign_command_algorithm.py | 286 ++++++++++++++++++++++++ 5 files changed, 481 insertions(+), 184 deletions(-) create mode 100644 tests/test_sign_command_algorithm.py diff --git a/ce/commands/iir.py b/ce/commands/iir.py index 5f6ccbe..1790424 100644 --- a/ce/commands/iir.py +++ b/ce/commands/iir.py @@ -1,7 +1,6 @@ """IIR command group: - ce iir challenge sign # single challenge (Ed25519, EdDSA) - ce iir challenge sign-rs256 # single challenge (RSA, RS256) + ce iir challenge sign # single challenge (--algorithm Ed25519 | RS256) ce iir challenge bulk-sign # bulk DID challenge signing ce iir issuer-did publish # publish signed challenges to IIR """ @@ -15,7 +14,6 @@ from rich.console import Console from ce.commands.iir_sign_challenge import sign_individual_challenge -from ce.commands.iir_sign_challenge_rs256 import sign_rs256_challenge from ce.auth.token_manager import require_login from ce.config.context import require_environment @@ -51,11 +49,6 @@ def issuer_did_group() -> None: challenge_group.add_command(sign_individual_challenge, name="sign") -# ce iir challenge sign-rs256 (single, RSA) - -challenge_group.add_command(sign_rs256_challenge, name="sign-rs256") - - # ce iir challenge bulk-sign @challenge_group.command("bulk-sign") diff --git a/ce/commands/iir_sign_challenge.py b/ce/commands/iir_sign_challenge.py index 3b79521..707f056 100644 --- a/ce/commands/iir_sign_challenge.py +++ b/ce/commands/iir_sign_challenge.py @@ -1,13 +1,19 @@ """`ce iir challenge sign` - sign and verify a Proof JWT for a single CE challenge. -Reads a challenge JSON file produced by CE, signs it with an Ed25519 private key -(alg=EdDSA), and verifies the resulting JWT against the public key resolved from -the DID (did:key or did:web). No login required. +Reads a challenge JSON file produced by CE, signs it with a private key, and +verifies the resulting JWT against the public key resolved from the DID +(did:key or did:web). No login required. + +--algorithm picks the signing method: + - Ed25519 : alg=EdDSA, --private-key is a multibase seed (z...). Handled in this module. + - RS256 : alg=RS256, --private-key is a PEM file path or the PEM text. + Handled in ce.commands.iir_sign_challenge_rs256. """ from __future__ import annotations import json +from pathlib import Path from typing import Any, Dict, Tuple import base58 @@ -20,6 +26,8 @@ ) from rich.console import Console +from ce.commands import iir_sign_challenge_rs256 as _rs256 + console = Console() err_console = Console(stderr=True) @@ -233,13 +241,37 @@ def _assert_signature_verifiable(token: str, kid: str) -> None: # Click command +ALGORITHM_ED25519 = "Ed25519" +ALGORITHM_RS256 = "RS256" + + +def _looks_like_rsa_key(value: str) -> bool: + """True when an Ed25519 --private-key value looks like a PEM key or a key file path.""" + if "-----BEGIN" in value or "\\n" in value: + return True + try: + return Path(value).expanduser().is_file() + except OSError: + return False + + @click.command("sign") +@click.option( + "--algorithm", + "algorithm", + required=True, + type=click.Choice([ALGORITHM_ED25519, ALGORITHM_RS256]), + help="Signing algorithm: Ed25519 (alg=EdDSA) or RS256 (RSA).", +) @click.option( "--private-key", "private_key", required=True, - metavar="MULTIBASE", - help="Ed25519 private seed (multibase base58btc, starts with 'z').", + metavar="KEY", + help=( + "Ed25519: private seed (multibase base58btc, starts with 'z'). " + "RS256: path to an unencrypted PEM/DER key file, or the PEM text." + ), ) @click.option( "--challenge-file", @@ -258,22 +290,31 @@ def _assert_signature_verifiable(token: str, kid: str) -> None: help="Write JWT to this file (otherwise printed to stdout).", ) def sign_individual_challenge( + algorithm: str, private_key: str, challenge_file: str, out_path: str | None, ) -> None: - """Sign a single CE challenge JSON file and produce a Proof JWT (EdDSA/Ed25519). + """Sign a single CE challenge JSON file and produce a Proof JWT. \b + --algorithm Ed25519 : --private-key is the multibase seed (z...). + --algorithm RS256 : --private-key is a PEM file path or the PEM text. The challenge JSON must include: did, challenge, aud, iat, exp. Signature verification uses did:key (offline) or did:web (HTTPS). \b - Example: - ce iir challenge sign \\ + Examples: + ce iir challenge sign --algorithm Ed25519 \\ --private-key zABC... \\ --challenge-file challenge.json \\ --output signed-challenge.jwt + + \b + ce iir challenge sign --algorithm RS256 \\ + --private-key rsa-key.pem \\ + --challenge-file challenge.json \\ + --output signed-challenge.jwt """ try: with open(challenge_file, "r", encoding="utf-8") as f: @@ -299,21 +340,29 @@ def sign_individual_challenge( kid = did_value.strip() - try: - token = _sign_payload(private_key, kid, payload_obj) - except ValueError as e: - raise click.ClickException(f"Signing failed: {e}") - - try: - _assert_signature_verifiable(token, kid) - except requests.RequestException as e: - raise click.ClickException(f"Failed to fetch did.json: {e}") - except ValueError as e: - raise click.ClickException(f"DID resolution error: {e}") + if algorithm == ALGORITHM_RS256: + token = _rs256.sign_and_verify(private_key, kid, payload_obj) + else: + if _looks_like_rsa_key(private_key): + raise click.ClickException( + "This looks like an RSA/PEM key. Use --algorithm RS256 for RSA keys." + ) + + try: + token = _sign_payload(private_key, kid, payload_obj) + except ValueError as e: + raise click.ClickException(f"Signing failed: {e}") + + try: + _assert_signature_verifiable(token, kid) + except requests.RequestException as e: + raise click.ClickException(f"Failed to fetch did.json: {e}") + except ValueError as e: + raise click.ClickException(f"DID resolution error: {e}") if out_path: with open(out_path, "w", encoding="utf-8") as f: f.write(token) err_console.print(f"Wrote Proof JWT to: [cyan]{out_path}[/cyan]") else: - click.echo(token) \ No newline at end of file + click.echo(token) diff --git a/ce/commands/iir_sign_challenge_rs256.py b/ce/commands/iir_sign_challenge_rs256.py index 3c956ce..20ae9aa 100644 --- a/ce/commands/iir_sign_challenge_rs256.py +++ b/ce/commands/iir_sign_challenge_rs256.py @@ -1,10 +1,8 @@ -"""`ce iir challenge sign-rs256` - sign and verify a Proof JWT for a CE challenge with RSA (RS256). +"""RS256 signing for `ce iir challenge sign --algorithm RS256`. -Reads a challenge JSON file produced by CE, signs it with an RSA private key -(alg=RS256), and verifies the resulting JWT against the public key resolved from -the DID (did:key or did:web). No login required. - -Ed25519 keys are handled by `ce iir challenge sign` (alg=EdDSA). +Signs a CE challenge with an RSA private key (alg=RS256) and verifies the +resulting JWT against the public key resolved from the DID (did:key or did:web). +The Ed25519 path lives in ce.commands.iir_sign_challenge. Key resolution: - did:key : multicodec 0x1205 (rsa-pub), PKCS#1 RSAPublicKey DER, base58btc. @@ -18,6 +16,7 @@ import base64 import binascii import json +from pathlib import Path from typing import Any, Dict, Tuple from urllib.parse import quote, unquote @@ -38,9 +37,13 @@ MIN_RSA_KEY_SIZE_BITS = 2048 VERIFICATION_METHOD_TYPE = "JsonWebKey2020" - +# Verification relationships the IIR API accepts for an RSA key. ACCEPTED_RELATIONSHIPS = ("authentication",) + + +# Multibase + multicodec helpers + def _parse_uvarint(data: bytes) -> Tuple[int, int]: x = 0 s = 0 @@ -365,85 +368,48 @@ def _assert_signature_verifiable(token: str, kid: str) -> None: -# Click command - -@click.command("sign-rs256") -@click.option( - "--private-key-file", - "private_key_file", - default=None, - type=click.Path(exists=True, dir_okay=False, readable=True), - metavar="PATH", - help="RSA private key file, PEM or DER (PKCS#8 or PKCS#1), unencrypted.", -) -@click.option( - "--private-key-pem", - "private_key_pem", - default=None, - metavar="TEXT", - help="Pasted RSA private key: full PEM (newlines or literal \\n) or just the base64 body.", -) -@click.option( - "--challenge-file", - "challenge_file", - required=True, - type=click.Path(exists=True, dir_okay=False, readable=True), - metavar="PATH", - help="Path to CE-generated challenge JSON file.", -) -@click.option( - "--output", "-o", - "out_path", - default=None, - type=click.Path(dir_okay=False, writable=True), - metavar="PATH", - help="Write JWT to this file (otherwise printed to stdout).", -) -def sign_rs256_challenge( - private_key_file: str | None, - private_key_pem: str | None, - challenge_file: str, - out_path: str | None, -) -> None: - """Sign a single CE challenge JSON file with an RSA key and produce a Proof JWT (RS256). - - \b - Give exactly one of --private-key-file or --private-key-pem. - The challenge JSON must include: did, challenge, aud, iat, exp. - Signature verification uses did:key (offline) or did:web (HTTPS). - - \b - Example: - ce iir challenge sign-rs256 \\ - --private-key-file rsa-key.pem \\ - --challenge-file challenge.json \\ - --output signed-challenge.jwt - """ - signing_key = _load_signing_key(private_key_file, private_key_pem) +# Entry point used by `ce iir challenge sign --algorithm RS256` - try: - with open(challenge_file, "r", encoding="utf-8") as f: - payload_obj = json.load(f) - except json.JSONDecodeError as e: - raise click.ClickException(f"Challenge file is not valid JSON: {e}") +def load_private_key_argument(value: str) -> RSAPrivateKey: + """--private-key for RS256: a path to a PEM/DER key file, or the PEM text itself.""" + value = value.strip() + if not value: + raise click.ClickException("--private-key is empty.") - if not isinstance(payload_obj, dict): - raise click.ClickException("Challenge payload must be a JSON object.") + is_text = "-----BEGIN" in value or "\\n" in value + if not is_text: + try: + path = Path(value).expanduser() + if path.is_file(): + return _load_signing_key(str(path), None) + except OSError: + pass - required_fields = ["did", "challenge", "aud", "iat", "exp"] - missing = [k for k in required_fields if k not in payload_obj] - if missing: - raise click.ClickException( - f"Challenge JSON missing required field(s): {', '.join(missing)}" - ) + if value.startswith("z") and len(value) < 120: + raise click.ClickException( + "This looks like an Ed25519 multibase key. Use --algorithm Ed25519 for Ed25519 keys." + ) + + if not _looks_like_base64(value): + raise click.ClickException(f"RSA private key file not found: {value}") + + return _load_signing_key(None, value) - did_value = payload_obj.get("did") - if not isinstance(did_value, str) or not did_value.strip(): - raise click.ClickException( - 'Challenge JSON must include a non-empty string field "did".' - ) - kid = did_value.strip() +def _looks_like_base64(value: str) -> bool: + body = "".join(value.split()) + if len(body) < 100: + return False + try: + base64.b64decode(body, validate=True) + except (binascii.Error, ValueError): + return False + return True + + +def sign_and_verify(private_key_value: str, kid: str, payload_obj: Dict[str, Any]) -> str: + """Load the RSA key, sign the challenge with RS256, and verify it against the DID.""" + signing_key = load_private_key_argument(private_key_value) try: token = _sign_payload(signing_key, kid, payload_obj) @@ -457,9 +423,4 @@ def sign_rs256_challenge( except ValueError as e: raise click.ClickException(f"DID resolution error: {e}") - if out_path: - with open(out_path, "w", encoding="utf-8") as f: - f.write(token) - err_console.print(f"Wrote Proof JWT to: [cyan]{out_path}[/cyan]") - else: - click.echo(token) + return token diff --git a/tests/test_iir_sign_challenge_rs256.py b/tests/test_iir_sign_challenge_rs256.py index 85807e6..09bee39 100644 --- a/tests/test_iir_sign_challenge_rs256.py +++ b/tests/test_iir_sign_challenge_rs256.py @@ -1,5 +1,5 @@ """ -Unit tests for ce.commands.iir_sign_challenge_rs256. +Unit tests for ce.commands.iir_sign_challenge_rs256 (the RS256 path of `ce iir challenge sign`). Run with: pytest -m unit -s """ @@ -14,7 +14,6 @@ import click import pytest import requests -from click.testing import CliRunner @@ -34,7 +33,8 @@ _resolve_public_key_for_kid, _sign_payload, _verify_signature_only, - sign_rs256_challenge, + load_private_key_argument, + sign_and_verify, ) @@ -515,90 +515,98 @@ def test_malformed_token_rejected(self, rsa_kid): -class TestSignRs256Command: - """End-to-end through the click command.""" - - def _run(self, args): - result = CliRunner().invoke(sign_rs256_challenge, args) - return result.exit_code, result.output - - def _key_file(self, rsa_key, tmp_path) -> Path: +class TestLoadPrivateKeyArgument: + def test_file_path(self, rsa_key, tmp_path): from cryptography.hazmat.primitives import serialization path = tmp_path / "rsa.pem" path.write_bytes(_pem(rsa_key, serialization.PrivateFormat.PKCS8)) - return path - - def test_key_file_did_key(self, rsa_key, rsa_kid, tmp_path, challenge_payload): - challenge = _write_json(tmp_path / "challenge.json", challenge_payload) - out_path = tmp_path / "signed.jwt" - - code, output = self._run( - [ - "--private-key-file", str(self._key_file(rsa_key, tmp_path)), - "--challenge-file", str(challenge), - "-o", str(out_path), - ] - ) + assert load_private_key_argument(str(path)).key_size == 2048 - assert code == 0, output - header = _decode_segment(out_path.read_text(encoding="utf-8"), 0) - assert header["alg"] == "RS256" - assert header["kid"] == rsa_kid + def test_pem_text(self, rsa_key): + from cryptography.hazmat.primitives import serialization + text = _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode() + assert load_private_key_argument(text).key_size == 2048 - def test_pasted_pem_did_web(self, rsa_key, tmp_path, challenge_payload): + def test_pem_text_with_literal_backslash_n(self, rsa_key): from cryptography.hazmat.primitives import serialization - challenge = _write_json(tmp_path / "challenge.json", dict(challenge_payload, did=DID_WEB_KID)) + text = _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode().replace("\n", "\\n") + assert load_private_key_argument(text).key_size == 2048 - with _mock_did_json(_did_web_doc(rsa_key.public_key())): - code, output = self._run( - [ - "--private-key-pem", _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode(), - "--challenge-file", str(challenge), - ] - ) - - assert code == 0, output - token = output.strip().splitlines()[-1] - assert _decode_segment(token, 0)["kid"] == DID_WEB_KID + def test_bare_base64_body(self, rsa_key): + from cryptography.hazmat.primitives import serialization + body = "".join( + line + for line in _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode().splitlines() + if "-----" not in line + ) + assert load_private_key_argument(body).key_size == 2048 + + def test_missing_file(self, tmp_path): + with pytest.raises(click.ClickException, match="RSA private key file not found"): + load_private_key_argument(str(tmp_path / "missing.pem")) + + def test_ed25519_multibase_gets_hint(self): + with pytest.raises(click.ClickException, match="--algorithm Ed25519"): + load_private_key_argument("z3u2en7t5LR2WtQH5PfsRMHEsVGzpW2GZaRcX5qnwX4bBEzhJR") - def test_ed25519_key_rejected(self, tmp_path, challenge_payload): + def test_ed25519_pem_rejected(self, tmp_path): from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey - key_path = tmp_path / "ed.pem" - key_path.write_bytes(_pem(Ed25519PrivateKey.generate(), serialization.PrivateFormat.PKCS8)) - challenge = _write_json(tmp_path / "challenge.json", challenge_payload) + path = tmp_path / "ed.pem" + path.write_bytes(_pem(Ed25519PrivateKey.generate(), serialization.PrivateFormat.PKCS8)) + with pytest.raises(click.ClickException, match="Expected an RSA private key"): + load_private_key_argument(str(path)) - code, output = self._run(["--private-key-file", str(key_path), "--challenge-file", str(challenge)]) + def test_small_key_rejected(self, tmp_path): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import rsa + path = tmp_path / "small.pem" + path.write_bytes(_pem(rsa.generate_private_key(public_exponent=65537, key_size=1024), serialization.PrivateFormat.PKCS8)) + with pytest.raises(click.ClickException, match="2048"): + load_private_key_argument(str(path)) - assert code != 0 - assert "ce iir challenge sign" in output + def test_empty_rejected(self): + with pytest.raises(click.ClickException, match="empty"): + load_private_key_argument(" ") - def test_did_is_ed25519_rejected(self, rsa_key, tmp_path, challenge_payload): - challenge = _write_json(tmp_path / "challenge.json", dict(challenge_payload, did=ED25519_DID_KEY)) - code, output = self._run( - ["--private-key-file", str(self._key_file(rsa_key, tmp_path)), "--challenge-file", str(challenge)] - ) +class TestSignAndVerify: + def test_did_key(self, rsa_key, rsa_kid, tmp_path, challenge_payload): + from cryptography.hazmat.primitives import serialization + path = tmp_path / "rsa.pem" + path.write_bytes(_pem(rsa_key, serialization.PrivateFormat.PKCS8)) + + token = sign_and_verify(str(path), rsa_kid, challenge_payload) - assert code != 0 - assert "not an RSA public key" in output + assert _decode_segment(token, 0) == {"typ": "JWT", "alg": "RS256", "kid": rsa_kid} + assert _decode_segment(token, 1) == challenge_payload - def test_missing_required_field_rejected(self, rsa_key, tmp_path, challenge_payload): - payload = dict(challenge_payload) - del payload["exp"] - challenge = _write_json(tmp_path / "challenge.json", payload) + def test_did_web(self, rsa_key, challenge_payload): + from cryptography.hazmat.primitives import serialization + text = _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode() - code, output = self._run( - ["--private-key-file", str(self._key_file(rsa_key, tmp_path)), "--challenge-file", str(challenge)] - ) + with _mock_did_json(_did_web_doc(rsa_key.public_key())): + token = sign_and_verify(text, DID_WEB_KID, dict(challenge_payload, did=DID_WEB_KID)) - assert code != 0 - assert "exp" in output + assert _decode_segment(token, 0)["kid"] == DID_WEB_KID - def test_no_key_option_rejected(self, tmp_path, challenge_payload): - challenge = _write_json(tmp_path / "challenge.json", challenge_payload) + def test_wrong_key_for_did(self, other_rsa_key, rsa_kid, challenge_payload): + from cryptography.hazmat.primitives import serialization + text = _pem(other_rsa_key, serialization.PrivateFormat.PKCS8).decode() + with pytest.raises(click.ClickException, match="Signature verification failed"): + sign_and_verify(text, rsa_kid, challenge_payload) - code, output = self._run(["--challenge-file", str(challenge)]) + def test_ed25519_did_rejected(self, rsa_key, challenge_payload): + from cryptography.hazmat.primitives import serialization + text = _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode() + with pytest.raises(click.ClickException, match="not an RSA public key"): + sign_and_verify(text, ED25519_DID_KEY, dict(challenge_payload, did=ED25519_DID_KEY)) - assert code != 0 - assert "exactly one" in output + def test_did_web_fetch_error(self, rsa_key, challenge_payload): + from cryptography.hazmat.primitives import serialization + text = _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode() + mock_resp = MagicMock() + mock_resp.raise_for_status.side_effect = requests.HTTPError("404 Not Found") + with patch(f"{MODULE}.requests.get", return_value=mock_resp): + with pytest.raises(click.ClickException, match="Failed to fetch did.json"): + sign_and_verify(text, DID_WEB_KID, dict(challenge_payload, did=DID_WEB_KID)) diff --git a/tests/test_sign_command_algorithm.py b/tests/test_sign_command_algorithm.py new file mode 100644 index 0000000..370fe33 --- /dev/null +++ b/tests/test_sign_command_algorithm.py @@ -0,0 +1,286 @@ +""" +Unit tests for `ce iir challenge sign --algorithm Ed25519|RS256`. +Run with: + pytest -m unit -s +""" + +from __future__ import annotations + +import base64 +import json +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +from click.testing import CliRunner + + + +pytestmark = pytest.mark.unit + + +from ce.commands.iir_sign_challenge import sign_individual_challenge + + +RS256_MODULE = "ce.commands.iir_sign_challenge_rs256" + +CHALLENGE_UUID = "11111111-2222-3333-4444-555555555555" +CTID = "ce-12345678-1234-1234-1234-123456789abc" +DID_WEB = "did:web:example.com" +DID_WEB_KID = f"{DID_WEB}#key-1" + + + +# Helpers + +def _run(args): + result = CliRunner().invoke(sign_individual_challenge, args) + return result.exit_code, result.output + + +def _decode_segment(token: str, index: int) -> dict: + segment = token.split(".")[index] + return json.loads(base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))) + + +def _write_challenge(tmp_path: Path, did: str) -> Path: + path = tmp_path / "challenge.json" + path.write_text( + json.dumps( + { + "did": did, + "challenge": CHALLENGE_UUID, + "aud": "ce-api", + "iat": 1700000000, + "exp": 1700003600, + "ctid": CTID, + } + ), + encoding="utf-8", + ) + return path + + +def _b64url_uint(value: int) -> str: + raw = value.to_bytes((value.bit_length() + 7) // 8, "big") + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + + +# Fixtures + +@pytest.fixture(scope="session") +def ed25519_keys(): + """(private multibase seed, did:key kid) for a fresh Ed25519 key.""" + import base58 + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + + sk = Ed25519PrivateKey.generate() + seed = sk.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption()) + pub = sk.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) + did = "did:key:z" + base58.b58encode(bytes([0xED, 0x01]) + pub).decode() + + return "z" + base58.b58encode(seed).decode(), f"{did}#{did[len('did:key:'):]}" + + +@pytest.fixture(scope="session") +def rsa_key(): + from cryptography.hazmat.primitives.asymmetric import rsa + + return rsa.generate_private_key(public_exponent=65537, key_size=2048) + + +@pytest.fixture(scope="session") +def rsa_kid(rsa_key): + import base58 + from cryptography.hazmat.primitives import serialization + + pkcs1 = rsa_key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1) + did = "did:key:z" + base58.b58encode(bytes([0x85, 0x24]) + pkcs1).decode() + return f"{did}#{did[len('did:key:'):]}" + + +@pytest.fixture +def rsa_pem_text(rsa_key) -> str: + from cryptography.hazmat.primitives import serialization + + return rsa_key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ).decode() + + +@pytest.fixture +def rsa_pem_file(rsa_pem_text, tmp_path) -> Path: + path = tmp_path / "rsa-key.pem" + path.write_text(rsa_pem_text, encoding="ascii") + return path + + + +class TestAlgorithmOption: + def test_algorithm_is_required(self, ed25519_keys, tmp_path): + priv, kid = ed25519_keys + code, output = _run(["--private-key", priv, "--challenge-file", str(_write_challenge(tmp_path, kid))]) + + assert code != 0 + assert "--algorithm" in output + + @pytest.mark.parametrize("value", ["rs256", "ed25519", "EdDSA", "RSA", "HS256"]) + def test_only_exact_values_accepted(self, ed25519_keys, tmp_path, value): + priv, kid = ed25519_keys + code, output = _run( + ["--algorithm", value, "--private-key", priv, "--challenge-file", str(_write_challenge(tmp_path, kid))] + ) + + assert code != 0 + assert "Invalid value for '--algorithm'" in output + + def test_help_lists_both_algorithms(self): + code, output = _run(["--help"]) + + assert code == 0 + assert "Ed25519" in output and "RS256" in output + + + +class TestEd25519: + def test_signs_eddsa(self, ed25519_keys, tmp_path): + priv, kid = ed25519_keys + out_path = tmp_path / "signed.jwt" + + code, output = _run( + [ + "--algorithm", "Ed25519", + "--private-key", priv, + "--challenge-file", str(_write_challenge(tmp_path, kid)), + "-o", str(out_path), + ] + ) + + assert code == 0, output + assert _decode_segment(out_path.read_text(encoding="utf-8"), 0) == {"typ": "JWT", "alg": "EdDSA", "kid": kid} + + def test_rsa_pem_file_gets_hint(self, rsa_pem_file, ed25519_keys, tmp_path): + _, kid = ed25519_keys + code, output = _run( + [ + "--algorithm", "Ed25519", + "--private-key", str(rsa_pem_file), + "--challenge-file", str(_write_challenge(tmp_path, kid)), + ] + ) + + assert code != 0 + assert "--algorithm RS256" in output + + def test_rsa_pem_text_gets_hint(self, rsa_pem_text, ed25519_keys, tmp_path): + _, kid = ed25519_keys + code, output = _run( + [ + "--algorithm", "Ed25519", + "--private-key", rsa_pem_text, + "--challenge-file", str(_write_challenge(tmp_path, kid)), + ] + ) + + assert code != 0 + assert "--algorithm RS256" in output + + + +class TestRs256: + def test_pem_file_did_key(self, rsa_pem_file, rsa_kid, tmp_path): + out_path = tmp_path / "signed.jwt" + + code, output = _run( + [ + "--algorithm", "RS256", + "--private-key", str(rsa_pem_file), + "--challenge-file", str(_write_challenge(tmp_path, rsa_kid)), + "-o", str(out_path), + ] + ) + + assert code == 0, output + assert _decode_segment(out_path.read_text(encoding="utf-8"), 0) == {"typ": "JWT", "alg": "RS256", "kid": rsa_kid} + + def test_pem_text_did_web(self, rsa_key, rsa_pem_text, tmp_path): + numbers = rsa_key.public_key().public_numbers() + doc = { + "id": DID_WEB, + "verificationMethod": [ + { + "id": DID_WEB_KID, + "type": "JsonWebKey2020", + "controller": DID_WEB, + "publicKeyJwk": {"kty": "RSA", "n": _b64url_uint(numbers.n), "e": _b64url_uint(numbers.e)}, + } + ], + "authentication": [DID_WEB_KID], + } + response = MagicMock() + response.json.return_value = doc + response.raise_for_status = MagicMock() + + with patch(f"{RS256_MODULE}.requests.get", return_value=response): + code, output = _run( + [ + "--algorithm", "RS256", + "--private-key", rsa_pem_text, + "--challenge-file", str(_write_challenge(tmp_path, DID_WEB_KID)), + ] + ) + + assert code == 0, output + token = output.strip().splitlines()[-1] + assert _decode_segment(token, 0)["kid"] == DID_WEB_KID + + def test_ed25519_seed_gets_hint(self, ed25519_keys, rsa_kid, tmp_path): + priv, _ = ed25519_keys + code, output = _run( + [ + "--algorithm", "RS256", + "--private-key", priv, + "--challenge-file", str(_write_challenge(tmp_path, rsa_kid)), + ] + ) + + assert code != 0 + assert "--algorithm Ed25519" in output + + def test_missing_pem_file(self, rsa_kid, tmp_path): + code, output = _run( + [ + "--algorithm", "RS256", + "--private-key", str(tmp_path / "missing.pem"), + "--challenge-file", str(_write_challenge(tmp_path, rsa_kid)), + ] + ) + + assert code != 0 + assert "RSA private key file not found" in output + + def test_rsa_key_with_ed25519_did(self, rsa_pem_file, ed25519_keys, tmp_path): + _, kid = ed25519_keys + code, output = _run( + [ + "--algorithm", "RS256", + "--private-key", str(rsa_pem_file), + "--challenge-file", str(_write_challenge(tmp_path, kid)), + ] + ) + + assert code != 0 + assert "not an RSA public key" in output + + def test_missing_required_field(self, rsa_pem_file, rsa_kid, tmp_path): + path = tmp_path / "challenge.json" + path.write_text(json.dumps({"did": rsa_kid, "challenge": CHALLENGE_UUID, "aud": "ce-api", "iat": 1}), encoding="utf-8") + + code, output = _run(["--algorithm", "RS256", "--private-key", str(rsa_pem_file), "--challenge-file", str(path)]) + + assert code != 0 + assert "exp" in output From 550c9548a75dc42671d7dd589357c2bf2bb2bf04 Mon Sep 17 00:00:00 2001 From: Sneha Edula Date: Thu, 19 Nov 2026 19:58:13 -0500 Subject: [PATCH 4/6] clean up --- ce/commands/iir_sign_challenge.py | 8 ++---- ce/commands/iir_sign_challenge_rs256.py | 23 +++++++++-------- tests/test_iir_sign_challenge_rs256.py | 33 ++++++++++++++++++++++--- 3 files changed, 44 insertions(+), 20 deletions(-) diff --git a/ce/commands/iir_sign_challenge.py b/ce/commands/iir_sign_challenge.py index 707f056..e7901f3 100644 --- a/ce/commands/iir_sign_challenge.py +++ b/ce/commands/iir_sign_challenge.py @@ -13,7 +13,6 @@ from __future__ import annotations import json -from pathlib import Path from typing import Any, Dict, Tuple import base58 @@ -249,10 +248,7 @@ def _looks_like_rsa_key(value: str) -> bool: """True when an Ed25519 --private-key value looks like a PEM key or a key file path.""" if "-----BEGIN" in value or "\\n" in value: return True - try: - return Path(value).expanduser().is_file() - except OSError: - return False + return _rs256.is_existing_file(value) @click.command("sign") @@ -365,4 +361,4 @@ def sign_individual_challenge( f.write(token) err_console.print(f"Wrote Proof JWT to: [cyan]{out_path}[/cyan]") else: - click.echo(token) + click.echo(token) \ No newline at end of file diff --git a/ce/commands/iir_sign_challenge_rs256.py b/ce/commands/iir_sign_challenge_rs256.py index 20ae9aa..81972ef 100644 --- a/ce/commands/iir_sign_challenge_rs256.py +++ b/ce/commands/iir_sign_challenge_rs256.py @@ -15,7 +15,6 @@ import base64 import binascii -import json from pathlib import Path from typing import Any, Dict, Tuple from urllib.parse import quote, unquote @@ -85,7 +84,7 @@ def _load_private_key_bytes(data: bytes) -> RSAPrivateKey: if not isinstance(key, RSAPrivateKey): raise ValueError( f"Expected an RSA private key, got {type(key).__name__}. " - "Use `ce iir challenge sign` for Ed25519 keys." + "Use --algorithm Ed25519 for Ed25519 keys." ) return key @@ -110,7 +109,7 @@ def _load_private_key_from_text(text: str) -> RSAPrivateKey: def _load_signing_key(private_key_file: str | None, private_key_pem: str | None) -> RSAPrivateKey: if bool(private_key_file) == bool(private_key_pem): raise click.ClickException( - "Give exactly one of --private-key-file or --private-key-pem." + "Give the RSA private key as either a file path or the key text, not both." ) try: @@ -378,12 +377,8 @@ def load_private_key_argument(value: str) -> RSAPrivateKey: is_text = "-----BEGIN" in value or "\\n" in value if not is_text: - try: - path = Path(value).expanduser() - if path.is_file(): - return _load_signing_key(str(path), None) - except OSError: - pass + if is_existing_file(value): + return _load_signing_key(str(Path(value).expanduser()), None) if value.startswith("z") and len(value) < 120: raise click.ClickException( @@ -396,6 +391,14 @@ def load_private_key_argument(value: str) -> RSAPrivateKey: return _load_signing_key(None, value) +def is_existing_file(value: str) -> bool: + """True when value is the path of an existing file.""" + try: + return Path(value).expanduser().is_file() + except OSError: + return False + + def _looks_like_base64(value: str) -> bool: body = "".join(value.split()) if len(body) < 100: @@ -423,4 +426,4 @@ def sign_and_verify(private_key_value: str, kid: str, payload_obj: Dict[str, Any except ValueError as e: raise click.ClickException(f"DID resolution error: {e}") - return token + return token \ No newline at end of file diff --git a/tests/test_iir_sign_challenge_rs256.py b/tests/test_iir_sign_challenge_rs256.py index 09bee39..ae8e9c7 100644 --- a/tests/test_iir_sign_challenge_rs256.py +++ b/tests/test_iir_sign_challenge_rs256.py @@ -33,6 +33,7 @@ _resolve_public_key_for_kid, _sign_payload, _verify_signature_only, + is_existing_file, load_private_key_argument, sign_and_verify, ) @@ -201,7 +202,7 @@ def test_ed25519_key_rejected_with_hint(self): from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey pem = _pem(Ed25519PrivateKey.generate(), serialization.PrivateFormat.PKCS8) - with pytest.raises(ValueError, match="ce iir challenge sign"): + with pytest.raises(ValueError, match="--algorithm Ed25519"): _load_private_key_bytes(pem) def test_encrypted_pem_rejected(self, rsa_key): @@ -260,7 +261,7 @@ def test_small_key_rejected(self, tmp_path): _load_signing_key(str(path), None) def test_no_option_rejected(self): - with pytest.raises(click.ClickException, match="exactly one"): + with pytest.raises(click.ClickException, match="not both"): _load_signing_key(None, None) def test_both_options_rejected(self, rsa_key, tmp_path): @@ -268,7 +269,7 @@ def test_both_options_rejected(self, rsa_key, tmp_path): pem = _pem(rsa_key, serialization.PrivateFormat.PKCS8) path = tmp_path / "rsa.pem" path.write_bytes(pem) - with pytest.raises(click.ClickException, match="exactly one"): + with pytest.raises(click.ClickException, match="not both"): _load_signing_key(str(path), pem.decode()) @@ -515,6 +516,30 @@ def test_malformed_token_rejected(self, rsa_kid): +class TestIsExistingFile: + def test_existing_file(self, tmp_path): + path = tmp_path / "key.pem" + path.write_text("x", encoding="ascii") + assert is_existing_file(str(path)) + + def test_missing_file(self, tmp_path): + assert not is_existing_file(str(tmp_path / "missing.pem")) + + def test_folder_is_not_a_file(self, tmp_path): + assert not is_existing_file(str(tmp_path)) + + def test_value_the_os_rejects_as_a_path(self, rsa_key): + # Pasted key text is far longer than a file name may be, so the OS raises + # instead of answering; that must come back as "not a file". + from cryptography.hazmat.primitives import serialization + body = "".join( + line + for line in _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode().splitlines() + if "-----" not in line + ) + assert not is_existing_file(body) + + class TestLoadPrivateKeyArgument: def test_file_path(self, rsa_key, tmp_path): from cryptography.hazmat.primitives import serialization @@ -609,4 +634,4 @@ def test_did_web_fetch_error(self, rsa_key, challenge_payload): mock_resp.raise_for_status.side_effect = requests.HTTPError("404 Not Found") with patch(f"{MODULE}.requests.get", return_value=mock_resp): with pytest.raises(click.ClickException, match="Failed to fetch did.json"): - sign_and_verify(text, DID_WEB_KID, dict(challenge_payload, did=DID_WEB_KID)) + sign_and_verify(text, DID_WEB_KID, dict(challenge_payload, did=DID_WEB_KID)) \ No newline at end of file From f57e5466b8bf0afbd65f87912920b75f25db97d0 Mon Sep 17 00:00:00 2001 From: Sneha Edula Date: Fri, 20 Nov 2026 13:38:19 -0500 Subject: [PATCH 5/6] Command structure change --- ce/commands/iir.py | 4 +- ce/iir/challenge/__init__.py | 0 ce/iir/challenge/sign.py | 159 ++++++++++++++++++ ce/implementations/__init__.py | 1 + .../iir_challenge_sign_ed25519.py} | 150 ++--------------- .../iir_challenge_sign_rs256.py} | 7 +- ...lgorithm.py => test_iir_challenge_sign.py} | 14 +- ....py => test_iir_challenge_sign_ed25519.py} | 92 +++++++++- ...56.py => test_iir_challenge_sign_rs256.py} | 8 +- 9 files changed, 285 insertions(+), 150 deletions(-) create mode 100644 ce/iir/challenge/__init__.py create mode 100644 ce/iir/challenge/sign.py create mode 100644 ce/implementations/__init__.py rename ce/{commands/iir_sign_challenge.py => implementations/iir_challenge_sign_ed25519.py} (56%) rename ce/{commands/iir_sign_challenge_rs256.py => implementations/iir_challenge_sign_rs256.py} (97%) rename tests/{test_sign_command_algorithm.py => test_iir_challenge_sign.py} (96%) rename tests/{test_sign_single_challenge.py => test_iir_challenge_sign_ed25519.py} (83%) rename tests/{test_iir_sign_challenge_rs256.py => test_iir_challenge_sign_rs256.py} (99%) diff --git a/ce/commands/iir.py b/ce/commands/iir.py index 1790424..02e5813 100644 --- a/ce/commands/iir.py +++ b/ce/commands/iir.py @@ -13,7 +13,7 @@ import click from rich.console import Console -from ce.commands.iir_sign_challenge import sign_individual_challenge +from ce.iir.challenge.sign import main as sign_command from ce.auth.token_manager import require_login from ce.config.context import require_environment @@ -46,7 +46,7 @@ def issuer_did_group() -> None: # ce iir challenge sign (single) -challenge_group.add_command(sign_individual_challenge, name="sign") +challenge_group.add_command(sign_command, name="sign") # ce iir challenge bulk-sign diff --git a/ce/iir/challenge/__init__.py b/ce/iir/challenge/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ce/iir/challenge/sign.py b/ce/iir/challenge/sign.py new file mode 100644 index 0000000..76b0385 --- /dev/null +++ b/ce/iir/challenge/sign.py @@ -0,0 +1,159 @@ +"""ce iir challenge sign + + ce iir challenge sign --algorithm Ed25519 --private-key zABC... \ + --challenge-file challenge.json --output signed-challenge.jwt + + ce iir challenge sign --algorithm RS256 --private-key rsa-key.pem \ + --challenge-file challenge.json --output signed-challenge.jwt + +Signs one CE challenge and produces a Proof JWT, then verifies it against the +public key resolved from the DID (did:key or did:web). No login required. +--algorithm picks the implementation: + + Ed25519 alg=EdDSA, --private-key is a multibase seed (z...). + ce.implementations.iir_challenge_sign_ed25519 + RS256 alg=RS256, --private-key is a PEM file path or the PEM text. + ce.implementations.iir_challenge_sign_rs256 +""" + +from __future__ import annotations + +import json +from typing import Any, Dict + +import click +from rich.console import Console + +from ce.implementations import iir_challenge_sign_ed25519 as _ed25519 +from ce.implementations import iir_challenge_sign_rs256 as _rs256 + +err_console = Console(stderr=True) + +ALGORITHM_ED25519 = "Ed25519" +ALGORITHM_RS256 = "RS256" + +REQUIRED_FIELDS = ["did", "challenge", "aud", "iat", "exp"] + + + +# Input checks + +def read_challenge(challenge_file: str) -> Dict[str, Any]: + """Load the challenge JSON and check it has the fields a Proof JWT needs.""" + try: + with open(challenge_file, "r", encoding="utf-8") as f: + payload_obj = json.load(f) + except json.JSONDecodeError as e: + raise click.ClickException(f"Challenge file is not valid JSON: {e}") + + if not isinstance(payload_obj, dict): + raise click.ClickException("Challenge payload must be a JSON object.") + + missing = [k for k in REQUIRED_FIELDS if k not in payload_obj] + if missing: + raise click.ClickException( + f"Challenge JSON missing required field(s): {', '.join(missing)}" + ) + + did_value = payload_obj.get("did") + if not isinstance(did_value, str) or not did_value.strip(): + raise click.ClickException( + 'Challenge JSON must include a non-empty string field "did".' + ) + + return payload_obj + + +def looks_like_rsa_key(value: str) -> bool: + """True when an Ed25519 --private-key value looks like a PEM key or a key file path.""" + if "-----BEGIN" in value or "\\n" in value: + return True + return _rs256.is_existing_file(value) + + + +# Click command + +@click.command(name="sign") +@click.option( + "--algorithm", + "algorithm", + required=True, + type=click.Choice([ALGORITHM_ED25519, ALGORITHM_RS256]), + help="Signing algorithm: Ed25519 (alg=EdDSA) or RS256 (RSA).", +) +@click.option( + "--private-key", + "private_key", + required=True, + metavar="KEY", + help=( + "Ed25519: private seed (multibase base58btc, starts with 'z'). " + "RS256: path to an unencrypted PEM/DER key file, or the PEM text." + ), +) +@click.option( + "--challenge-file", + "challenge_file", + required=True, + type=click.Path(exists=True, dir_okay=False, readable=True), + metavar="PATH", + help="Path to CE-generated challenge JSON file.", +) +@click.option( + "--output", "-o", + "out_path", + default=None, + type=click.Path(dir_okay=False, writable=True), + metavar="PATH", + help="Write JWT to this file (otherwise printed to stdout).", +) +def main( + algorithm: str, + private_key: str, + challenge_file: str, + out_path: str | None, +) -> None: + """Sign a single CE challenge JSON file and produce a Proof JWT. + + \b + --algorithm Ed25519 : --private-key is the multibase seed (z...). + --algorithm RS256 : --private-key is a PEM file path or the PEM text. + The challenge JSON must include: did, challenge, aud, iat, exp. + Signature verification uses did:key (offline) or did:web (HTTPS). + + \b + Examples: + ce iir challenge sign --algorithm Ed25519 \\ + --private-key zABC... \\ + --challenge-file challenge.json \\ + --output signed-challenge.jwt + + \b + ce iir challenge sign --algorithm RS256 \\ + --private-key rsa-key.pem \\ + --challenge-file challenge.json \\ + --output signed-challenge.jwt + """ + payload_obj = read_challenge(challenge_file) + kid = payload_obj["did"].strip() + + if algorithm == ALGORITHM_RS256: + token = _rs256.sign_and_verify(private_key, kid, payload_obj) + else: + if looks_like_rsa_key(private_key): + raise click.ClickException( + "This looks like an RSA/PEM key. Use --algorithm RS256 for RSA keys." + ) + token = _ed25519.sign_and_verify(private_key, kid, payload_obj) + + if out_path: + with open(out_path, "w", encoding="utf-8") as f: + f.write(token) + err_console.print(f"Wrote Proof JWT to: [cyan]{out_path}[/cyan]") + else: + click.echo(token) + + +if __name__ == "__main__": + main() diff --git a/ce/implementations/__init__.py b/ce/implementations/__init__.py new file mode 100644 index 0000000..8da2855 --- /dev/null +++ b/ce/implementations/__init__.py @@ -0,0 +1 @@ +"""Reusable implementations behind the CLI commands (not CLI wrappers).""" diff --git a/ce/commands/iir_sign_challenge.py b/ce/implementations/iir_challenge_sign_ed25519.py similarity index 56% rename from ce/commands/iir_sign_challenge.py rename to ce/implementations/iir_challenge_sign_ed25519.py index e7901f3..7d60be8 100644 --- a/ce/commands/iir_sign_challenge.py +++ b/ce/implementations/iir_challenge_sign_ed25519.py @@ -1,18 +1,13 @@ -"""`ce iir challenge sign` - sign and verify a Proof JWT for a single CE challenge. +"""Ed25519 signing for `ce iir challenge sign --algorithm Ed25519`. -Reads a challenge JSON file produced by CE, signs it with a private key, and -verifies the resulting JWT against the public key resolved from the DID -(did:key or did:web). No login required. - ---algorithm picks the signing method: - - Ed25519 : alg=EdDSA, --private-key is a multibase seed (z...). Handled in this module. - - RS256 : alg=RS256, --private-key is a PEM file path or the PEM text. - Handled in ce.commands.iir_sign_challenge_rs256. +Signs a CE challenge with an Ed25519 private key (alg=EdDSA) and verifies the +resulting JWT against the public key resolved from the DID (did:key or did:web). +The RS256 path lives in ce.implementations.iir_challenge_sign_rs256. +The command is ce.iir.challenge.sign. """ from __future__ import annotations -import json from typing import Any, Dict, Tuple import base58 @@ -25,8 +20,6 @@ ) from rich.console import Console -from ce.commands import iir_sign_challenge_rs256 as _rs256 - console = Console() err_console = Console(stderr=True) @@ -238,127 +231,20 @@ def _assert_signature_verifiable(token: str, kid: str) -> None: -# Click command - -ALGORITHM_ED25519 = "Ed25519" -ALGORITHM_RS256 = "RS256" - - -def _looks_like_rsa_key(value: str) -> bool: - """True when an Ed25519 --private-key value looks like a PEM key or a key file path.""" - if "-----BEGIN" in value or "\\n" in value: - return True - return _rs256.is_existing_file(value) +# Entry point used by `ce iir challenge sign --algorithm Ed25519` - -@click.command("sign") -@click.option( - "--algorithm", - "algorithm", - required=True, - type=click.Choice([ALGORITHM_ED25519, ALGORITHM_RS256]), - help="Signing algorithm: Ed25519 (alg=EdDSA) or RS256 (RSA).", -) -@click.option( - "--private-key", - "private_key", - required=True, - metavar="KEY", - help=( - "Ed25519: private seed (multibase base58btc, starts with 'z'). " - "RS256: path to an unencrypted PEM/DER key file, or the PEM text." - ), -) -@click.option( - "--challenge-file", - "challenge_file", - required=True, - type=click.Path(exists=True, dir_okay=False, readable=True), - metavar="PATH", - help="Path to CE-generated challenge JSON file.", -) -@click.option( - "--output", "-o", - "out_path", - default=None, - type=click.Path(dir_okay=False, writable=True), - metavar="PATH", - help="Write JWT to this file (otherwise printed to stdout).", -) -def sign_individual_challenge( - algorithm: str, - private_key: str, - challenge_file: str, - out_path: str | None, -) -> None: - """Sign a single CE challenge JSON file and produce a Proof JWT. - - \b - --algorithm Ed25519 : --private-key is the multibase seed (z...). - --algorithm RS256 : --private-key is a PEM file path or the PEM text. - The challenge JSON must include: did, challenge, aud, iat, exp. - Signature verification uses did:key (offline) or did:web (HTTPS). - - \b - Examples: - ce iir challenge sign --algorithm Ed25519 \\ - --private-key zABC... \\ - --challenge-file challenge.json \\ - --output signed-challenge.jwt - - \b - ce iir challenge sign --algorithm RS256 \\ - --private-key rsa-key.pem \\ - --challenge-file challenge.json \\ - --output signed-challenge.jwt - """ +def sign_and_verify(private_key_value: str, kid: str, payload_obj: Dict[str, Any]) -> str: + """Sign the challenge with the Ed25519 seed (EdDSA) and verify it against the DID.""" try: - with open(challenge_file, "r", encoding="utf-8") as f: - payload_obj = json.load(f) - except json.JSONDecodeError as e: - raise click.ClickException(f"Challenge file is not valid JSON: {e}") - - if not isinstance(payload_obj, dict): - raise click.ClickException("Challenge payload must be a JSON object.") - - required_fields = ["did", "challenge", "aud", "iat", "exp"] - missing = [k for k in required_fields if k not in payload_obj] - if missing: - raise click.ClickException( - f"Challenge JSON missing required field(s): {', '.join(missing)}" - ) + token = _sign_payload(private_key_value, kid, payload_obj) + except ValueError as e: + raise click.ClickException(f"Signing failed: {e}") - did_value = payload_obj.get("did") - if not isinstance(did_value, str) or not did_value.strip(): - raise click.ClickException( - 'Challenge JSON must include a non-empty string field "did".' - ) + try: + _assert_signature_verifiable(token, kid) + except requests.RequestException as e: + raise click.ClickException(f"Failed to fetch did.json: {e}") + except ValueError as e: + raise click.ClickException(f"DID resolution error: {e}") - kid = did_value.strip() - - if algorithm == ALGORITHM_RS256: - token = _rs256.sign_and_verify(private_key, kid, payload_obj) - else: - if _looks_like_rsa_key(private_key): - raise click.ClickException( - "This looks like an RSA/PEM key. Use --algorithm RS256 for RSA keys." - ) - - try: - token = _sign_payload(private_key, kid, payload_obj) - except ValueError as e: - raise click.ClickException(f"Signing failed: {e}") - - try: - _assert_signature_verifiable(token, kid) - except requests.RequestException as e: - raise click.ClickException(f"Failed to fetch did.json: {e}") - except ValueError as e: - raise click.ClickException(f"DID resolution error: {e}") - - if out_path: - with open(out_path, "w", encoding="utf-8") as f: - f.write(token) - err_console.print(f"Wrote Proof JWT to: [cyan]{out_path}[/cyan]") - else: - click.echo(token) \ No newline at end of file + return token diff --git a/ce/commands/iir_sign_challenge_rs256.py b/ce/implementations/iir_challenge_sign_rs256.py similarity index 97% rename from ce/commands/iir_sign_challenge_rs256.py rename to ce/implementations/iir_challenge_sign_rs256.py index 81972ef..a2add70 100644 --- a/ce/commands/iir_sign_challenge_rs256.py +++ b/ce/implementations/iir_challenge_sign_rs256.py @@ -2,7 +2,8 @@ Signs a CE challenge with an RSA private key (alg=RS256) and verifies the resulting JWT against the public key resolved from the DID (did:key or did:web). -The Ed25519 path lives in ce.commands.iir_sign_challenge. +The Ed25519 path lives in ce.implementations.iir_challenge_sign_ed25519. +The command is ce.iir.challenge.sign. Key resolution: - did:key : multicodec 0x1205 (rsa-pub), PKCS#1 RSAPublicKey DER, base58btc. @@ -396,6 +397,8 @@ def is_existing_file(value: str) -> bool: try: return Path(value).expanduser().is_file() except OSError: + # The OS can refuse a value as a path (for example pasted key text that is + # too long or has characters a path can't have). Such a value is not a file. return False @@ -426,4 +429,4 @@ def sign_and_verify(private_key_value: str, kid: str, payload_obj: Dict[str, Any except ValueError as e: raise click.ClickException(f"DID resolution error: {e}") - return token \ No newline at end of file + return token diff --git a/tests/test_sign_command_algorithm.py b/tests/test_iir_challenge_sign.py similarity index 96% rename from tests/test_sign_command_algorithm.py rename to tests/test_iir_challenge_sign.py index 370fe33..989e872 100644 --- a/tests/test_sign_command_algorithm.py +++ b/tests/test_iir_challenge_sign.py @@ -19,10 +19,10 @@ pytestmark = pytest.mark.unit -from ce.commands.iir_sign_challenge import sign_individual_challenge +from ce.iir.challenge.sign import main as sign_command -RS256_MODULE = "ce.commands.iir_sign_challenge_rs256" +RS256_MODULE = "ce.implementations.iir_challenge_sign_rs256" CHALLENGE_UUID = "11111111-2222-3333-4444-555555555555" CTID = "ce-12345678-1234-1234-1234-123456789abc" @@ -34,7 +34,7 @@ # Helpers def _run(args): - result = CliRunner().invoke(sign_individual_challenge, args) + result = CliRunner().invoke(sign_command, args) return result.exit_code, result.output @@ -284,3 +284,11 @@ def test_missing_required_field(self, rsa_pem_file, rsa_kid, tmp_path): assert code != 0 assert "exp" in output + + + +class TestRegistration: + def test_registered_as_iir_challenge_sign(self): + from ce.commands.iir import challenge_group + + assert challenge_group.commands["sign"] is sign_command diff --git a/tests/test_sign_single_challenge.py b/tests/test_iir_challenge_sign_ed25519.py similarity index 83% rename from tests/test_sign_single_challenge.py rename to tests/test_iir_challenge_sign_ed25519.py index e64633b..1ce92c4 100644 --- a/tests/test_sign_single_challenge.py +++ b/tests/test_iir_challenge_sign_ed25519.py @@ -1,5 +1,5 @@ """ -Unit tests for ce.commands.iir_sign_challenge. +Unit tests for ce.implementations.iir_challenge_sign_ed25519. Run with: pytest -m unit -s """ @@ -20,7 +20,7 @@ pytestmark = pytest.mark.unit -from ce.commands.iir_sign_challenge import ( +from ce.implementations.iir_challenge_sign_ed25519 import ( _assert_signature_verifiable, _decode_multibase_base58btc, _did_web_to_url, @@ -32,6 +32,7 @@ _resolve_public_key_bytes_for_kid, _sign_payload, _verify_signature_only, + sign_and_verify, ) @@ -235,7 +236,7 @@ def test_returns_parsed_json_on_200(self): mock_resp.raise_for_status = MagicMock() with patch( - "ce.commands.iir_sign_challenge.requests.get", + "ce.implementations.iir_challenge_sign_ed25519.requests.get", return_value=mock_resp, ) as mock_get: result = _fetch_did_json("did:web:example.com") @@ -250,7 +251,7 @@ def test_http_error_propagates(self): mock_resp.raise_for_status.side_effect = requests.HTTPError("404 Not Found") with patch( - "ce.commands.iir_sign_challenge.requests.get", + "ce.implementations.iir_challenge_sign_ed25519.requests.get", return_value=mock_resp, ): with pytest.raises(requests.HTTPError): @@ -262,7 +263,7 @@ def test_non_object_response_raises(self): mock_resp.raise_for_status = MagicMock() with patch( - "ce.commands.iir_sign_challenge.requests.get", + "ce.implementations.iir_challenge_sign_ed25519.requests.get", return_value=mock_resp, ): with pytest.raises(ValueError, match="must be a JSON object"): @@ -274,7 +275,7 @@ def test_passes_through_path_segments_in_url(self): mock_resp.raise_for_status = MagicMock() with patch( - "ce.commands.iir_sign_challenge.requests.get", + "ce.implementations.iir_challenge_sign_ed25519.requests.get", return_value=mock_resp, ) as mock_get: _fetch_did_json("did:web:example.com:users:alice") @@ -436,7 +437,7 @@ def test_did_web_path_fetches_doc(self): mock_resp.json.return_value = doc mock_resp.raise_for_status = MagicMock() with patch( - "ce.commands.iir_sign_challenge.requests.get", + "ce.implementations.iir_challenge_sign_ed25519.requests.get", return_value=mock_resp, ): result = _resolve_public_key_bytes_for_kid(kid) @@ -550,3 +551,80 @@ def test_malformed_token_raises_click_exception(self, ed25519_keypair): with pytest.raises(click.ClickException, match="JWT verification error"): _assert_signature_verifiable("not.a.real.jwt", kid) + +class TestSignAndVerify: + def test_did_key(self, ed25519_keypair, valid_challenge_payload): + priv, _, kid = ed25519_keypair + payload = dict(valid_challenge_payload, did=kid) + + token = sign_and_verify(priv, kid, payload) + + header_b64 = token.split(".")[0] + header = json.loads(base64.urlsafe_b64decode(header_b64 + "=" * (-len(header_b64) % 4))) + assert header == {"typ": "JWT", "alg": "EdDSA", "kid": kid} + + def test_did_web(self, valid_challenge_payload): + import base58 + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + + sk = Ed25519PrivateKey.generate() + seed = sk.private_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PrivateFormat.Raw, + encryption_algorithm=serialization.NoEncryption(), + ) + pub = sk.public_key().public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + did = "did:web:example.com" + kid = f"{did}#key-1" + doc = { + "id": did, + "verificationMethod": [ + { + "id": kid, + "type": "Multikey", + "publicKeyMultibase": "z" + base58.b58encode(bytes([0xED, 0x01]) + pub).decode(), + } + ], + } + mock_resp = MagicMock() + mock_resp.json.return_value = doc + mock_resp.raise_for_status = MagicMock() + + with patch( + "ce.implementations.iir_challenge_sign_ed25519.requests.get", + return_value=mock_resp, + ): + token = sign_and_verify("z" + base58.b58encode(seed).decode(), kid, dict(valid_challenge_payload, did=kid)) + + assert token.count(".") == 2 + + def test_bad_private_key(self, valid_challenge_payload): + with pytest.raises(click.ClickException, match="Signing failed"): + sign_and_verify("zNOT-A-REAL-KEY", ED25519_KID, valid_challenge_payload) + + def test_wrong_key_for_did(self, ed25519_keypair, valid_challenge_payload): + priv, _, _ = ed25519_keypair + # Signed with the session key, but the kid names a different (fixed) DID. + with pytest.raises(click.ClickException, match="Signature verification failed"): + sign_and_verify(priv, ED25519_KID, valid_challenge_payload) + + def test_did_web_fetch_error(self, ed25519_keypair, valid_challenge_payload): + priv, _, _ = ed25519_keypair + mock_resp = MagicMock() + mock_resp.raise_for_status.side_effect = requests.HTTPError("404 Not Found") + + with patch( + "ce.implementations.iir_challenge_sign_ed25519.requests.get", + return_value=mock_resp, + ): + with pytest.raises(click.ClickException, match="Failed to fetch did.json"): + sign_and_verify(priv, "did:web:example.com#key-1", valid_challenge_payload) + + def test_unsupported_did_method(self, ed25519_keypair, valid_challenge_payload): + priv, _, _ = ed25519_keypair + with pytest.raises(click.ClickException, match="DID resolution error"): + sign_and_verify(priv, "did:ethr:0x123#key-1", valid_challenge_payload) diff --git a/tests/test_iir_sign_challenge_rs256.py b/tests/test_iir_challenge_sign_rs256.py similarity index 99% rename from tests/test_iir_sign_challenge_rs256.py rename to tests/test_iir_challenge_sign_rs256.py index ae8e9c7..5e88f7f 100644 --- a/tests/test_iir_sign_challenge_rs256.py +++ b/tests/test_iir_challenge_sign_rs256.py @@ -1,5 +1,5 @@ """ -Unit tests for ce.commands.iir_sign_challenge_rs256 (the RS256 path of `ce iir challenge sign`). +Unit tests for ce.implementations.iir_challenge_sign_rs256 (the RS256 path of `ce iir challenge sign`). Run with: pytest -m unit -s """ @@ -20,7 +20,7 @@ pytestmark = pytest.mark.unit -from ce.commands.iir_sign_challenge_rs256 import ( +from ce.implementations.iir_challenge_sign_rs256 import ( _assert_signature_verifiable, _did_web_to_url, _fetch_did_json, @@ -39,7 +39,7 @@ ) -MODULE = "ce.commands.iir_sign_challenge_rs256" +MODULE = "ce.implementations.iir_challenge_sign_rs256" CHALLENGE_UUID = "11111111-2222-3333-4444-555555555555" CTID = "ce-12345678-1234-1234-1234-123456789abc" @@ -634,4 +634,4 @@ def test_did_web_fetch_error(self, rsa_key, challenge_payload): mock_resp.raise_for_status.side_effect = requests.HTTPError("404 Not Found") with patch(f"{MODULE}.requests.get", return_value=mock_resp): with pytest.raises(click.ClickException, match="Failed to fetch did.json"): - sign_and_verify(text, DID_WEB_KID, dict(challenge_payload, did=DID_WEB_KID)) \ No newline at end of file + sign_and_verify(text, DID_WEB_KID, dict(challenge_payload, did=DID_WEB_KID)) From 5d13b5b90b284913aca35cc6a60fb6e3cea8c090 Mon Sep 17 00:00:00 2001 From: Sneha Edula Date: Fri, 20 Nov 2026 13:38:41 -0500 Subject: [PATCH 6/6] add workspace file --- ce.code-workspace | 61 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 ce.code-workspace diff --git a/ce.code-workspace b/ce.code-workspace new file mode 100644 index 0000000..181b90e --- /dev/null +++ b/ce.code-workspace @@ -0,0 +1,61 @@ +{ + "extensions": { + "recommendations": [ + "ms-python.python", + "ms-python.vscode-pylance", + "charliermarsh.ruff" + ] + }, + "folders": [ + { + "path": "." + } + ], + "settings": { + "[json]": { + "editor.codeActionsOnSave": { + "source.fixAll.sortJSON": "explicit" + }, + "editor.defaultFormatter": "vscode.json-language-features", + "editor.detectIndentation": false, + "editor.formatOnSave": true, + "editor.insertSpaces": true, + "editor.tabSize": 4 + }, + "[jsonc]": { + "editor.codeActionsOnSave": { + "source.sort.json": "explicit" + }, + "editor.defaultFormatter": "vscode.json-language-features", + "editor.detectIndentation": false, + "editor.formatOnSave": true, + "editor.insertSpaces": true, + "editor.tabSize": 4 + }, + "[python]": { + "editor.codeActionsOnSave": { + "source.fixAll.ruff": "explicit", + "source.organizeImports.ruff": "explicit" + }, + "editor.defaultFormatter": "charliermarsh.ruff", + "editor.formatOnSave": true, + "editor.insertSpaces": true, + "editor.tabSize": 4 + }, + "editor.detectIndentation": false, + "editor.insertSpaces": true, + "editor.rulers": [ + 80 + ], + "editor.tabSize": 4, + "files.insertFinalNewline": true, + "files.trimTrailingWhitespace": true, + "python.analysis.typeCheckingMode": "basic", + "python.terminal.activateEnvironment": true, + "python.testing.pytestEnabled": true, + "python.testing.unittestEnabled": false, + "ruff.enable": true, + "ruff.fixAll": true, + "ruff.organizeImports": true + } +}