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 + } +} diff --git a/ce/commands/iir.py b/ce/commands/iir.py index 60428a6..02e5813 100644 --- a/ce/commands/iir.py +++ b/ce/commands/iir.py @@ -1,6 +1,6 @@ """IIR command group: - ce iir challenge sign # single challenge + 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 """ @@ -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 70% rename from ce/commands/iir_sign_challenge.py rename to ce/implementations/iir_challenge_sign_ed25519.py index 3b79521..7d60be8 100644 --- a/ce/commands/iir_sign_challenge.py +++ b/ce/implementations/iir_challenge_sign_ed25519.py @@ -1,13 +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 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. +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 @@ -231,76 +231,12 @@ def _assert_signature_verifiable(token: str, kid: str) -> None: -# Click command - -@click.command("sign") -@click.option( - "--private-key", - "private_key", - required=True, - metavar="MULTIBASE", - help="Ed25519 private seed (multibase base58btc, starts with 'z').", -) -@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( - 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). - - \b - 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 - """ - 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() +# Entry point used by `ce iir challenge sign --algorithm Ed25519` +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: - token = _sign_payload(private_key, kid, payload_obj) + token = _sign_payload(private_key_value, kid, payload_obj) except ValueError as e: raise click.ClickException(f"Signing failed: {e}") @@ -311,9 +247,4 @@ def sign_individual_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) \ No newline at end of file + return token diff --git a/ce/implementations/iir_challenge_sign_rs256.py b/ce/implementations/iir_challenge_sign_rs256.py new file mode 100644 index 0000000..a2add70 --- /dev/null +++ b/ce/implementations/iir_challenge_sign_rs256.py @@ -0,0 +1,432 @@ +"""RS256 signing for `ce iir challenge sign --algorithm RS256`. + +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.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. + 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 +from pathlib import Path +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" + +# 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 + 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 --algorithm Ed25519 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 the RSA private key as either a file path or the key text, not both." + ) + + 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)" + ) + + + +# Entry point used by `ce iir challenge sign --algorithm RS256` + +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.") + + is_text = "-----BEGIN" in value or "\\n" in value + if not is_text: + 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( + "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) + + +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: + # 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 + + +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) + 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}") + + return token diff --git a/tests/test_iir_challenge_sign.py b/tests/test_iir_challenge_sign.py new file mode 100644 index 0000000..989e872 --- /dev/null +++ b/tests/test_iir_challenge_sign.py @@ -0,0 +1,294 @@ +""" +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.iir.challenge.sign import main as sign_command + + +RS256_MODULE = "ce.implementations.iir_challenge_sign_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_command, 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 + + + +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_challenge_sign_rs256.py b/tests/test_iir_challenge_sign_rs256.py new file mode 100644 index 0000000..5e88f7f --- /dev/null +++ b/tests/test_iir_challenge_sign_rs256.py @@ -0,0 +1,637 @@ +""" +Unit tests for ce.implementations.iir_challenge_sign_rs256 (the RS256 path of `ce iir challenge sign`). +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 + + + +pytestmark = pytest.mark.unit + + +from ce.implementations.iir_challenge_sign_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, + is_existing_file, + load_private_key_argument, + sign_and_verify, +) + + +MODULE = "ce.implementations.iir_challenge_sign_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="--algorithm Ed25519"): + _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="not both"): + _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="not both"): + _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 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 + path = tmp_path / "rsa.pem" + path.write_bytes(_pem(rsa_key, serialization.PrivateFormat.PKCS8)) + assert load_private_key_argument(str(path)).key_size == 2048 + + 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_pem_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_argument(text).key_size == 2048 + + 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_pem_rejected(self, tmp_path): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + 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)) + + 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)) + + def test_empty_rejected(self): + with pytest.raises(click.ClickException, match="empty"): + load_private_key_argument(" ") + + +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 _decode_segment(token, 0) == {"typ": "JWT", "alg": "RS256", "kid": rsa_kid} + assert _decode_segment(token, 1) == challenge_payload + + def test_did_web(self, rsa_key, challenge_payload): + from cryptography.hazmat.primitives import serialization + text = _pem(rsa_key, serialization.PrivateFormat.PKCS8).decode() + + 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 _decode_segment(token, 0)["kid"] == DID_WEB_KID + + 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) + + 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)) + + 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))