From 436d30d096466362cb5be937b475f55256e59634 Mon Sep 17 00:00:00 2001 From: Sneha Edula Date: Tue, 1 Dec 2026 20:48:05 -0500 Subject: [PATCH 1/2] Add RSA Support for Bulk Signing --- README.md | 101 +-- ce/commands/iir.py | 29 +- ce/iir/challenge/sign.py | 5 + ce/iir/csv_processor.py | 111 +++- ce/iir/did_ops.py | 63 +- ...FlowIntegration.test_sign_verify_save.yaml | 182 ++++++ ..._did_key_jwt_is_rejected_while_hidden.yaml | 90 +++ ...t_eddsa_token_for_rsa_key_is_rejected.yaml | 90 +++ ...FlowIntegration.test_sign_verify_save.yaml | 182 ++++++ ...ration.test_wrong_rsa_key_is_rejected.yaml | 90 +++ ...s256_did_key_is_rejected_while_hidden.yaml | 42 ++ ..._rsa_did_key_is_rejected_while_hidden.yaml | 42 ++ ..._ed25519_and_rsa_verification_methods.yaml | 42 ++ tests/test_did_ops_unit.py | 179 +++++- tests/test_iir_challenge_sign.py | 78 +++ tests/test_iir_csv_processor.py | 580 ++++++++++++++++-- tests/test_iir_signing_integration.py | 392 ++++++++++++ 17 files changed, 2149 insertions(+), 149 deletions(-) create mode 100644 tests/cassettes/TestEd25519DidWebFlowIntegration.test_sign_verify_save.yaml create mode 100644 tests/cassettes/TestRs256DidKeyFlowIntegration.test_rsa_did_key_jwt_is_rejected_while_hidden.yaml create mode 100644 tests/cassettes/TestRs256DidWebFlowIntegration.test_eddsa_token_for_rsa_key_is_rejected.yaml create mode 100644 tests/cassettes/TestRs256DidWebFlowIntegration.test_sign_verify_save.yaml create mode 100644 tests/cassettes/TestRs256DidWebFlowIntegration.test_wrong_rsa_key_is_rejected.yaml create mode 100644 tests/cassettes/TestValidateRsaDidKeyIntegration.test_rs256_did_key_is_rejected_while_hidden.yaml create mode 100644 tests/cassettes/TestValidateRsaDidKeyIntegration.test_rsa_did_key_is_rejected_while_hidden.yaml create mode 100644 tests/cassettes/TestValidateTwoKeyDidWebIntegration.test_lists_ed25519_and_rsa_verification_methods.yaml create mode 100644 tests/test_iir_signing_integration.py diff --git a/README.md b/README.md index 62d02b8..b8ded62 100644 --- a/README.md +++ b/README.md @@ -3,43 +3,43 @@ A command-line tool for managing Credential Engine platform resources. ## Requirements - + - Python 3.11 or later - `pip` ## Installation - + > **Recommended:** install inside a virtual environment. This avoids file-permission errors, PATH conflicts, and "invalid distribution" warnings from previous installs. - + ### Option 1: Install from source with a virtual environment (recommended) - + **macOS / Linux:** - + ```bash git clone https://github.com/CredentialEngine/ce-cli.git cd ce-cli - + python3 -m venv .venv source .venv/bin/activate - + pip install -e . ``` - + **Windows (PowerShell):** - + ```powershell git clone https://github.com/CredentialEngine/ce-cli.git cd ce-cli - + python -m venv .venv .venv\Scripts\activate - + pip install -e . ``` - + When the venv is active you'll see `(.venv)` in your prompt, and `ce` is automatically on `PATH`. To leave the venv, run `deactivate`. To re-enter it next time, run the activate command above from the project folder. - + ### Option 2: Install from a release - + 1. Download the `.whl` from the [Releases page](https://github.com/CredentialEngine/ce-cli/releases). 2. Install it (inside a venv is still recommended): ```bash @@ -47,43 +47,43 @@ When the venv is active you'll see `(.venv)` in your prompt, and `ce` is automat ``` ### Upgrading - + From a release `.whl`: - + ```bash pip install --upgrade ce_cli--py3-none-any.whl ``` - + From source: `git pull` and re-run `pip install -e .` inside your venv. - + ### Option 3: Install from source without a venv - + ```bash git clone https://github.com/CredentialEngine/ce-cli.git cd ce-cli pip install -e . ``` - + This puts the `ce` command on your `$PATH`. On Windows, see the [Windows PATH note](#windows-path-note) below if `ce` isn't found. - + ### Verify the installation - + ```bash ce --help ``` - + You should see the top-level command list. - + ### Windows PATH note - + When you install on Windows without a venv, pip often drops ce.exe into your user Scripts folder, which Windows doesn't put on PATH by default: - + ``` C:\Users\\AppData\Roaming\Python\Python310\Scripts ``` - + If `ce --help` fails after install, either use a venv (recommended) or add that folder to your User PATH: - + ```powershell [Environment]::SetEnvironmentVariable( "Path", @@ -91,9 +91,9 @@ If `ce --help` fails after install, either use a venv (recommended) or add that "User" ) ``` - + Then **close and reopen PowerShell** existing windows won't pick up the new PATH. - + ## Quick start @@ -153,21 +153,30 @@ IIR commands are grouped by the noun they operate on: #### Sign a single challenge (`ce iir challenge sign`) -Signs a CE-generated challenge JSON file with an Ed25519 private key (alg `EdDSA`) and verifies the resulting JWT against the public key resolved from the DID in the payload. No login required — offline for `did:key`, single HTTPS fetch for `did:web`. +Signs a CE-generated challenge JSON file and verifies the resulting JWT against the public key resolved from the DID in the payload. `--algorithm` picks the key type. No login required: offline for `did:key`, a single HTTPS fetch for `did:web`. -```bash -ce iir challenge sign \ - --private-key z3u2en... \ - --challenge-file challenge.json \ - --output signed-challenge.jwt +| `--algorithm` | JWT `alg` | Key in the DID | DIDs | +| ------------- | --------- | ---------------------------------------- | -------------------------- | +| `Ed25519` | `EdDSA` | `Multikey` (`publicKeyMultibase`, `z...`) | `did:key`, `did:web` | +| `RS256` | `RS256` | `JsonWebKey2020` (`publicKeyJwk`, `kty: RSA`) | `did:web` only for now | + +```powershell +ce iir challenge sign --algorithm Ed25519 --private-key z3u2en... --challenge-file challenge.json --output signed-challenge.jwt + +ce iir challenge sign --algorithm RS256 --private-key rsa-private-key.pem --challenge-file challenge.json --output signed-challenge.jwt ``` | Flag | Required | Description | | ------------------ | -------- | -------------------------------------------------------------------- | -| `--private-key` | Yes | Ed25519 private seed, multibase base58btc (starts with `z`) | +| `--algorithm` | Yes | `Ed25519` or `RS256` (exact spelling) | +| `--private-key` | Yes | Ed25519: private seed, multibase base58btc (starts with `z`). RS256: path to an unencrypted PEM key file (`BEGIN PRIVATE KEY` or `BEGIN RSA PRIVATE KEY`), the PEM text, or the bare base64 key | | `--challenge-file` | Yes | Path to the challenge JSON produced by CE | | `--output`, `-o` | No | Write the JWT to this file. If omitted, the JWT is printed to stdout | +RSA keys must be at least 2048 bits. For RS256 the DID document must list the key under `authentication`. RSA `did:key` +is not supported yet: use a `did:web` with a `JsonWebKey2020` key. Giving an RSA key with `--algorithm Ed25519`, or an +Ed25519 seed with `--algorithm RS256`, fails with a hint to use the other algorithm. + The challenge JSON must include `did`, `challenge`, `aud`, `iat`, and `exp`. The `did` field is used as the JWT header `kid` and to resolve the public key for verification (`did:key` resolves offline; `did:web` is fetched over HTTPS using the OS trust store). Example challenge file: @@ -199,7 +208,7 @@ Register DIDs for multiple organizations in one go. The process has two phases. ce iir challenge bulk-sign --csv input.csv --output output.csv ``` -Validates each row (membership, registry lookup, DID resolution), creates challenges, signs JWTs with the provided private keys, and writes the results to an output CSV. If `--output` is omitted, defaults to `Output--.csv`. Failed rows are written to `Errors--.csv` (override with `--errors`). +Validates each row (algorithm, membership, registry lookup, DID resolution), creates challenges, signs JWTs with the provided private keys using each row's `Algorithm`, verifies them against the DID, and writes the results to an output CSV. If `--output` is omitted, defaults to `Output--.csv`. Failed rows are written to `Errors--.csv` (override with `--errors`). **Phase 2 — Publish to the IIR registry (`ce iir issuer-did publish`):** @@ -207,7 +216,7 @@ Validates each row (membership, registry lookup, DID resolution), creates challe ce iir issuer-did publish --input output.csv ``` -Verifies the JWT signatures and publishes each issuer to the IIR. Pass `--yes`/`-y` to skip the confirmation prompt. Failed publishes are written to `PublishErrors--.csv` (override with `--publish-errors`). +Verifies the JWT signatures and publishes each issuer to the IIR. Ed25519 and RS256 rows are handled the same way: the API reads the algorithm from the JWT. Pass `--yes`/`-y` to skip the confirmation prompt. Failed publishes are written to `PublishErrors--.csv` (override with `--publish-errors`). #### Input CSV format @@ -216,8 +225,8 @@ Verifies the JWT signatures and publishes each issuer to the IIR. Pass `--yes`/` | `CTID` | Yes | The organization's CTID (must be published in the registry) | | `DID` | Yes | `did:key:...` or `did:web:...` | | `VerificationMethod` | Yes | Full verification method ID (e.g., `did:key:z6Mk...#z6Mk...`) | -| `Algorithm` | For did:key | `Ed25519`, `secp256k1`, `P-256`, or `X25519` | -| `PrivateKey` | Yes | Multibase-encoded private key for signing | +| `Algorithm` | Yes | `Ed25519` or `RS256`, on every row (did:web included) | +| `PrivateKey` | Yes | Ed25519: multibase seed (`z...`). RS256: PEM key file path, PEM text with literal `\n` line breaks, or bare base64 | | `ValidFrom` | No | Date when the issuer becomes valid (MM/DD/YYYY) | | `ValidUntil` | No | Date when the issuer expires (MM/DD/YYYY) | @@ -226,7 +235,8 @@ Example: ```csv CTID,DID,VerificationMethod,Algorithm,PrivateKey,ValidFrom,ValidUntil ce-12345678-...,did:key:z6MkhaX...,did:key:z6MkhaX...#z6MkhaX...,Ed25519,z3u2en...,01/01/2024,12/31/2025 -ce-87654321-...,did:web:example.com,did:web:example.com#key-1,,z3u2en...,, +ce-87654321-...,did:web:example.com,did:web:example.com#key-1,Ed25519,z3u2en...,, +ce-87654321-...,did:web:example.com,did:web:example.com#key-2,RS256,keys\rsa-private-key.pem,, ``` `ValidFrom` and `ValidUntil` are optional. @@ -307,15 +317,18 @@ ce-cli/ │ ├── env.py # ce env list / use / show │ ├── config.py # ce config set / get / list / reset │ ├── iir.py # ce iir challenge bulk-sign, ce iir issuer-did publish - │ ├── iir_sign_challenge.py # ce iir challenge sign │ └── resource.py # ce resource list / show / create / delete ├── config/ │ ├── settings.py # OIDCSettings, token I/O, paths │ └── context.py # Environment model, active-env helpers ├── iir/ + │ ├── challenge/ + │ │ └── sign.py # ce iir challenge sign (--algorithm Ed25519 | RS256) │ ├── csv_processor.py # Bulk DID upload (bulk-sign + publish) - │ └── did_ops.py # DID validation, challenges, JWT signing + │ └── did_ops.py # DID validation, challenges, IIR API calls ├── implementations/ + │ ├── iir_challenge_sign_ed25519.py # Ed25519 (EdDSA) signing and verification + │ ├── iir_challenge_sign_rs256.py # RS256 signing and verification │ └── publisher/ # Behind ce publisher: client.py, service.py, cli.py (shared options and errors) ├── publisher/ # ce publisher: a noun is a folder, a verb is a file that exposes `main` │ └── project/ diff --git a/ce/commands/iir.py b/ce/commands/iir.py index dd8ae8a..73f52e4 100644 --- a/ce/commands/iir.py +++ b/ce/commands/iir.py @@ -59,7 +59,10 @@ def issuer_did_group() -> None: "csv_path", required=True, type=click.Path(exists=True, dir_okay=False, readable=True), - help="Input CSV file (columns: CTID, DID, VerificationMethod, Algorithm, PrivateKey, ValidFrom, ValidUntil).", + help=( + "Input CSV file (columns: CTID, DID, VerificationMethod, Algorithm, " + "PrivateKey, ValidFrom, ValidUntil). Algorithm is Ed25519 or RS256." + ), ) @click.option( "--output", @@ -82,19 +85,27 @@ def bulk_sign(csv_path: str, output_path: str | None, errors_path: str | None) - Checks per row: 1. CTID format 2. Date format validation (ValidFrom, ValidUntil if provided) - 3. Membership check - Is user a member of the org - 4. Registry check - Is CTID published to the registry - 5. DID classification - 6. DID validation via API - 7. Verification method - 8. Create challenge - 9. Sign JWT - 10. Local JWT verification + 3. Algorithm - Ed25519 or RS256 + 4. Membership check - Is user a member of the org + 5. Registry check - Is CTID published to the registry + 6. DID classification (did:key key type must match Algorithm) + 7. DID validation via API + 8. Verification method + 9. Create challenge + 10. Sign JWT with the row's Algorithm and verify it against the DID \b Input CSV columns (required): CTID, DID, VerificationMethod, Algorithm, PrivateKey + \b + Algorithm and PrivateKey (required on every row, did:web included): + Ed25519 PrivateKey is the multibase seed (z...) + RS256 PrivateKey is a PEM key file path (relative paths are read + from the CSV's folder), PEM text with literal \\n line + breaks, or bare base64 + A did:web with two keys needs one row per key, each with its own Algorithm. + \b Input CSV columns (optional): ValidFrom, ValidUntil (format: MM/DD/YYYY) diff --git a/ce/iir/challenge/sign.py b/ce/iir/challenge/sign.py index 0322f97..82595b9 100644 --- a/ce/iir/challenge/sign.py +++ b/ce/iir/challenge/sign.py @@ -8,6 +8,7 @@ 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. +RS256 is supported for did:web only for now. --algorithm picks the implementation: Ed25519 alg=EdDSA, --private-key is a multibase seed (z...). @@ -24,6 +25,7 @@ import click from rich.console import Console +from ce.iir import did_ops from ce.implementations import iir_challenge_sign_ed25519 as _ed25519 from ce.implementations import iir_challenge_sign_rs256 as _rs256 @@ -120,6 +122,7 @@ def main( \b --algorithm Ed25519 : --private-key is the multibase seed (z...). --algorithm RS256 : --private-key is a PEM file path or the PEM text. + did:web only for now (RSA did:key is not supported yet). The challenge JSON must include: did, challenge, aud, iat, exp. Signature verification uses did:key (offline) or did:web (HTTPS). @@ -140,6 +143,8 @@ def main( kid = payload_obj["did"].strip() if algorithm == ALGORITHM_RS256: + if kid.startswith("did:key:") and not did_ops.RSA_DID_KEY_ENABLED: + raise click.ClickException(did_ops.RSA_DID_KEY_HIDDEN_MESSAGE) token = _rs256.sign_and_verify(private_key, kid, payload_obj) else: if looks_like_rsa_key(private_key): diff --git a/ce/iir/csv_processor.py b/ce/iir/csv_processor.py index 73bcc77..334b3f5 100644 --- a/ce/iir/csv_processor.py +++ b/ce/iir/csv_processor.py @@ -4,12 +4,15 @@ ce iir challenge bulk-sign - CTID format validation + - Algorithm check (Ed25519 or RS256, required on every row) - Membership check - Registry lookup - DID classification + validation - Verification method check - Challenge creation - - JWT signing + local verification + - JWT signing + local verification, by Algorithm: + Ed25519 -> ce.implementations.iir_challenge_sign_ed25519 + RS256 -> ce.implementations.iir_challenge_sign_rs256 - writes Output CSV and Errors CSV ce iir issuer-did publish @@ -23,8 +26,12 @@ import csv from pathlib import Path +from typing import Any + +import click from ce.iir.did_ops import ( + ALGORITHM_RS256, call_create_challenges, call_get_organization_iir_detail, call_get_registry_resource, @@ -36,13 +43,14 @@ call_verify_jwt_signature, classify_did, merge_autofill, - sign_proof_jwt, + validate_algorithm, validate_ctid, validate_date, validate_did_key_prefix, validate_verification_method, - verify_proof_jwt, ) +from ce.implementations import iir_challenge_sign_ed25519 as _ed25519 +from ce.implementations import iir_challenge_sign_rs256 as _rs256 from ce.utils.display import new_console, plain_table console = new_console() @@ -53,13 +61,57 @@ "CTID", "DID", "VerificationMethod", + "Algorithm", "Challenge", "ProofJWT", "ValidFrom", "ValidUntil", ] ERROR_FIELDS = ["CTID", "DID", "VerificationMethod", "Algorithm", "Error"] -PUBLISH_ERR_FIELDS = ["CTID", "DID", "VerificationMethod", "Challenge", "Error"] +PUBLISH_ERR_FIELDS = [ + "CTID", + "DID", + "VerificationMethod", + "Algorithm", + "Challenge", + "Error", +] + + +def is_pem_text(value: str) -> bool: + """True when value is PEM key text (real or literal \\n line breaks), not a path.""" + return "-----BEGIN" in value or "\\n" in value + + +def resolve_private_key(algorithm: str, private_key: str, csv_folder: Path) -> str: + if algorithm != ALGORITHM_RS256: + return private_key + if is_pem_text(private_key): + return private_key + + candidate = csv_folder / Path(private_key).expanduser() + if _rs256.is_existing_file(str(candidate)): + return str(candidate) + return private_key + + +def sign_challenge( + algorithm: str, + private_key: str, + kid: str, + payload: dict[str, Any], + csv_folder: Path, +) -> str: + if algorithm == ALGORITHM_RS256: + key_value = resolve_private_key(algorithm, private_key, csv_folder) + return _rs256.sign_and_verify(key_value, kid, payload) + + if is_pem_text(private_key): + raise click.ClickException( + "PrivateKey looks like an RSA/PEM key but Algorithm is Ed25519. " + "Use RS256 for RSA keys." + ) + return _ed25519.sign_and_verify(private_key, kid, payload) def run_generate( @@ -73,15 +125,20 @@ def run_generate( """Validate membership, registry, DIDs, create challenges, sign JWTs. Steps per row: - 1. Validate CTID format - 2. Membership check — is the user a member of this org? - 3. Registry check — is the CTID published in the registry? - 4. Classify DID + prefix check - 5. DID API validation - 6. Validate verification method - 7. Create challenge - 8. Sign JWT - 9. Local JWT verification + 1. Validate CTID format (and ValidFrom / ValidUntil) + 2. Algorithm check — Ed25519 or RS256, required on every row + 3. Membership check — is the user a member of this org? + 4. Registry check — is the CTID published in the registry? + 5. Classify DID + did:key key type check (multicodec vs Algorithm) + 6. DID API validation + 7. Validate verification method + 8. Create challenge + 9. Sign JWT with the Algorithm's implementation, then verify it locally + + PrivateKey per Algorithm: + Ed25519 multibase seed (z...) + RS256 PEM key file path (relative paths are read from the CSV's folder), + PEM text with literal \\n line breaks, or bare base64 Returns (ok_count, error_count). """ @@ -146,6 +203,10 @@ def fail(reason: str) -> None: ok, err, valid_until = validate_date(valid_until, "ValidUntil") if not ok: fail(err) + if not error: + ok, err = validate_algorithm(alg) + if not ok: + fail(err) if not error: ok, err = call_is_user_member( @@ -233,15 +294,18 @@ def fail(reason: str) -> None: fail("PrivateKey is required for JWT signing") else: try: - proof_jwt = sign_proof_jwt(privkey, vm, challenge_payload) + proof_jwt = sign_challenge( + alg, + privkey, + vm, + challenge_payload, + input_file.parent, + ) + except click.ClickException as e: + fail(f"JWT signing failed: {e.format_message()}") except Exception as e: # noqa: BLE001 - isolate signing failures to the current CSV row. fail(f"JWT signing failed: {e}") - if not error: - ok, err = verify_proof_jwt(proof_jwt, vm) - if not ok: - fail(err) - ctid_short = (ctid[:42] + "…") if len(ctid) > 43 else ctid if not error: @@ -251,6 +315,7 @@ def fail(reason: str) -> None: "CTID": ctid, "DID": did, "VerificationMethod": vm, + "Algorithm": alg, "Challenge": challenge_uuid, "ProofJWT": proof_jwt, "ValidFrom": valid_from, @@ -273,12 +338,12 @@ def fail(reason: str) -> None: console.print(table) - with output_file.open("w", newline="") as f: + with output_file.open("w", newline="", encoding="utf-8-sig") as f: writer = csv.DictWriter(f, fieldnames=OUTPUT_FIELDS) writer.writeheader() writer.writerows(ok_rows) - with errors_file.open("w", newline="") as f: + with errors_file.open("w", newline="", encoding="utf-8-sig") as f: writer = csv.DictWriter(f, fieldnames=ERROR_FIELDS) writer.writeheader() writer.writerows(error_rows) @@ -335,6 +400,7 @@ def run_upload( proof_jwt = row["ProofJWT"] challenge_uuid = row["Challenge"] vm = row["VerificationMethod"] + alg = row.get("Algorithm", "") valid_from = row.get("ValidFrom", "") valid_until = row.get("ValidUntil", "") ctid_short = (ctid[:42] + "…") if len(ctid) > 43 else ctid @@ -403,6 +469,7 @@ def pub_fail(reason: str) -> None: "CTID": ctid, "DID": did, "VerificationMethod": vm, + "Algorithm": alg, "Challenge": challenge_uuid, "Error": pub_error, } @@ -412,7 +479,7 @@ def pub_fail(reason: str) -> None: console.print(table) - with publish_err_file.open("w", newline="") as f: + with publish_err_file.open("w", newline="", encoding="utf-8-sig") as f: writer = csv.DictWriter(f, fieldnames=PUBLISH_ERR_FIELDS) writer.writeheader() writer.writerows(publish_error_rows) diff --git a/ce/iir/did_ops.py b/ce/iir/did_ops.py index 5110ffc..49b38e5 100644 --- a/ce/iir/did_ops.py +++ b/ce/iir/did_ops.py @@ -61,13 +61,20 @@ re.IGNORECASE, ) -SUPPORTED_ALGORITHMS = {"Ed25519", "secp256k1", "P-256", "X25519"} +ALGORITHM_ED25519 = "Ed25519" +ALGORITHM_RS256 = "RS256" -DID_KEY_PREFIX_MAP = { - "z6Mk": "Ed25519", - "zQ3s": "secp256k1", - "zDn": "P-256", - "z6LS": "X25519", +SUPPORTED_ALGORITHMS = {ALGORITHM_ED25519, ALGORITHM_RS256} + +RSA_DID_KEY_ENABLED = False +RSA_DID_KEY_HIDDEN_MESSAGE = ( + "RS256 is supported for did:web only for now. RSA did:key is not supported yet." +) +RSA_PUB_MULTICODEC = 0x1205 + +DID_KEY_CODEC_MAP = { + 0xED: ("Ed25519", ALGORITHM_ED25519), # ed25519-pub + RSA_PUB_MULTICODEC: ("RSA", ALGORITHM_RS256), # rsa-pub } IIR_TASK = "IIR" @@ -161,27 +168,51 @@ def classify_did(did: str) -> tuple[str, str]: return "unknown", f"unrecognised DID method in '{did}'" -def validate_did_key_prefix(did: str, algorithm: str) -> tuple[bool, str]: +def validate_algorithm(algorithm: str) -> tuple[bool, str]: if not algorithm: - return False, "Algorithm is required for did:key" + return ( + False, + f"Algorithm is required — must be one of {', '.join(sorted(SUPPORTED_ALGORITHMS))}", + ) if algorithm not in SUPPORTED_ALGORITHMS: return ( False, f"unsupported algorithm '{algorithm}' — must be one of {', '.join(sorted(SUPPORTED_ALGORITHMS))}", ) - key_part = did[len("did:key:") :] + return True, "" + + +def validate_did_key_prefix(did: str, algorithm: str) -> tuple[bool, str]: + ok, err = validate_algorithm(algorithm) + if not ok: + return False, err + + key_part = did[len("did:key:") :].split("#", 1)[0] if not key_part: return False, "did:key has no key material after 'did:key:'" - expected = next( - (alg for pfx, alg in DID_KEY_PREFIX_MAP.items() if key_part.startswith(pfx)), - None, - ) - if expected is None: - return False, f"unrecognised did:key prefix '{key_part[:8]}...'" + + try: + raw = _decode_multibase_base58btc(key_part) + codec, _ = _parse_uvarint(raw) + except ValueError as e: + return False, f"invalid did:key encoding: {e}" + + if codec == RSA_PUB_MULTICODEC and not RSA_DID_KEY_ENABLED: + return False, RSA_DID_KEY_HIDDEN_MESSAGE + + entry = DID_KEY_CODEC_MAP.get(codec) + if entry is None: + return ( + False, + f"unsupported did:key key type (multicodec 0x{codec:X}) — supported: Ed25519, RSA", + ) + + key_type, expected = entry if expected != algorithm: return ( False, - f"algorithm mismatch: key prefix suggests '{expected}' but CSV declares '{algorithm}'", + f"algorithm mismatch: did:key holds an {key_type} key (use {expected}) " + f"but CSV declares '{algorithm}'", ) return True, "" diff --git a/tests/cassettes/TestEd25519DidWebFlowIntegration.test_sign_verify_save.yaml b/tests/cassettes/TestEd25519DidWebFlowIntegration.test_sign_verify_save.yaml new file mode 100644 index 0000000..c11a910 --- /dev/null +++ b/tests/cassettes/TestEd25519DidWebFlowIntegration.test_sign_verify_save.yaml @@ -0,0 +1,182 @@ +interactions: +- request: + body: Ctid=ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73&VerificationMethodIds=did%3Aweb%3Asandbox.credentialengine.org%23z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '158' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/createChallenges + response: + body: + string: '[{"Challenge":"664f5398-0d99-4999-adea-5a45adb455f8","Did":"did:web:sandbox.credentialengine.org#z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f","Aud":"https://issuerregistry.credentialengine.org","Iat":1796175262,"Exp":1796261662,"Ctid":"ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73","CreatedDate":"2026-12-02T01:34:22.8276181+00:00"}]' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '333' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:22 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcY3JlYXRlQ2hhbGxlbmdlcw==?= + status: + code: 200 + message: OK +- request: + body: '' + headers: + accept: + - application/did+json, application/json + accept-encoding: + - gzip, deflate, zstd + connection: + - keep-alive + host: + - sandbox.credentialengine.org + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: GET + uri: https://sandbox.credentialengine.org/.well-known/did.json + response: + body: + string: "{\r\n\"@context\": [\r\n\t \"https://www.w3.org/ns/did/v1\",\r\n\t + \ \"https://w3id.org/security/suites/ed25519-2020/v1\",\r\n\t \"https://w3id.org/security/suites/x25519-2020/v1\"\r\n\t],\r\n\t\"id\": + \"did:web:sandbox.credentialengine.org\",\r\n\t\"verificationMethod\": [\r\n\t + \ {\r\n\t\t\"id\": \"did:web:sandbox.credentialengine.org#z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f\",\r\n\t\t\"type\": + \"Ed25519VerificationKey2020\",\r\n\t\t\"controller\": \"did:web:sandbox.credentialengine.org\",\r\n\t\t\"publicKeyMultibase\": + \"z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f\"\r\n\t },\r\n\t {\r\n + \ \"id\": \"did:web:sandbox.credentialengine.org#key-1\",\r\n \"type\": + \"JsonWebKey2020\",\r\n \"controller\": \"did:web:sandbox.credentialengine.org\",\r\n + \ \"publicKeyJwk\": {\r\n \"kty\": \"RSA\",\r\n \"n\": \"1xcCnJh3uciJ4JVy5ttEQMVON23oXVcabjUvthA--mJYgysnA3rc-sNEX2W3hzjPVDZYdqy9BcDERAifQ2xpv49spPnWsCN6yLHncNtboYsBNwMnhJOWL_ih7kvpDQuxkRrIMrM2h8Jasrf1qZOX7e7iJw1ucNVh7qf6DdQPtEw0uaBk0U29EpeHjkTY8M7lKg24miHfx903T9589s5_mGpbsTNdATU6ngVd9aQdJH4d-XN8qy6CfKNfX4lxfqYO8h871nXwiaIkB4dul91iSSUjxG9C49wHchu_B10lL8eIPNZ99ZZ_Q0EKE76S6vD02BNziApOYmpcM6_r9rJZ0Q\",\r\n + \ \"e\": \"AQAB\",\r\n \"alg\": \"RS256\",\r\n \"use\": + \"sig\"\r\n }\r\n }\r\n\t],\r\n\t\"assertionMethod\": [\r\n\t\t\"did:web:sandbox.credentialengine.org#z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f\",\r\n\t\t\"did:web:sandbox.credentialengine.org#key-1\"\r\n\t],\r\n\t\"authentication\":[\r\n\t\t\"did:web:sandbox.credentialengine.org#z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f\",\r\n\t\t\"did:web:sandbox.credentialengine.org#key-1\"\r\n\t]\r\n\t\r\n}\r\n" + headers: + accept-ranges: + - bytes + content-length: + - '1524' + content-type: + - application/json + date: + - Wed, 02 Dec 2026 01:33:55 GMT + etag: + - '"4288ec267978dd1:0"' + last-modified: + - Thu, 19 Nov 2026 22:56:03 GMT + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + status: + code: 200 + message: OK +- request: + body: Jwt=eyJhbGciOiJFZERTQSIsImtpZCI6ImRpZDp3ZWI6c2FuZGJveC5jcmVkZW50aWFsZW5naW5lLm9yZyN6Nk1rd1lHVkZtNm9GUmVMWXdvSExvYmpWVjVQQmpuYVl3QjlWdkphaG40bkF4NGYiLCJ0eXAiOiJKV1QifQ.eyJkaWQiOiJkaWQ6d2ViOnNhbmRib3guY3JlZGVudGlhbGVuZ2luZS5vcmcjejZNa3dZR1ZGbTZvRlJlTFl3b0hMb2JqVlY1UEJqbmFZd0I5VnZKYWhuNG5BeDRmIiwiY2hhbGxlbmdlIjoiNjY0ZjUzOTgtMGQ5OS00OTk5LWFkZWEtNWE0NWFkYjQ1NWY4IiwiYXVkIjoiaHR0cHM6Ly9pc3N1ZXJyZWdpc3RyeS5jcmVkZW50aWFsZW5naW5lLm9yZyIsImlhdCI6MTc5NjE3NTI2MiwiZXhwIjoxNzk2MjYxNjYyLCJjdGlkIjoiY2UtYTQwNDE5ODMtYjFhZS00YWQ0LWE0M2QtMjg0YTViNGIyZDczIn0.QQwXnMMwF2VpXKgngcgH3rKNyWkvpXFxe2pCey5Lk143jQ-NiGh8tPc5l75yzKv7sz782tRMnHd4n56s2eaaCw&ChallengeId=664f5398-0d99-4999-adea-5a45adb455f8 + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '678' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/validateJwt + response: + body: + string: '{"Valid":true}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '14' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:22 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcdmFsaWRhdGVKd3Q=?= + status: + code: 200 + message: OK +- request: + body: Ctid=ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73&ChallengeId=664f5398-0d99-4999-adea-5a45adb455f8&Token=eyJhbGciOiJFZERTQSIsImtpZCI6ImRpZDp3ZWI6c2FuZGJveC5jcmVkZW50aWFsZW5naW5lLm9yZyN6Nk1rd1lHVkZtNm9GUmVMWXdvSExvYmpWVjVQQmpuYVl3QjlWdkphaG40bkF4NGYiLCJ0eXAiOiJKV1QifQ.eyJkaWQiOiJkaWQ6d2ViOnNhbmRib3guY3JlZGVudGlhbGVuZ2luZS5vcmcjejZNa3dZR1ZGbTZvRlJlTFl3b0hMb2JqVlY1UEJqbmFZd0I5VnZKYWhuNG5BeDRmIiwiY2hhbGxlbmdlIjoiNjY0ZjUzOTgtMGQ5OS00OTk5LWFkZWEtNWE0NWFkYjQ1NWY4IiwiYXVkIjoiaHR0cHM6Ly9pc3N1ZXJyZWdpc3RyeS5jcmVkZW50aWFsZW5naW5lLm9yZyIsImlhdCI6MTc5NjE3NTI2MiwiZXhwIjoxNzk2MjYxNjYyLCJjdGlkIjoiY2UtYTQwNDE5ODMtYjFhZS00YWQ0LWE0M2QtMjg0YTViNGIyZDczIn0.QQwXnMMwF2VpXKgngcgH3rKNyWkvpXFxe2pCey5Lk143jQ-NiGh8tPc5l75yzKv7sz782tRMnHd4n56s2eaaCw + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '725' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/saveChallengeToken + response: + body: + string: '{"ChallengeId":"664f5398-0d99-4999-adea-5a45adb455f8","Ctid":"ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73","Token":"eyJhbGciOiJFZERTQSIsImtpZCI6ImRpZDp3ZWI6c2FuZGJveC5jcmVkZW50aWFsZW5naW5lLm9yZyN6Nk1rd1lHVkZtNm9GUmVMWXdvSExvYmpWVjVQQmpuYVl3QjlWdkphaG40bkF4NGYiLCJ0eXAiOiJKV1QifQ.eyJkaWQiOiJkaWQ6d2ViOnNhbmRib3guY3JlZGVudGlhbGVuZ2luZS5vcmcjejZNa3dZR1ZGbTZvRlJlTFl3b0hMb2JqVlY1UEJqbmFZd0I5VnZKYWhuNG5BeDRmIiwiY2hhbGxlbmdlIjoiNjY0ZjUzOTgtMGQ5OS00OTk5LWFkZWEtNWE0NWFkYjQ1NWY4IiwiYXVkIjoiaHR0cHM6Ly9pc3N1ZXJyZWdpc3RyeS5jcmVkZW50aWFsZW5naW5lLm9yZyIsImlhdCI6MTc5NjE3NTI2MiwiZXhwIjoxNzk2MjYxNjYyLCJjdGlkIjoiY2UtYTQwNDE5ODMtYjFhZS00YWQ0LWE0M2QtMjg0YTViNGIyZDczIn0.QQwXnMMwF2VpXKgngcgH3rKNyWkvpXFxe2pCey5Lk143jQ-NiGh8tPc5l75yzKv7sz782tRMnHd4n56s2eaaCw","IsTokenVerified":true,"CreatedDate":"2026-12-02T01:34:23.3912517+00:00"}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '812' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:22 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcc2F2ZUNoYWxsZW5nZVRva2Vu?= + status: + code: 200 + message: OK +version: 1 diff --git a/tests/cassettes/TestRs256DidKeyFlowIntegration.test_rsa_did_key_jwt_is_rejected_while_hidden.yaml b/tests/cassettes/TestRs256DidKeyFlowIntegration.test_rsa_did_key_jwt_is_rejected_while_hidden.yaml new file mode 100644 index 0000000..be3e03c --- /dev/null +++ b/tests/cassettes/TestRs256DidKeyFlowIntegration.test_rsa_did_key_jwt_is_rejected_while_hidden.yaml @@ -0,0 +1,90 @@ +interactions: +- request: + body: Ctid=ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73&VerificationMethodIds=did%3Akey%3Az4MXj1wBzi9jUstyNt8jPr5DXnHRkBQ5n2E7pE7X5PYUoxnyqgEaFJWvJ97vV4R9c3f1MrJcNoSBHC1PyiAEankju2i5TRjfePwa97whbwag3p4Bx5ea3rVNF87P6syMx21EimhXWZVbAP3EFvSLffBECSL8wJLcZu8XFeMEehG7xRcUqtevMikTTafH7bEeriESYWsqSSpasG6uuTC41ZnKBHzaq72Bby3wiCEfcfjW3k4iVuLVYXnGRbTcwXFnMNhVcWkH7oWke9wYiL7xPHczC3BHNi4YEDxuZKuryZQPndR9EHvgsTs9q2g1h7hCo91335MDcWQd519QfXurjMAg8v9iWB2bwKQMRCW6MYopmSHyRenbr%23z4MXj1wBzi9jUstyNt8jPr5DXnHRkBQ5n2E7pE7X5PYUoxnyqgEaFJWvJ97vV4R9c3f1MrJcNoSBHC1PyiAEankju2i5TRjfePwa97whbwag3p4Bx5ea3rVNF87P6syMx21EimhXWZVbAP3EFvSLffBECSL8wJLcZu8XFeMEehG7xRcUqtevMikTTafH7bEeriESYWsqSSpasG6uuTC41ZnKBHzaq72Bby3wiCEfcfjW3k4iVuLVYXnGRbTcwXFnMNhVcWkH7oWke9wYiL7xPHczC3BHNi4YEDxuZKuryZQPndR9EHvgsTs9q2g1h7hCo91335MDcWQd519QfXurjMAg8v9iWB2bwKQMRCW6MYopmSHyRenbr + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '828' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/createChallenges + response: + body: + string: '[{"Challenge":"bc8c8544-0cd1-4de2-b81f-e9ef4e741ad2","Did":"did:key:z4MXj1wBzi9jUstyNt8jPr5DXnHRkBQ5n2E7pE7X5PYUoxnyqgEaFJWvJ97vV4R9c3f1MrJcNoSBHC1PyiAEankju2i5TRjfePwa97whbwag3p4Bx5ea3rVNF87P6syMx21EimhXWZVbAP3EFvSLffBECSL8wJLcZu8XFeMEehG7xRcUqtevMikTTafH7bEeriESYWsqSSpasG6uuTC41ZnKBHzaq72Bby3wiCEfcfjW3k4iVuLVYXnGRbTcwXFnMNhVcWkH7oWke9wYiL7xPHczC3BHNi4YEDxuZKuryZQPndR9EHvgsTs9q2g1h7hCo91335MDcWQd519QfXurjMAg8v9iWB2bwKQMRCW6MYopmSHyRenbr#z4MXj1wBzi9jUstyNt8jPr5DXnHRkBQ5n2E7pE7X5PYUoxnyqgEaFJWvJ97vV4R9c3f1MrJcNoSBHC1PyiAEankju2i5TRjfePwa97whbwag3p4Bx5ea3rVNF87P6syMx21EimhXWZVbAP3EFvSLffBECSL8wJLcZu8XFeMEehG7xRcUqtevMikTTafH7bEeriESYWsqSSpasG6uuTC41ZnKBHzaq72Bby3wiCEfcfjW3k4iVuLVYXnGRbTcwXFnMNhVcWkH7oWke9wYiL7xPHczC3BHNi4YEDxuZKuryZQPndR9EHvgsTs9q2g1h7hCo91335MDcWQd519QfXurjMAg8v9iWB2bwKQMRCW6MYopmSHyRenbr","Aud":"https://issuerregistry.credentialengine.org","Iat":1796175264,"Exp":1796261664,"Ctid":"ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73","CreatedDate":"2026-12-02T01:34:24.5040706+00:00"}]' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '1003' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:23 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcY3JlYXRlQ2hhbGxlbmdlcw==?= + status: + code: 200 + message: OK +- request: + body: Jwt=eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDprZXk6ejRNWGoxd0J6aTlqVXN0eU50OGpQcjVEWG5IUmtCUTVuMkU3cEU3WDVQWVVveG55cWdFYUZKV3ZKOTd2VjRSOWMzZjFNckpjTm9TQkhDMVB5aUFFYW5ranUyaTVUUmpmZVB3YTk3d2hid2FnM3A0Qng1ZWEzclZORjg3UDZzeU14MjFFaW1oWFdaVmJBUDNFRnZTTGZmQkVDU0w4d0pMY1p1OFhGZU1FZWhHN3hSY1VxdGV2TWlrVFRhZkg3YkVlcmlFU1lXc3FTU3Bhc0c2dXVUQzQxWm5LQkh6YXE3MkJieTN3aUNFZmNmalczazRpVnVMVllYbkdSYlRjd1hGbk1OaFZjV2tIN29Xa2U5d1lpTDd4UEhjekMzQkhOaTRZRUR4dVpLdXJ5WlFQbmRSOUVIdmdzVHM5cTJnMWg3aENvOTEzMzVNRGNXUWQ1MTlRZlh1cmpNQWc4djlpV0IyYndLUU1SQ1c2TVlvcG1TSHlSZW5iciN6NE1YajF3QnppOWpVc3R5TnQ4alByNURYbkhSa0JRNW4yRTdwRTdYNVBZVW94bnlxZ0VhRkpXdko5N3ZWNFI5YzNmMU1ySmNOb1NCSEMxUHlpQUVhbmtqdTJpNVRSamZlUHdhOTd3aGJ3YWczcDRCeDVlYTNyVk5GODdQNnN5TXgyMUVpbWhYV1pWYkFQM0VGdlNMZmZCRUNTTDh3SkxjWnU4WEZlTUVlaEc3eFJjVXF0ZXZNaWtUVGFmSDdiRWVyaUVTWVdzcVNTcGFzRzZ1dVRDNDFabktCSHphcTcyQmJ5M3dpQ0VmY2ZqVzNrNGlWdUxWWVhuR1JiVGN3WEZuTU5oVmNXa0g3b1drZTl3WWlMN3hQSGN6QzNCSE5pNFlFRHh1Wkt1cnlaUVBuZFI5RUh2Z3NUczlxMmcxaDdoQ285MTMzNU1EY1dRZDUxOVFmWHVyak1BZzh2OWlXQjJid0tRTVJDVzZNWW9wbVNIeVJlbmJyIiwidHlwIjoiSldUIn0.eyJkaWQiOiJkaWQ6a2V5Ono0TVhqMXdCemk5alVzdHlOdDhqUHI1RFhuSFJrQlE1bjJFN3BFN1g1UFlVb3hueXFnRWFGSld2Sjk3dlY0UjljM2YxTXJKY05vU0JIQzFQeWlBRWFua2p1Mmk1VFJqZmVQd2E5N3doYndhZzNwNEJ4NWVhM3JWTkY4N1A2c3lNeDIxRWltaFhXWlZiQVAzRUZ2U0xmZkJFQ1NMOHdKTGNadThYRmVNRWVoRzd4UmNVcXRldk1pa1RUYWZIN2JFZXJpRVNZV3NxU1NwYXNHNnV1VEM0MVpuS0JIemFxNzJCYnkzd2lDRWZjZmpXM2s0aVZ1TFZZWG5HUmJUY3dYRm5NTmhWY1drSDdvV2tlOXdZaUw3eFBIY3pDM0JITmk0WUVEeHVaS3VyeVpRUG5kUjlFSHZnc1RzOXEyZzFoN2hDbzkxMzM1TURjV1FkNTE5UWZYdXJqTUFnOHY5aVdCMmJ3S1FNUkNXNk1Zb3BtU0h5UmVuYnIjejRNWGoxd0J6aTlqVXN0eU50OGpQcjVEWG5IUmtCUTVuMkU3cEU3WDVQWVVveG55cWdFYUZKV3ZKOTd2VjRSOWMzZjFNckpjTm9TQkhDMVB5aUFFYW5ranUyaTVUUmpmZVB3YTk3d2hid2FnM3A0Qng1ZWEzclZORjg3UDZzeU14MjFFaW1oWFdaVmJBUDNFRnZTTGZmQkVDU0w4d0pMY1p1OFhGZU1FZWhHN3hSY1VxdGV2TWlrVFRhZkg3YkVlcmlFU1lXc3FTU3Bhc0c2dXVUQzQxWm5LQkh6YXE3MkJieTN3aUNFZmNmalczazRpVnVMVllYbkdSYlRjd1hGbk1OaFZjV2tIN29Xa2U5d1lpTDd4UEhjekMzQkhOaTRZRUR4dVpLdXJ5WlFQbmRSOUVIdmdzVHM5cTJnMWg3aENvOTEzMzVNRGNXUWQ1MTlRZlh1cmpNQWc4djlpV0IyYndLUU1SQ1c2TVlvcG1TSHlSZW5iciIsImNoYWxsZW5nZSI6ImJjOGM4NTQ0LTBjZDEtNGRlMi1iODFmLWU5ZWY0ZTc0MWFkMiIsImF1ZCI6Imh0dHBzOi8vaXNzdWVycmVnaXN0cnkuY3JlZGVudGlhbGVuZ2luZS5vcmciLCJpYXQiOjE3OTYxNzUyNjQsImV4cCI6MTc5NjI2MTY2NCwiY3RpZCI6ImNlLWE0MDQxOTgzLWIxYWUtNGFkNC1hNDNkLTI4NGE1YjRiMmQ3MyJ9.VxxCx8Mbax3eIEIP8o0-KshkigXy4O1NPVbo7YxylW7McJynkkibtSmfEcbOOVAQ6Yx92vJOUIa7ziWrVtlbfs8ogjb3GnBI05RT97T0hYvWIvuNe7M85rTe97RVYatLmzjsaxajaLtE58h37GFMf-IxF5MfrSDXEKsaI1JsK2ecj_V2H7z9Y9Hw0vjbvclc-dEWDcQ9q56-ItQWN66PRdmDiEz6ZSbdROXWX6sthpirCH10iCql-3Q2x_rW7w4rnC9ztMlJCNRYbo3F5qXLj7d-NV_1xVf0hzMF6qiHD9XhJoIAwfQ9qj9rQCS8YYuTd9ZF9DTHGPrVoHam2OynNg&ChallengeId=bc8c8544-0cd1-4de2-b81f-e9ef4e741ad2 + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '2720' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/validateJwt + response: + body: + string: '{"Error":""}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '12' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:23 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcdmFsaWRhdGVKd3Q=?= + status: + code: 400 + message: Bad Request +version: 1 diff --git a/tests/cassettes/TestRs256DidWebFlowIntegration.test_eddsa_token_for_rsa_key_is_rejected.yaml b/tests/cassettes/TestRs256DidWebFlowIntegration.test_eddsa_token_for_rsa_key_is_rejected.yaml new file mode 100644 index 0000000..f6a5467 --- /dev/null +++ b/tests/cassettes/TestRs256DidWebFlowIntegration.test_eddsa_token_for_rsa_key_is_rejected.yaml @@ -0,0 +1,90 @@ +interactions: +- request: + body: Ctid=ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73&VerificationMethodIds=did%3Aweb%3Asandbox.credentialengine.org%23key-1 + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '115' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/createChallenges + response: + body: + string: '[{"Challenge":"d795875b-a42a-47e5-9e0a-542036cd4fb6","Did":"did:web:sandbox.credentialengine.org#key-1","Aud":"https://issuerregistry.credentialengine.org","Iat":1796175264,"Exp":1796261664,"Ctid":"ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73","CreatedDate":"2026-12-02T01:34:24.234786+00:00"}]' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '289' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:23 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcY3JlYXRlQ2hhbGxlbmdlcw==?= + status: + code: 200 + message: OK +- request: + body: Jwt=eyJhbGciOiJFZERTQSIsImtpZCI6ImRpZDp3ZWI6c2FuZGJveC5jcmVkZW50aWFsZW5naW5lLm9yZyNrZXktMSIsInR5cCI6IkpXVCJ9.eyJkaWQiOiJkaWQ6d2ViOnNhbmRib3guY3JlZGVudGlhbGVuZ2luZS5vcmcja2V5LTEiLCJjaGFsbGVuZ2UiOiJkNzk1ODc1Yi1hNDJhLTQ3ZTUtOWUwYS01NDIwMzZjZDRmYjYiLCJhdWQiOiJodHRwczovL2lzc3VlcnJlZ2lzdHJ5LmNyZWRlbnRpYWxlbmdpbmUub3JnIiwiaWF0IjoxNzk2MTc1MjY0LCJleHAiOjE3OTYyNjE2NjQsImN0aWQiOiJjZS1hNDA0MTk4My1iMWFlLTRhZDQtYTQzZC0yODRhNWI0YjJkNzMifQ.2UFxuNlhunFtj5DFae8GmyZIIDktNo7bwUjuA3O7gwMVkX2GyjMIm9UTd1ebJv4lcCmG-MfhX4tfK3-KL6hJDA&ChallengeId=d795875b-a42a-47e5-9e0a-542036cd4fb6 + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '563' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/validateJwt + response: + body: + string: '{"Error":""}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '12' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:23 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcdmFsaWRhdGVKd3Q=?= + status: + code: 400 + message: Bad Request +version: 1 diff --git a/tests/cassettes/TestRs256DidWebFlowIntegration.test_sign_verify_save.yaml b/tests/cassettes/TestRs256DidWebFlowIntegration.test_sign_verify_save.yaml new file mode 100644 index 0000000..babb529 --- /dev/null +++ b/tests/cassettes/TestRs256DidWebFlowIntegration.test_sign_verify_save.yaml @@ -0,0 +1,182 @@ +interactions: +- request: + body: Ctid=ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73&VerificationMethodIds=did%3Aweb%3Asandbox.credentialengine.org%23key-1 + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '115' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/createChallenges + response: + body: + string: '[{"Challenge":"267dcc70-ee78-4001-8418-c4065ab19dae","Did":"did:web:sandbox.credentialengine.org#key-1","Aud":"https://issuerregistry.credentialengine.org","Iat":1796175263,"Exp":1796261663,"Ctid":"ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73","CreatedDate":"2026-12-02T01:34:23.4466571+00:00"}]' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '290' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:22 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcY3JlYXRlQ2hhbGxlbmdlcw==?= + status: + code: 200 + message: OK +- request: + body: '' + headers: + accept: + - application/did+json, application/json + accept-encoding: + - gzip, deflate, zstd + connection: + - keep-alive + host: + - sandbox.credentialengine.org + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: GET + uri: https://sandbox.credentialengine.org/.well-known/did.json + response: + body: + string: "{\r\n\"@context\": [\r\n\t \"https://www.w3.org/ns/did/v1\",\r\n\t + \ \"https://w3id.org/security/suites/ed25519-2020/v1\",\r\n\t \"https://w3id.org/security/suites/x25519-2020/v1\"\r\n\t],\r\n\t\"id\": + \"did:web:sandbox.credentialengine.org\",\r\n\t\"verificationMethod\": [\r\n\t + \ {\r\n\t\t\"id\": \"did:web:sandbox.credentialengine.org#z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f\",\r\n\t\t\"type\": + \"Ed25519VerificationKey2020\",\r\n\t\t\"controller\": \"did:web:sandbox.credentialengine.org\",\r\n\t\t\"publicKeyMultibase\": + \"z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f\"\r\n\t },\r\n\t {\r\n + \ \"id\": \"did:web:sandbox.credentialengine.org#key-1\",\r\n \"type\": + \"JsonWebKey2020\",\r\n \"controller\": \"did:web:sandbox.credentialengine.org\",\r\n + \ \"publicKeyJwk\": {\r\n \"kty\": \"RSA\",\r\n \"n\": \"1xcCnJh3uciJ4JVy5ttEQMVON23oXVcabjUvthA--mJYgysnA3rc-sNEX2W3hzjPVDZYdqy9BcDERAifQ2xpv49spPnWsCN6yLHncNtboYsBNwMnhJOWL_ih7kvpDQuxkRrIMrM2h8Jasrf1qZOX7e7iJw1ucNVh7qf6DdQPtEw0uaBk0U29EpeHjkTY8M7lKg24miHfx903T9589s5_mGpbsTNdATU6ngVd9aQdJH4d-XN8qy6CfKNfX4lxfqYO8h871nXwiaIkB4dul91iSSUjxG9C49wHchu_B10lL8eIPNZ99ZZ_Q0EKE76S6vD02BNziApOYmpcM6_r9rJZ0Q\",\r\n + \ \"e\": \"AQAB\",\r\n \"alg\": \"RS256\",\r\n \"use\": + \"sig\"\r\n }\r\n }\r\n\t],\r\n\t\"assertionMethod\": [\r\n\t\t\"did:web:sandbox.credentialengine.org#z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f\",\r\n\t\t\"did:web:sandbox.credentialengine.org#key-1\"\r\n\t],\r\n\t\"authentication\":[\r\n\t\t\"did:web:sandbox.credentialengine.org#z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f\",\r\n\t\t\"did:web:sandbox.credentialengine.org#key-1\"\r\n\t]\r\n\t\r\n}\r\n" + headers: + accept-ranges: + - bytes + content-length: + - '1524' + content-type: + - application/json + date: + - Wed, 02 Dec 2026 01:33:56 GMT + etag: + - '"4288ec267978dd1:0"' + last-modified: + - Thu, 19 Nov 2026 22:56:03 GMT + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + status: + code: 200 + message: OK +- request: + body: Jwt=eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDp3ZWI6c2FuZGJveC5jcmVkZW50aWFsZW5naW5lLm9yZyNrZXktMSIsInR5cCI6IkpXVCJ9.eyJkaWQiOiJkaWQ6d2ViOnNhbmRib3guY3JlZGVudGlhbGVuZ2luZS5vcmcja2V5LTEiLCJjaGFsbGVuZ2UiOiIyNjdkY2M3MC1lZTc4LTQwMDEtODQxOC1jNDA2NWFiMTlkYWUiLCJhdWQiOiJodHRwczovL2lzc3VlcnJlZ2lzdHJ5LmNyZWRlbnRpYWxlbmdpbmUub3JnIiwiaWF0IjoxNzk2MTc1MjYzLCJleHAiOjE3OTYyNjE2NjMsImN0aWQiOiJjZS1hNDA0MTk4My1iMWFlLTRhZDQtYTQzZC0yODRhNWI0YjJkNzMifQ.osapf3vP_aqi_ZrUz8KeW-BJCc_b-4Yepv0FVR1zf0PYzIPBlkTjQR-N5JV4zR0TTkzcdfswq2vCOvrhzus6XZ5mRUS3-E8IuFJUE9vbKBsba2C8cJZwRWAEa2Gd3uBMxhheRG4Gu5nHPu7bwRxBrZ1x66NGEmYhZZnKfbi5LLgOaxiOCzFFTud8m47wRAs02HsisUAz49ewdfSeZ1RL87cjVVRBLZNW1VnJoX0CmFxewPHpoPLbkT6qvs1h1972JMai0eIbhwyqpMzdYlOlDxV93Ixhy2qgr6153oumWdQT_LHBoIaI1YoNxXIkmFApG5XCLbiY1-lAMwvXsvsUEA&ChallengeId=267dcc70-ee78-4001-8418-c4065ab19dae + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '819' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/validateJwt + response: + body: + string: '{"Valid":true}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '14' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:23 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcdmFsaWRhdGVKd3Q=?= + status: + code: 200 + message: OK +- request: + body: Ctid=ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73&ChallengeId=267dcc70-ee78-4001-8418-c4065ab19dae&Token=eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDp3ZWI6c2FuZGJveC5jcmVkZW50aWFsZW5naW5lLm9yZyNrZXktMSIsInR5cCI6IkpXVCJ9.eyJkaWQiOiJkaWQ6d2ViOnNhbmRib3guY3JlZGVudGlhbGVuZ2luZS5vcmcja2V5LTEiLCJjaGFsbGVuZ2UiOiIyNjdkY2M3MC1lZTc4LTQwMDEtODQxOC1jNDA2NWFiMTlkYWUiLCJhdWQiOiJodHRwczovL2lzc3VlcnJlZ2lzdHJ5LmNyZWRlbnRpYWxlbmdpbmUub3JnIiwiaWF0IjoxNzk2MTc1MjYzLCJleHAiOjE3OTYyNjE2NjMsImN0aWQiOiJjZS1hNDA0MTk4My1iMWFlLTRhZDQtYTQzZC0yODRhNWI0YjJkNzMifQ.osapf3vP_aqi_ZrUz8KeW-BJCc_b-4Yepv0FVR1zf0PYzIPBlkTjQR-N5JV4zR0TTkzcdfswq2vCOvrhzus6XZ5mRUS3-E8IuFJUE9vbKBsba2C8cJZwRWAEa2Gd3uBMxhheRG4Gu5nHPu7bwRxBrZ1x66NGEmYhZZnKfbi5LLgOaxiOCzFFTud8m47wRAs02HsisUAz49ewdfSeZ1RL87cjVVRBLZNW1VnJoX0CmFxewPHpoPLbkT6qvs1h1972JMai0eIbhwyqpMzdYlOlDxV93Ixhy2qgr6153oumWdQT_LHBoIaI1YoNxXIkmFApG5XCLbiY1-lAMwvXsvsUEA + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '866' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/saveChallengeToken + response: + body: + string: '{"ChallengeId":"267dcc70-ee78-4001-8418-c4065ab19dae","Ctid":"ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73","Token":"eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDp3ZWI6c2FuZGJveC5jcmVkZW50aWFsZW5naW5lLm9yZyNrZXktMSIsInR5cCI6IkpXVCJ9.eyJkaWQiOiJkaWQ6d2ViOnNhbmRib3guY3JlZGVudGlhbGVuZ2luZS5vcmcja2V5LTEiLCJjaGFsbGVuZ2UiOiIyNjdkY2M3MC1lZTc4LTQwMDEtODQxOC1jNDA2NWFiMTlkYWUiLCJhdWQiOiJodHRwczovL2lzc3VlcnJlZ2lzdHJ5LmNyZWRlbnRpYWxlbmdpbmUub3JnIiwiaWF0IjoxNzk2MTc1MjYzLCJleHAiOjE3OTYyNjE2NjMsImN0aWQiOiJjZS1hNDA0MTk4My1iMWFlLTRhZDQtYTQzZC0yODRhNWI0YjJkNzMifQ.osapf3vP_aqi_ZrUz8KeW-BJCc_b-4Yepv0FVR1zf0PYzIPBlkTjQR-N5JV4zR0TTkzcdfswq2vCOvrhzus6XZ5mRUS3-E8IuFJUE9vbKBsba2C8cJZwRWAEa2Gd3uBMxhheRG4Gu5nHPu7bwRxBrZ1x66NGEmYhZZnKfbi5LLgOaxiOCzFFTud8m47wRAs02HsisUAz49ewdfSeZ1RL87cjVVRBLZNW1VnJoX0CmFxewPHpoPLbkT6qvs1h1972JMai0eIbhwyqpMzdYlOlDxV93Ixhy2qgr6153oumWdQT_LHBoIaI1YoNxXIkmFApG5XCLbiY1-lAMwvXsvsUEA","IsTokenVerified":true,"CreatedDate":"2026-12-02T01:34:23.9855842+00:00"}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '953' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:23 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcc2F2ZUNoYWxsZW5nZVRva2Vu?= + status: + code: 200 + message: OK +version: 1 diff --git a/tests/cassettes/TestRs256DidWebFlowIntegration.test_wrong_rsa_key_is_rejected.yaml b/tests/cassettes/TestRs256DidWebFlowIntegration.test_wrong_rsa_key_is_rejected.yaml new file mode 100644 index 0000000..eb7d188 --- /dev/null +++ b/tests/cassettes/TestRs256DidWebFlowIntegration.test_wrong_rsa_key_is_rejected.yaml @@ -0,0 +1,90 @@ +interactions: +- request: + body: Ctid=ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73&VerificationMethodIds=did%3Aweb%3Asandbox.credentialengine.org%23key-1 + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '115' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/createChallenges + response: + body: + string: '[{"Challenge":"f3218abd-5778-4ef3-9628-7a920173e173","Did":"did:web:sandbox.credentialengine.org#key-1","Aud":"https://issuerregistry.credentialengine.org","Iat":1796175264,"Exp":1796261664,"Ctid":"ce-a4041983-b1ae-4ad4-a43d-284a5b4b2d73","CreatedDate":"2026-12-02T01:34:24.0387441+00:00"}]' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '290' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:23 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcY3JlYXRlQ2hhbGxlbmdlcw==?= + status: + code: 200 + message: OK +- request: + body: Jwt=eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDp3ZWI6c2FuZGJveC5jcmVkZW50aWFsZW5naW5lLm9yZyNrZXktMSIsInR5cCI6IkpXVCJ9.eyJkaWQiOiJkaWQ6d2ViOnNhbmRib3guY3JlZGVudGlhbGVuZ2luZS5vcmcja2V5LTEiLCJjaGFsbGVuZ2UiOiJmMzIxOGFiZC01Nzc4LTRlZjMtOTYyOC03YTkyMDE3M2UxNzMiLCJhdWQiOiJodHRwczovL2lzc3VlcnJlZ2lzdHJ5LmNyZWRlbnRpYWxlbmdpbmUub3JnIiwiaWF0IjoxNzk2MTc1MjY0LCJleHAiOjE3OTYyNjE2NjQsImN0aWQiOiJjZS1hNDA0MTk4My1iMWFlLTRhZDQtYTQzZC0yODRhNWI0YjJkNzMifQ.AWFxr0tFiH-0fJX53qM9Mk_7-yyn44dMIPP2BG5lHt7PJLtCHFsvB2kiKfvU7Hf-TmF8jwKbxP6LDvtFLY8-08NC40lxdH3tHSyT30IBz7IXCujgVr3lahXHTUnjpoWaeWDz2i9zm5krtkRVmGw9M6AUL1488xefodzQrUsZHa3UETX0GahjqLRAg9xS80rjKIa2XBXrSZHj-t_e-Dpym_0Xe6ooIboDmF__b0P8DABwoGJL9XBFgcIQ3YeSYuFIuHPTgkBNG8AsJ_Rw6_QzwrThqz2PZTwT-hokhL7p-4j8yCU4bS3iWLRbg_vThGQ704NEpdalS0jnq3turTMoEQ&ChallengeId=f3218abd-5778-4ef3-9628-7a920173e173 + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + content-length: + - '819' + content-type: + - application/x-www-form-urlencoded + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: POST + uri: https://localhost:44330/iir-api/validateJwt + response: + body: + string: '{"Error":""}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '12' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:23 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcdmFsaWRhdGVKd3Q=?= + status: + code: 400 + message: Bad Request +version: 1 diff --git a/tests/cassettes/TestValidateRsaDidKeyIntegration.test_rs256_did_key_is_rejected_while_hidden.yaml b/tests/cassettes/TestValidateRsaDidKeyIntegration.test_rs256_did_key_is_rejected_while_hidden.yaml new file mode 100644 index 0000000..ba71099 --- /dev/null +++ b/tests/cassettes/TestValidateRsaDidKeyIntegration.test_rs256_did_key_is_rejected_while_hidden.yaml @@ -0,0 +1,42 @@ +interactions: +- request: + body: '' + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: GET + uri: https://localhost:44330/iir-api/validateDidKey?alg=RS256&did=did%3Akey%3Az4MXj1wBzi9jUstyP5Bi6CGB8mEVztoazVggv9d2CRTa7BWGE4VWM6C6ZAdJLQyvPAR2W6nerp91V5dmfbbpeNvLcrvf11Fv9QfMg5z7rvpWQQUGZzXMcgKNkyZVgBBjnbKm1BK9es59xZ6UuJPixz1E6Z62nYKJp88Ns3fmhZXqcSvERG8ftjTt6BniVNjYvmKaciGAFcbBL4vP7RJjvKED7nEeLeqN43vdw6EVanF1tpFhqNRyWfSsLiKH21J8deuwoWFUGYSMGpSydsuGDrSJMdMGniWUEQ17cixrsx2weXfS9NzVVoSiGiwWXafa3vwtvaaZQ3iXJkUktjcdgYgJv75Pu6uUngT8h5TnpLM89PEhGczwS + response: + body: + string: '{"Error":""}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '12' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:22 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcdmFsaWRhdGVEaWRLZXk=?= + status: + code: 400 + message: Bad Request +version: 1 diff --git a/tests/cassettes/TestValidateRsaDidKeyIntegration.test_rsa_did_key_is_rejected_while_hidden.yaml b/tests/cassettes/TestValidateRsaDidKeyIntegration.test_rsa_did_key_is_rejected_while_hidden.yaml new file mode 100644 index 0000000..4195161 --- /dev/null +++ b/tests/cassettes/TestValidateRsaDidKeyIntegration.test_rsa_did_key_is_rejected_while_hidden.yaml @@ -0,0 +1,42 @@ +interactions: +- request: + body: '' + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: GET + uri: https://localhost:44330/iir-api/validateDidKey?alg=RSA&did=did%3Akey%3Az4MXj1wBzi9jUstyP212B7UHbo5kV4xCENsJtVJ22xgPZ2VH6Ak6Sb2P113btNn2wmvyah8HQvW2iKSZnHP4eUxZCPiMoT3qT6ufLSFMmVZyaNWEhsabGFdXBrtfeLWGqBuzgfKpS8W5tV41NKE5GPtJDhZT5VcH5fqw6FuTKa2NGnkyUSrPgQREQrzpPnuWzRBoXHomGXuXZ7dNBxfFVaWUN4hQ2iEv9MMEE7BHym7tTWg1geVpeca3xmCrqhssvVejkwY7s4T8d7UrNwYJLATWwN5HcNq7H1RyL85FyVBHePTs7ooh1qXGRAbD8Au4PeY5S2Gk9L1yjFaFU2yuBPKWyPNrnoZDhMH9KZTXwNW37sDzo7wTN + response: + body: + string: '{"Error":""}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '12' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:22 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcdmFsaWRhdGVEaWRLZXk=?= + status: + code: 400 + message: Bad Request +version: 1 diff --git a/tests/cassettes/TestValidateTwoKeyDidWebIntegration.test_lists_ed25519_and_rsa_verification_methods.yaml b/tests/cassettes/TestValidateTwoKeyDidWebIntegration.test_lists_ed25519_and_rsa_verification_methods.yaml new file mode 100644 index 0000000..b354059 --- /dev/null +++ b/tests/cassettes/TestValidateTwoKeyDidWebIntegration.test_lists_ed25519_and_rsa_verification_methods.yaml @@ -0,0 +1,42 @@ +interactions: +- request: + body: '' + headers: + accept: + - '*/*' + accept-encoding: + - gzip, deflate, zstd + authorization: + - REDACTED + connection: + - keep-alive + host: + - localhost:44330 + user-agent: + - ce-cli/2026.11.30.13.dev0+gf2226fb1a.d20261202 + method: GET + uri: https://localhost:44330/iir-api/validateDidWeb?did=did%3Aweb%3Asandbox.credentialengine.org + response: + body: + string: '{"DidDocumentUrl":"https://sandbox.credentialengine.org/.well-known/did.json","VerificationMethodIds":["did:web:sandbox.credentialengine.org#z6MkwYGVFm6oFReLYwoHLobjVV5PBjnaYwB9VvJahn4nAx4f","did:web:sandbox.credentialengine.org#key-1"]}' + headers: + access-control-expose-headers: + - Request-Context + content-length: + - '237' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 02 Dec 2026 01:34:22 GMT + request-context: + - appId=cid-v1:3de5a21a-3b87-4008-b83b-c667a37cd396 + server: + - Microsoft-IIS/10.0 + x-powered-by: + - ASP.NET + x-sourcefiles: + - =?UTF-8?B?QzpcVXNlcnNcU25laGFFZHVsYVxzb3VyY2VccmVwb3NcQ3JlZGVudGlhbEVuZ2luZVxQdWJsaXNoZXJcRGlyZWN0b3J5XGlpci1hcGlcdmFsaWRhdGVEaWRXZWI=?= + status: + code: 200 + message: OK +version: 1 diff --git a/tests/test_did_ops_unit.py b/tests/test_did_ops_unit.py index b1e411a..34b63c3 100644 --- a/tests/test_did_ops_unit.py +++ b/tests/test_did_ops_unit.py @@ -18,9 +18,11 @@ pytestmark = pytest.mark.unit +from ce.iir import did_ops from ce.iir.api.iir_client.types import UNSET from ce.iir.did_ops import ( IIR_TASK, + SUPPORTED_ALGORITHMS, _client, _did_web_to_url, _extract_ed25519_pub_from_did_key, @@ -40,6 +42,7 @@ extract_user_id_from_token, merge_autofill, sign_proof_jwt, + validate_algorithm, validate_ctid, validate_date, validate_date_range, @@ -59,6 +62,44 @@ ED25519_KID = f"{ED25519_DID_KEY}#{ED25519_DID_KEY[len('did:key:') :]}" +def _uvarint(value: int) -> bytes: + out = bytearray() + while True: + byte = value & 0x7F + value >>= 7 + if value: + out.append(byte | 0x80) + else: + out.append(byte) + return bytes(out) + + +def _did_key_for(codec: int, key_bytes: bytes) -> str: + import base58 + + return "did:key:z" + base58.b58encode(_uvarint(codec) + key_bytes).decode() + + +@pytest.fixture(scope="session") +def rsa_did_key(): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import rsa + + public_key = rsa.generate_private_key( + public_exponent=65537, key_size=2048 + ).public_key() + der = public_key.public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.PKCS1, + ) + return _did_key_for(0x1205, der) + + +@pytest.fixture +def rsa_did_key_enabled(monkeypatch): + monkeypatch.setattr("ce.iir.did_ops.RSA_DID_KEY_ENABLED", True) + + def _fake_response(status_code: int, parsed=None) -> SimpleNamespace: return SimpleNamespace(status_code=status_code, parsed=parsed) @@ -259,30 +300,110 @@ def test_empty_did_returns_unknown(self): assert "empty" in err.lower() +class TestValidateAlgorithm: + def test_supported_algorithms_are_ed25519_and_rs256(self): + assert SUPPORTED_ALGORITHMS == {"Ed25519", "RS256"} + + @pytest.mark.parametrize("algorithm", ["Ed25519", "RS256"]) + def test_supported_algorithm_passes(self, algorithm): + ok, err = validate_algorithm(algorithm) + assert ok and err == "" + + def test_missing_algorithm_fails(self): + ok, err = validate_algorithm("") + assert not ok + assert "required" in err + assert "Ed25519, RS256" in err + + @pytest.mark.parametrize( + "algorithm", + ["RSA", "rs256", "ed25519", "P-256", "secp256k1", "X25519", "HS256"], + ) + def test_unsupported_algorithm_fails(self, algorithm): + ok, err = validate_algorithm(algorithm) + assert not ok + assert "unsupported" in err + assert f"'{algorithm}'" in err + + class TestValidateDidKeyPrefix: - def test_ed25519_prefix_matches_algorithm(self): - ok, _ = validate_did_key_prefix("did:key:z6MkhaXgBZ", "Ed25519") - assert ok + def test_ed25519_did_key_matches_ed25519(self): + ok, err = validate_did_key_prefix(ED25519_DID_KEY, "Ed25519") + assert ok and err == "" - def test_prefix_algorithm_mismatch_fails(self): - ok, err = validate_did_key_prefix("did:key:z6MkhaXgBZ", "P-256") + def test_ed25519_did_key_with_fragment_matches(self): + ok, err = validate_did_key_prefix(ED25519_KID, "Ed25519") + assert ok and err == "" + + def test_rsa_did_key_is_hidden_by_default(self): + assert did_ops.RSA_DID_KEY_ENABLED is False + + @pytest.mark.parametrize("algorithm", ["RS256", "Ed25519"]) + def test_rsa_did_key_is_rejected_while_hidden(self, rsa_did_key, algorithm): + ok, err = validate_did_key_prefix(rsa_did_key, algorithm) + assert not ok + assert ( + err + == "RS256 is supported for did:web only for now. RSA did:key is not supported yet." + ) + + @pytest.mark.usefixtures("rsa_did_key_enabled") + def test_rsa_did_key_matches_rs256(self, rsa_did_key): + assert rsa_did_key.startswith("did:key:z4MX") + ok, err = validate_did_key_prefix(rsa_did_key, "RS256") + assert ok and err == "" + + def test_ed25519_did_key_declared_rs256_is_mismatch(self): + ok, err = validate_did_key_prefix(ED25519_DID_KEY, "RS256") + assert not ok + assert "mismatch" in err + assert "Ed25519 key" in err + + @pytest.mark.usefixtures("rsa_did_key_enabled") + def test_rsa_did_key_declared_ed25519_is_mismatch(self, rsa_did_key): + ok, err = validate_did_key_prefix(rsa_did_key, "Ed25519") assert not ok assert "mismatch" in err + assert "RSA key (use RS256)" in err def test_unsupported_algorithm_fails(self): - ok, err = validate_did_key_prefix("did:key:z6MkhaXgBZ", "RSA") + ok, err = validate_did_key_prefix(ED25519_DID_KEY, "RSA") assert not ok - assert "unsupported" in err + assert "unsupported algorithm" in err def test_missing_algorithm_fails(self): - ok, err = validate_did_key_prefix("did:key:z6MkhaXgBZ", "") + ok, err = validate_did_key_prefix(ED25519_DID_KEY, "") assert not ok assert "required" in err - def test_unrecognised_key_prefix_fails(self): - ok, err = validate_did_key_prefix("did:key:zXXXunknown", "Ed25519") + @pytest.mark.parametrize( + "codec,size,name", + [ + (0x1200, 33, "P-256"), + (0xE7, 33, "secp256k1"), + (0xEC, 32, "X25519"), + ], + ) + def test_unsupported_key_type_fails(self, codec, size, name): + did = _did_key_for(codec, b"\x02" * size) + ok, err = validate_did_key_prefix(did, "Ed25519") + assert not ok, name + assert f"multicodec 0x{codec:X}" in err + + def test_invalid_base58_fails(self): + ok, err = validate_did_key_prefix("did:key:z0OIl", "Ed25519") assert not ok - assert "unrecognised" in err + assert "invalid did:key encoding" in err + + def test_missing_multibase_prefix_fails(self): + ok, err = validate_did_key_prefix("did:key:6MkhaXgBZ", "Ed25519") + assert not ok + assert "invalid did:key encoding" in err + + def test_empty_key_material_fails(self): + ok, err = validate_did_key_prefix("did:key:", "Ed25519") + assert not ok + assert "no key material" in err class TestValidateVerificationMethod: @@ -607,7 +728,41 @@ def test_did_key_with_bad_prefix_short_circuits(self): "did:key:zXXXunknown", "Ed25519", ACCESS_TOKEN, PUBLISHER_BASE, False ) assert not ok and vm_ids == [] - assert "unrecognised" in err.lower() + assert "unsupported did:key key type" in err + mock_sync.assert_not_called() + + def test_rsa_did_key_short_circuits_while_hidden(self, rsa_did_key): + with patch("ce.iir.did_ops.validate_did_key_sync") as mock_sync: + ok, vm_ids, _, err = call_validate_did( + rsa_did_key, "RS256", ACCESS_TOKEN, PUBLISHER_BASE, False + ) + assert not ok and vm_ids == [] + assert ( + err + == "RS256 is supported for did:web only for now. RSA did:key is not supported yet." + ) + mock_sync.assert_not_called() + + @pytest.mark.usefixtures("rsa_did_key_enabled") + def test_rsa_did_key_passes_rs256_to_api(self, rsa_did_key): + body = _ParsedObj(VerificationMethodIds=[rsa_did_key]) + with patch("ce.iir.did_ops.validate_did_key_sync") as mock_sync: + mock_sync.return_value = _fake_response(200, body) + ok, vm_ids, _, err = call_validate_did( + rsa_did_key, "RS256", ACCESS_TOKEN, PUBLISHER_BASE, False + ) + assert ok and err == "" + assert vm_ids == [rsa_did_key] + assert mock_sync.call_args.kwargs["alg"] == "RS256" + + @pytest.mark.usefixtures("rsa_did_key_enabled") + def test_rsa_did_key_declared_ed25519_short_circuits(self, rsa_did_key): + with patch("ce.iir.did_ops.validate_did_key_sync") as mock_sync: + ok, vm_ids, _, err = call_validate_did( + rsa_did_key, "Ed25519", ACCESS_TOKEN, PUBLISHER_BASE, False + ) + assert not ok and vm_ids == [] + assert "mismatch" in err mock_sync.assert_not_called() def test_missing_vm_ids_returns_empty_list_not_none(self): diff --git a/tests/test_iir_challenge_sign.py b/tests/test_iir_challenge_sign.py index 953f8e5..82c9e69 100644 --- a/tests/test_iir_challenge_sign.py +++ b/tests/test_iir_challenge_sign.py @@ -221,6 +221,12 @@ def test_rsa_pem_text_gets_hint(self, rsa_pem_text, ed25519_keys, tmp_path): assert "--algorithm RS256" in output +@pytest.fixture +def rsa_did_key_enabled(monkeypatch): + monkeypatch.setattr("ce.iir.did_ops.RSA_DID_KEY_ENABLED", True) + + +@pytest.mark.usefixtures("rsa_did_key_enabled") class TestRs256: def test_pem_file_did_key(self, rsa_pem_file, rsa_kid, tmp_path): out_path = tmp_path / "signed.jwt" @@ -354,6 +360,78 @@ def test_missing_required_field(self, rsa_pem_file, rsa_kid, tmp_path): assert "exp" in output +class TestRsaDidKeyHidden: + def test_rs256_with_rsa_did_key_is_rejected(self, rsa_pem_file, rsa_kid, tmp_path): + with patch(f"{RS256_MODULE}.sign_and_verify") as sign: + code, output = _run( + [ + "--algorithm", + "RS256", + "--private-key", + str(rsa_pem_file), + "--challenge-file", + str(_write_challenge(tmp_path, rsa_kid)), + ] + ) + + assert code != 0 + assert ( + "RS256 is supported for did:web only for now. RSA did:key is not supported yet." + in output + ) + sign.assert_not_called() + + def test_rs256_with_ed25519_did_key_is_rejected( + self, rsa_pem_file, ed25519_keys, tmp_path + ): + _, ed_kid = ed25519_keys + code, output = _run( + [ + "--algorithm", + "RS256", + "--private-key", + str(rsa_pem_file), + "--challenge-file", + str(_write_challenge(tmp_path, ed_kid)), + ] + ) + + assert code != 0 + assert "did:web only for now" in output + + def test_rs256_with_did_web_is_not_blocked(self, rsa_pem_file, tmp_path): + with patch(f"{RS256_MODULE}.sign_and_verify", return_value="a.b.c") as sign: + code, output = _run( + [ + "--algorithm", + "RS256", + "--private-key", + str(rsa_pem_file), + "--challenge-file", + str(_write_challenge(tmp_path, DID_WEB_KID)), + ] + ) + + assert code == 0, output + assert sign.call_args.args[1] == DID_WEB_KID + + def test_ed25519_did_key_still_signs(self, ed25519_keys, tmp_path): + seed, ed_kid = ed25519_keys + code, output = _run( + [ + "--algorithm", + "Ed25519", + "--private-key", + seed, + "--challenge-file", + str(_write_challenge(tmp_path, ed_kid)), + ] + ) + + assert code == 0, output + assert _decode_segment(output.strip().splitlines()[-1], 0)["alg"] == "EdDSA" + + class TestRegistration: def test_registered_as_iir_challenge_sign(self): from ce.commands.iir import challenge_group diff --git a/tests/test_iir_csv_processor.py b/tests/test_iir_csv_processor.py index e9ec93b..7f6d342 100644 --- a/tests/test_iir_csv_processor.py +++ b/tests/test_iir_csv_processor.py @@ -4,15 +4,24 @@ from types import SimpleNamespace from unittest.mock import Mock +import base58 +import click import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from ce.iir import csv_processor as processor CTID = "ce-12345678-1234-1234-1234-123456789abc" DID = "did:web:example.org" VM = DID + "#key" +ED25519_VM = DID + "#key-1" +RSA_VM = DID + "#key-2" ENV = SimpleNamespace(publisher_base="https://api.example", ssl_verify=True) +REAL_SIGN_CHALLENGE = processor.sign_challenge + pytestmark = pytest.mark.unit @@ -25,23 +34,57 @@ def write_rows(path, rows): def read_rows(path): - with path.open(newline="", encoding="utf-8") as stream: + with path.open(newline="", encoding="utf-8-sig") as stream: return list(csv.DictReader(stream)) +def input_row(**overrides): + row = { + "CTID": CTID, + "DID": DID, + "VerificationMethod": VM, + "Algorithm": "Ed25519", + "PrivateKey": "fixture", + "ValidFrom": "01/01/2026", + "ValidUntil": "01/01/2027", + } + row.update(overrides) + return row + + +def run_generate(tmp_path, rows): + source, signed, errors = [ + tmp_path / name for name in ("input.csv", "signed.csv", "errors.csv") + ] + write_rows(source, rows) + counts = processor.run_generate( + str(source), str(signed), str(errors), "fixture", ENV, "user" + ) + return counts, read_rows(signed), read_rows(errors) + + +def challenges_for(vm_ids, token, base, ssl_verify): + del token, base, ssl_verify + return True, [{"did": vm, "challenge": f"challenge-for-{vm}"} for vm in vm_ids], "" + + @pytest.fixture def operations(monkeypatch): values = { "call_is_user_member": (True, ""), "call_get_registry_resource": (True, {"Name": "Example"}, ""), - "call_validate_did_web": (True, {"verificationMethodIds": [VM]}, ""), + "call_validate_did_key": (True, {"verificationMethodIds": []}, ""), + "call_validate_did_web": ( + True, + {"verificationMethodIds": [VM, ED25519_VM, RSA_VM]}, + "", + ), "call_create_challenges": ( True, [{"did": VM, "challenge": "example-challenge"}], "", ), - "sign_proof_jwt": "fixture-proof", - "verify_proof_jwt": (True, ""), + "sign_challenge": "fixture-proof", "call_verify_jwt_signature": (True, ""), "call_save_challenge_token": (True, ""), "call_get_organization_iir_detail": (True, {"LegalName": "Example Legal"}, ""), @@ -62,47 +105,83 @@ def operations(monkeypatch): ("call_validate_did_web", (False, {}, "invalid DID")), ("call_create_challenges", (False, [], "challenge failure")), ("call_create_challenges", (True, [], "")), - ("verify_proof_jwt", (False, "verification failed")), - ("sign_proof_jwt", ValueError("bad key")), + ("sign_challenge", click.ClickException("DID resolution error: no match")), + ("sign_challenge", ValueError("bad key")), ], ) def test_generate_rows(tmp_path, operations, failure, result): - source, signed, errors = [ - tmp_path / name for name in ("input.csv", "signed.csv", "errors.csv") - ] - write_rows( - source, - [ - { - "CTID": CTID, - "DID": DID, - "VerificationMethod": VM, - "Algorithm": "Ed25519", - "PrivateKey": "fixture", - "ValidFrom": "01/01/2026", - "ValidUntil": "01/01/2027", - } - ], - ) if failure: if isinstance(result, Exception): operations[failure].side_effect = result else: operations[failure].return_value = result - counts = processor.run_generate( - str(source), str(signed), str(errors), "fixture", ENV, "user" - ) + counts, signed, errors = run_generate(tmp_path, [input_row()]) if failure: assert counts == (0, 1) - assert not read_rows(signed) - assert read_rows(errors)[0]["Error"] + assert not signed + assert errors[0]["Error"] + assert errors[0]["Algorithm"] == "Ed25519" else: assert counts == (1, 0) - assert not read_rows(errors) - row = read_rows(signed)[0] + assert not errors + row = signed[0] assert row["ProofJWT"] == "fixture-proof" assert row["ValidFrom"] == "2026-01-01T00:00:00Z" assert row["Challenge"] == "example-challenge" + assert row["Algorithm"] == "Ed25519" + + +def test_signing_click_error_message_is_written_to_errors_csv(tmp_path, operations): + operations["sign_challenge"].side_effect = click.ClickException( + "DID resolution error: no match" + ) + _, _, errors = run_generate(tmp_path, [input_row()]) + assert errors[0]["Error"] == "JWT signing failed: DID resolution error: no match" + + +@pytest.mark.parametrize("algorithm", ["Ed25519", "RS256"]) +def test_generate_passes_algorithm_and_csv_folder_to_signer( + tmp_path, operations, algorithm +): + counts, signed, _ = run_generate( + tmp_path, [input_row(Algorithm=algorithm, PrivateKey="keys/key.pem")] + ) + assert counts == (1, 0) + assert signed[0]["Algorithm"] == algorithm + + args = operations["sign_challenge"].call_args.args + assert args[0] == algorithm + assert args[1] == "keys/key.pem" + assert args[2] == VM + assert args[3]["challenge"] == "example-challenge" + assert args[3]["ctid"] == CTID + assert args[4] == tmp_path + + +def test_did_web_with_ed25519_and_rsa_keys_signs_each_row_with_its_algorithm( + tmp_path, operations +): + operations["call_create_challenges"].side_effect = lambda ctid, vm_ids, *rest: ( + challenges_for(vm_ids, *rest) + ) + counts, signed, errors = run_generate( + tmp_path, + [ + input_row(VerificationMethod=ED25519_VM, Algorithm="Ed25519"), + input_row(VerificationMethod=RSA_VM, Algorithm="RS256"), + ], + ) + assert counts == (2, 0) + assert not errors + assert [(r["VerificationMethod"], r["Algorithm"]) for r in signed] == [ + (ED25519_VM, "Ed25519"), + (RSA_VM, "RS256"), + ] + calls = [c.args[:3] for c in operations["sign_challenge"].call_args_list] + assert calls == [ + ("Ed25519", "fixture", ED25519_VM), + ("RS256", "fixture", RSA_VM), + ] @pytest.mark.parametrize( @@ -113,27 +192,372 @@ def test_generate_rows(tmp_path, operations, failure, result): ("DID", "invalid"), ("VerificationMethod", ""), ("PrivateKey", ""), + ("Algorithm", ""), + ("Algorithm", "RSA"), + ("Algorithm", "secp256k1"), ], ) def test_invalid_input_row(tmp_path, operations, field, value): - source, signed, errors = [ - tmp_path / name for name in ("input.csv", "signed.csv", "errors.csv") - ] - row = { - "CTID": CTID, - "DID": DID, - "VerificationMethod": VM, - "PrivateKey": "fixture", - "ValidFrom": "", - } + row = input_row(ValidFrom="", ValidUntil="") row[field] = value - write_rows(source, [row]) - assert processor.run_generate( - str(source), str(signed), str(errors), "fixture", ENV, "user" - ) == (0, 1) - assert read_rows(errors)[0]["Error"] - operations["sign_proof_jwt"].assert_not_called() + counts, _, errors = run_generate(tmp_path, [row]) + assert counts == (0, 1) + assert errors[0]["Error"] + operations["sign_challenge"].assert_not_called() + + +@pytest.mark.parametrize("value", ["", "RSA"]) +def test_algorithm_is_checked_before_any_api_call(tmp_path, operations, value): + _, _, errors = run_generate(tmp_path, [input_row(Algorithm=value)]) + assert "Ed25519, RS256" in errors[0]["Error"] + operations["call_is_user_member"].assert_not_called() + operations["call_validate_did_web"].assert_not_called() + + +def test_csv_files_are_written_as_utf8_with_bom(tmp_path, operations): + failing = tmp_path / "failing" + failing.mkdir() + run_generate(failing, [input_row(Algorithm="")]) + + errors_bytes = (failing / "errors.csv").read_bytes() + assert errors_bytes.startswith(b"\xef\xbb\xbf") + assert "Algorithm is required \u2014 must be one of" in errors_bytes.decode( + "utf-8-sig" + ) + + passing = tmp_path / "passing" + passing.mkdir() + run_generate(passing, [input_row()]) + assert (passing / "signed.csv").read_bytes().startswith(b"\xef\xbb\xbf") + + +def test_publish_errors_csv_is_written_as_utf8_with_bom(tmp_path, operations): + signed, errors = tmp_path / "signed.csv", tmp_path / "errors.csv" + write_rows( + signed, + [ + { + "CTID": CTID, + "DID": DID, + "VerificationMethod": VM, + "Challenge": "example-challenge", + "ProofJWT": "fixture-proof", + } + ], + ) + operations["call_verify_jwt_signature"].return_value = (False, "bad \u2014 proof") + processor.run_upload(str(signed), str(errors), "fixture", ENV, yes=True) + errors_bytes = errors.read_bytes() + assert errors_bytes.startswith(b"\xef\xbb\xbf") + assert "bad \u2014 proof" in errors_bytes.decode("utf-8-sig") + + +def test_did_web_row_without_algorithm_column_fails(tmp_path, operations): + row = input_row() + del row["Algorithm"] + counts, _, errors = run_generate(tmp_path, [row]) + assert counts == (0, 1) + assert "Algorithm is required" in errors[0]["Error"] + + +PEM_TEXT = "-----BEGIN PRIVATE KEY-----\nMIIE\n-----END PRIVATE KEY-----" + + +class TestResolvePrivateKey: + def test_rs256_relative_path_is_read_from_csv_folder(self, tmp_path, monkeypatch): + csv_folder = tmp_path / "batch" + (csv_folder / "keys").mkdir(parents=True) + key_file = csv_folder / "keys" / "rsa.pem" + key_file.write_text("pem", encoding="utf-8") + monkeypatch.chdir(tmp_path) + + resolved = processor.resolve_private_key("RS256", "keys/rsa.pem", csv_folder) + assert resolved == str(key_file) + + def test_rs256_absolute_path_is_kept(self, tmp_path): + key_file = tmp_path / "rsa.pem" + key_file.write_text("pem", encoding="utf-8") + resolved = processor.resolve_private_key( + "RS256", str(key_file), tmp_path / "other" + ) + assert resolved == str(key_file) + + def test_rs256_path_not_in_csv_folder_is_passed_on(self, tmp_path): + resolved = processor.resolve_private_key("RS256", "missing.pem", tmp_path) + assert resolved == "missing.pem" + + @pytest.mark.parametrize( + "value", + [PEM_TEXT, "-----BEGIN PRIVATE KEY-----\\nMIIE\\n-----END PRIVATE KEY-----"], + ) + def test_rs256_pem_text_is_unchanged(self, tmp_path, value): + assert processor.resolve_private_key("RS256", value, tmp_path) == value + + def test_ed25519_value_is_unchanged(self, tmp_path): + (tmp_path / "zSeed").write_text("x", encoding="utf-8") + assert processor.resolve_private_key("Ed25519", "zSeed", tmp_path) == "zSeed" + +class TestSignChallenge: + @pytest.fixture + def signers(self, monkeypatch): + ed = Mock(return_value="ed-jwt") + rs = Mock(return_value="rs-jwt") + monkeypatch.setattr(processor._ed25519, "sign_and_verify", ed) + monkeypatch.setattr(processor._rs256, "sign_and_verify", rs) + return SimpleNamespace(ed=ed, rs=rs) + + def test_ed25519_uses_ed25519_implementation(self, tmp_path, signers): + payload = {"did": VM} + token = processor.sign_challenge("Ed25519", "zSeed", VM, payload, tmp_path) + assert token == "ed-jwt" + signers.ed.assert_called_once_with("zSeed", VM, payload) + signers.rs.assert_not_called() + + def test_rs256_uses_rs256_implementation_with_resolved_path( + self, tmp_path, signers + ): + key_file = tmp_path / "rsa.pem" + key_file.write_text("pem", encoding="utf-8") + payload = {"did": VM} + token = processor.sign_challenge("RS256", "rsa.pem", VM, payload, tmp_path) + assert token == "rs-jwt" + signers.rs.assert_called_once_with(str(key_file), VM, payload) + signers.ed.assert_not_called() + + @pytest.mark.parametrize("value", [PEM_TEXT, "abc\\ndef"]) + def test_ed25519_with_pem_key_is_rejected(self, tmp_path, signers, value): + with pytest.raises(click.ClickException, match="Use RS256"): + processor.sign_challenge("Ed25519", value, VM, {}, tmp_path) + signers.ed.assert_not_called() + + +def _uvarint(value): + out = bytearray() + while True: + byte = value & 0x7F + value >>= 7 + if value: + out.append(byte | 0x80) + else: + out.append(byte) + return bytes(out) + + +def _did_key(codec, key_bytes): + return "did:key:z" + base58.b58encode(_uvarint(codec) + key_bytes).decode() + + +def _vm_for(did_key): + return f"{did_key}#{did_key[len('did:key:') :]}" + + +@pytest.fixture +def ed25519_identity(): + 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, + ) + private_multibase = "z" + base58.b58encode(_uvarint(0x1300) + seed).decode() + return private_multibase, _did_key(0xED, pub) + + +@pytest.fixture +def rsa_identity(tmp_path): + """RSA 2048 key written next to the CSV, plus its did:key (0x1205 + PKCS#1).""" + sk = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pem = sk.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + (tmp_path / "rsa-private-key.pem").write_bytes(pem) + der = sk.public_key().public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.PKCS1, + ) + return "rsa-private-key.pem", _did_key(0x1205, der), pem.decode() + + +@pytest.fixture +def rsa_did_key_enabled(monkeypatch): + """Turn RS256 did:key back on to test the code kept for re-enabling it.""" + monkeypatch.setattr("ce.iir.did_ops.RSA_DID_KEY_ENABLED", True) + + +@pytest.fixture +def real_signing(operations, monkeypatch): + """Use the real sign_challenge; challenges are created for the row's VM.""" + monkeypatch.setattr(processor, "sign_challenge", REAL_SIGN_CHALLENGE) + operations["call_create_challenges"].side_effect = lambda ctid, vm_ids, *rest: ( + challenges_for(vm_ids, *rest) + ) + return operations + + +def _jwt_header(token): + import base64 + import json + + part = token.split(".")[0] + return json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))) + + +def test_rs256_did_key_row_is_rejected_while_hidden( + tmp_path, real_signing, rsa_identity +): + rsa_key_path, rsa_did, _ = rsa_identity + counts, signed, errors = run_generate( + tmp_path, + [ + input_row( + DID=rsa_did, + VerificationMethod=_vm_for(rsa_did), + Algorithm="RS256", + PrivateKey=rsa_key_path, + ) + ], + ) + assert counts == (0, 1) + assert not signed + assert ( + errors[0]["Error"] + == "RS256 is supported for did:web only for now. RSA did:key is not supported yet." + ) + assert errors[0]["Algorithm"] == "RS256" + real_signing["call_validate_did_key"].assert_not_called() + real_signing["call_create_challenges"].assert_not_called() + + +def test_ed25519_did_key_still_signs_while_rsa_did_key_hidden( + tmp_path, real_signing, ed25519_identity +): + ed_key, ed_did = ed25519_identity + counts, signed, errors = run_generate( + tmp_path, + [ + input_row( + DID=ed_did, + VerificationMethod=_vm_for(ed_did), + Algorithm="Ed25519", + PrivateKey=ed_key, + ) + ], + ) + assert errors == [] + assert counts == (1, 0) + assert _jwt_header(signed[0]["ProofJWT"])["alg"] == "EdDSA" + + +@pytest.mark.usefixtures("rsa_did_key_enabled") +def test_real_signing_ed25519_and_rs256_did_keys( + tmp_path, real_signing, ed25519_identity, rsa_identity +): + ed_key, ed_did = ed25519_identity + rsa_key_path, rsa_did, _ = rsa_identity + counts, signed, errors = run_generate( + tmp_path, + [ + input_row( + DID=ed_did, + VerificationMethod=_vm_for(ed_did), + Algorithm="Ed25519", + PrivateKey=ed_key, + ), + input_row( + DID=rsa_did, + VerificationMethod=_vm_for(rsa_did), + Algorithm="RS256", + PrivateKey=rsa_key_path, + ), + ], + ) + assert errors == [] + assert counts == (2, 0) + + ed_row, rsa_row = signed + assert _jwt_header(ed_row["ProofJWT"])["alg"] == "EdDSA" + assert _jwt_header(rsa_row["ProofJWT"])["alg"] == "RS256" + assert _jwt_header(rsa_row["ProofJWT"])["kid"] == _vm_for(rsa_did) + assert rsa_row["Algorithm"] == "RS256" + + +@pytest.mark.usefixtures("rsa_did_key_enabled") +def test_real_signing_rs256_with_literal_newline_pem_in_csv( + tmp_path, real_signing, rsa_identity +): + _, rsa_did, pem = rsa_identity + counts, signed, errors = run_generate( + tmp_path, + [ + input_row( + DID=rsa_did, + VerificationMethod=_vm_for(rsa_did), + Algorithm="RS256", + PrivateKey=pem.strip().replace("\n", "\\n"), + ) + ], + ) + assert errors == [] + assert counts == (1, 0) + assert _jwt_header(signed[0]["ProofJWT"])["alg"] == "RS256" + + +@pytest.mark.usefixtures("rsa_did_key_enabled") +def test_real_signing_rsa_did_key_declared_ed25519_fails_before_signing( + tmp_path, real_signing, rsa_identity +): + rsa_key_path, rsa_did, _ = rsa_identity + counts, _, errors = run_generate( + tmp_path, + [ + input_row( + DID=rsa_did, + VerificationMethod=_vm_for(rsa_did), + Algorithm="Ed25519", + PrivateKey=rsa_key_path, + ) + ], + ) + assert counts == (0, 1) + assert "mismatch" in errors[0]["Error"] + real_signing["call_create_challenges"].assert_not_called() + + +@pytest.mark.usefixtures("rsa_did_key_enabled") +def test_real_signing_wrong_rsa_key_fails_verification( + tmp_path, real_signing, rsa_identity +): + _, rsa_did, _ = rsa_identity + other = rsa.generate_private_key(public_exponent=65537, key_size=2048) + (tmp_path / "other.pem").write_bytes( + other.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + counts, signed, errors = run_generate( + tmp_path, + [ + input_row( + DID=rsa_did, + VerificationMethod=_vm_for(rsa_did), + Algorithm="RS256", + PrivateKey="other.pem", + ) + ], + ) + assert counts == (0, 1) + assert not signed + assert errors[0]["Error"].startswith("JWT signing failed:") + assert errors[0]["Algorithm"] == "RS256" @pytest.mark.parametrize( "failure,result", @@ -170,10 +594,74 @@ def test_publish_rows(tmp_path, operations, failure, result): assert operations["call_submit_to_iir"].call_args.args[2] == "Example" else: assert len(rows) == 1 and rows[0]["Error"] + assert rows[0]["Algorithm"] == "" if failure != "call_submit_to_iir": operations["call_submit_to_iir"].assert_not_called() +@pytest.mark.parametrize("algorithm", ["Ed25519", "RS256"]) +def test_publish_sends_jwt_for_either_algorithm(tmp_path, operations, algorithm): + signed, errors = tmp_path / "signed.csv", tmp_path / "errors.csv" + write_rows( + signed, + [ + { + "CTID": CTID, + "DID": DID, + "VerificationMethod": RSA_VM, + "Algorithm": algorithm, + "Challenge": "example-challenge", + "ProofJWT": f"{algorithm}-proof", + } + ], + ) + processor.run_upload(str(signed), str(errors), "fixture", ENV, yes=True) + assert not read_rows(errors) + assert operations["call_verify_jwt_signature"].call_args.args[:2] == ( + f"{algorithm}-proof", + "example-challenge", + ) + operations["call_submit_to_iir"].assert_called_once() + + +def test_publish_error_row_keeps_algorithm(tmp_path, operations): + signed, errors = tmp_path / "signed.csv", tmp_path / "errors.csv" + write_rows( + signed, + [ + { + "CTID": CTID, + "DID": DID, + "VerificationMethod": RSA_VM, + "Algorithm": "RS256", + "Challenge": "example-challenge", + "ProofJWT": "rs-proof", + } + ], + ) + operations["call_verify_jwt_signature"].return_value = ( + False, + "JWT validation failed", + ) + processor.run_upload(str(signed), str(errors), "fixture", ENV, yes=True) + rows = read_rows(errors) + assert rows[0]["Algorithm"] == "RS256" + assert rows[0]["Error"] == "JWT validation failed" + + +def test_bulk_sign_output_feeds_publish(tmp_path, operations): + counts, _, _ = run_generate( + tmp_path, [input_row(VerificationMethod=VM, Algorithm="RS256")] + ) + assert counts == (1, 0) + publish_errors = tmp_path / "publish-errors.csv" + processor.run_upload( + str(tmp_path / "signed.csv"), str(publish_errors), "fixture", ENV, yes=True + ) + assert not read_rows(publish_errors) + operations["call_submit_to_iir"].assert_called_once() + + def test_missing_and_empty_input(tmp_path, operations): source, signed, errors = [ tmp_path / name for name in ("input.csv", "signed.csv", "errors.csv") diff --git a/tests/test_iir_signing_integration.py b/tests/test_iir_signing_integration.py new file mode 100644 index 0000000..6b46853 --- /dev/null +++ b/tests/test_iir_signing_integration.py @@ -0,0 +1,392 @@ +from __future__ import annotations + +import base64 +import json +import os +from pathlib import Path +from types import SimpleNamespace +from urllib.parse import parse_qs, urlsplit + +import base58 +import jwt +import pytest +import yaml +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from dotenv import load_dotenv + +from ce.iir.did_ops import ( + call_create_challenges, + call_save_challenge_token, + call_validate_did_key, + call_validate_did_web, + call_verify_jwt_signature, +) +from ce.implementations import iir_challenge_sign_ed25519 as _ed25519 +from ce.implementations import iir_challenge_sign_rs256 as _rs256 + +pytestmark = [pytest.mark.integration, pytest.mark.vcr] + +CASSETTE_DIR = Path(__file__).parent / "cassettes" +# Key ids that make_test_did_web.py writes; other DIDs set CE_TEST_WEB_*_VM. +DEFAULT_ED25519_FRAGMENT = "#key-1" +DEFAULT_RSA_FRAGMENT = "#key-2" + + +# --------------------------------------------------------------------------- +# Mode and configuration +# --------------------------------------------------------------------------- + + +def _is_playback(request) -> bool: + return (request.config.getoption("record_mode", default=None) or "none") == "none" + + +def _env(name: str) -> str: + value = os.environ.get(name, "").strip() + if value.casefold() == "to be filled to test": + return "" + return value + + +def _cassette_path(request) -> Path: + return CASSETTE_DIR / f"{request.node.cls.__name__}.{request.node.name}.yaml" + + +def _interactions(request) -> list[dict]: + path = _cassette_path(request) + return yaml.safe_load(path.read_text(encoding="utf-8"))["interactions"] + + +def _recorded_request(request, path_suffix: str) -> dict: + """The first recorded request whose path ends with path_suffix.""" + for interaction in _interactions(request): + recorded = interaction["request"] + if urlsplit(recorded["uri"]).path.endswith(path_suffix): + return recorded + pytest.fail( + f"No recorded request to {path_suffix} in {_cassette_path(request).name}" + ) + + +def _recorded_query(request, path_suffix: str, name: str) -> str: + query = parse_qs(urlsplit(_recorded_request(request, path_suffix)["uri"]).query) + return query[name][0] + + +def _recorded_jwt(request) -> str: + body = _recorded_request(request, "/validateJwt")["body"] + return parse_qs(body)["Jwt"][0] + + +@pytest.fixture +def live(request) -> SimpleNamespace: + """Settings for this test: from .env.test when recording, from the cassette in playback.""" + if _is_playback(request): + if not _cassette_path(request).exists(): + pytest.skip( + f"Not recorded yet: {_cassette_path(request).name}. " + "Record it with --record-mode=once." + ) + first_uri = urlsplit(_interactions(request)[0]["request"]["uri"]) + return SimpleNamespace( + playback=True, + base=f"{first_uri.scheme}://{first_uri.netloc}", + token="PLAYBACK_TOKEN", + ctid="ce-playback", + did_web="did:web:playback.invalid", + # Request bodies are not matched in playback, so these are placeholders. + ed25519_vm="did:web:playback.invalid#ed25519", + rsa_vm="did:web:playback.invalid#rsa", + ed25519_key="", + rsa_key_path="", + ) + + load_dotenv(Path(__file__).resolve().parents[1] / ".env.test") + required = ( + "CE_PUBLISHER_BASE", + "CE_TEST_ACCESS_TOKEN", + "CE_TEST_CTID", + "CE_TEST_DID_WEB", + ) + missing = [name for name in required if not _env(name)] + if missing: + pytest.skip("Missing live recording configuration: " + ", ".join(missing)) + + # The seed itself wins; otherwise read it from the key file. + ed25519_key = _env("CE_TEST_WEB_ED25519_PRIVKEY") + ed25519_path = _env("CE_TEST_WEB_ED25519_KEY_PATH") + if not ed25519_key and ed25519_path: + ed25519_key = Path(ed25519_path).read_text(encoding="ascii").strip() + + did_web = _env("CE_TEST_DID_WEB") + return SimpleNamespace( + playback=False, + base=_env("CE_PUBLISHER_BASE").rstrip("/"), + token=_env("CE_TEST_ACCESS_TOKEN"), + ctid=_env("CE_TEST_CTID"), + did_web=did_web, + ed25519_vm=_verification_method_id( + did_web, _env("CE_TEST_WEB_ED25519_VM"), DEFAULT_ED25519_FRAGMENT + ), + rsa_vm=_verification_method_id( + did_web, _env("CE_TEST_WEB_RSA_VM"), DEFAULT_RSA_FRAGMENT + ), + ed25519_key=ed25519_key, + rsa_key_path=_env("CE_TEST_WEB_RSA_KEY_PATH"), + ) + + +def _verification_method_id(did: str, value: str, default_fragment: str) -> str: + """A full verification method id from a full id, a "#fragment", or the default.""" + if not value: + return did + default_fragment + if value.startswith("#"): + return did + value + return value + + +def _require(value: str, name: str) -> None: + if not value: + pytest.skip(f"{name} is required to record this test") + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _get(challenge: dict, name: str): + """The publisher has used both PascalCase and camelCase over time.""" + return challenge.get(name) or challenge.get(name.lower()) + + +def _create_challenge(live: SimpleNamespace, vm_id: str) -> dict: + ok, challenges, err = call_create_challenges( + live.ctid, [vm_id], live.token, live.base, ssl_verify=False + ) + assert ok, f"createChallenges failed: {err}" + assert challenges, "createChallenges returned an empty list" + return challenges[0] + + +def _payload(live: SimpleNamespace, challenge: dict) -> dict: + return { + "did": _get(challenge, "Did"), + "challenge": _get(challenge, "Challenge"), + "aud": _get(challenge, "Aud"), + "iat": _get(challenge, "Iat"), + "exp": _get(challenge, "Exp"), + "ctid": live.ctid, + } + + +def _jwt_header(token: str) -> dict: + part = token.split(".")[0] + return json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))) + + +def _verify(live: SimpleNamespace, token: str, challenge: dict) -> tuple[bool, str]: + return call_verify_jwt_signature( + token, _get(challenge, "Challenge"), live.token, live.base, ssl_verify=False + ) + + +def _save(live: SimpleNamespace, token: str, challenge: dict) -> None: + ok, err = call_save_challenge_token( + live.ctid, + _get(challenge, "Challenge"), + token, + live.token, + live.base, + ssl_verify=False, + ) + assert ok, f"saveChallengeToken failed: {err}" + + +def _uvarint(value: int) -> bytes: + out = bytearray() + while True: + byte = value & 0x7F + value >>= 7 + if value: + out.append(byte | 0x80) + else: + out.append(byte) + return bytes(out) + + +def _rsa_did_key(private_key: rsa.RSAPrivateKey) -> str: + """did:key for an RSA key: multicodec 0x1205 + PKCS#1 RSAPublicKey DER.""" + der = private_key.public_key().public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.PKCS1, + ) + return "did:key:z" + base58.b58encode(_uvarint(0x1205) + der).decode() + + +def _new_rsa_key() -> rsa.RSAPrivateKey: + return rsa.generate_private_key(public_exponent=65537, key_size=2048) + + +def _sign_raw(private_key, algorithm: str, kid: str, payload: dict) -> str: + """Sign without the CLI's local checks, to send the API tokens it must reject.""" + return jwt.encode( + payload, private_key, algorithm=algorithm, headers={"kid": kid, "typ": "JWT"} + ) + + +# --------------------------------------------------------------------------- +# DID validation +# --------------------------------------------------------------------------- + + +class TestValidateTwoKeyDidWebIntegration: + def test_lists_ed25519_and_rsa_verification_methods(self, request, live): + did_web = live.did_web + if live.playback: + did_web = _recorded_query(request, "/validateDidWeb", "did") + + ok, data, err = call_validate_did_web( + did_web, live.token, live.base, ssl_verify=False + ) + assert ok, f"validateDidWeb failed: {err}" + + vm_ids = ( + data.get("verificationMethodIds") or data.get("VerificationMethodIds") or [] + ) + assert vm_ids, f"validateDidWeb returned no verification method ids: {data}" + if live.playback: + assert len(vm_ids) >= 2, f"Expected an Ed25519 and an RSA key: {vm_ids}" + else: + assert live.ed25519_vm in vm_ids, f"{live.ed25519_vm} not in {vm_ids}" + assert live.rsa_vm in vm_ids, f"{live.rsa_vm} not in {vm_ids}" + + +def _assert_rsa_did_key_rejected(request, live: SimpleNamespace, alg: str) -> None: + did_key = _rsa_did_key(_new_rsa_key()) + if live.playback: + did_key = _recorded_query(request, "/validateDidKey", "did") + + ok, _data, err = call_validate_did_key( + did_key, alg, live.token, live.base, ssl_verify=False + ) + assert not ok, "API accepted an RSA did:key; RS256 is did:web only for now" + print(f"validateDidKey({alg}) rejected as expected: {err}") + + +class TestValidateRsaDidKeyIntegration: + # One test per alg (not parametrized) so each gets a plain cassette name. + def test_rs256_did_key_is_rejected_while_hidden(self, request, live): + _assert_rsa_did_key_rejected(request, live, "RS256") + + def test_rsa_did_key_is_rejected_while_hidden(self, request, live): + _assert_rsa_did_key_rejected(request, live, "RSA") + + +# --------------------------------------------------------------------------- +# Full flows: create -> sign -> validateJwt -> saveChallengeToken +# --------------------------------------------------------------------------- + + +class TestEd25519DidWebFlowIntegration: + def test_sign_verify_save(self, request, live): + vm_id = live.ed25519_vm + if not live.playback: + _require( + live.ed25519_key, + "CE_TEST_WEB_ED25519_PRIVKEY or CE_TEST_WEB_ED25519_KEY_PATH", + ) + + challenge = _create_challenge(live, vm_id) + if live.playback: + token = _recorded_jwt(request) + else: + # Signs and checks the JWT against #key-1 in the live did.json. + token = _ed25519.sign_and_verify( + live.ed25519_key, vm_id, _payload(live, challenge) + ) + + assert _jwt_header(token)["alg"] == "EdDSA" + # The JWT is for the key the challenge was issued to (works in playback too). + assert _jwt_header(token)["kid"] == _get(challenge, "Did") + + ok, err = _verify(live, token, challenge) + assert ok, f"API rejected the Ed25519 did:web JWT: {err}" + _save(live, token, challenge) + + +class TestRs256DidWebFlowIntegration: + def test_sign_verify_save(self, request, live): + vm_id = live.rsa_vm + if not live.playback: + _require(live.rsa_key_path, "CE_TEST_WEB_RSA_KEY_PATH") + + challenge = _create_challenge(live, vm_id) + if live.playback: + token = _recorded_jwt(request) + else: + # Signs and checks the JWT against #key-2 in the live did.json. + token = _rs256.sign_and_verify( + live.rsa_key_path, vm_id, _payload(live, challenge) + ) + + assert _jwt_header(token)["alg"] == "RS256" + # The JWT is for the key the challenge was issued to (works in playback too). + assert _jwt_header(token)["kid"] == _get(challenge, "Did") + + ok, err = _verify(live, token, challenge) + assert ok, f"API rejected the RS256 did:web JWT: {err}" + _save(live, token, challenge) + + def test_wrong_rsa_key_is_rejected(self, request, live): + vm_id = live.rsa_vm + + challenge = _create_challenge(live, vm_id) + if live.playback: + token = _recorded_jwt(request) + else: + token = _sign_raw(_new_rsa_key(), "RS256", vm_id, _payload(live, challenge)) + + ok, err = _verify(live, token, challenge) + assert not ok, "API accepted an RS256 JWT signed with a key not in the DID" + print(f"Wrong RSA key rejected as expected: {err}") + + def test_eddsa_token_for_rsa_key_is_rejected(self, request, live): + vm_id = live.rsa_vm + + challenge = _create_challenge(live, vm_id) + if live.playback: + token = _recorded_jwt(request) + else: + token = _sign_raw( + Ed25519PrivateKey.generate(), "EdDSA", vm_id, _payload(live, challenge) + ) + + assert _jwt_header(token)["alg"] == "EdDSA" + ok, err = _verify(live, token, challenge) + assert not ok, "API accepted an EdDSA JWT for the RSA verification method" + print(f"EdDSA token for the RSA key rejected as expected: {err}") + + +class TestRs256DidKeyFlowIntegration: + def test_rsa_did_key_jwt_is_rejected_while_hidden(self, request, live): + # createChallenges does not check the DID, so the validator is what refuses it. + private_key = _new_rsa_key() + did_key = _rsa_did_key(private_key) + vm_id = f"{did_key}#{did_key[len('did:key:') :]}" + + challenge = _create_challenge(live, vm_id) + if live.playback: + token = _recorded_jwt(request) + else: + token = _sign_raw(private_key, "RS256", vm_id, _payload(live, challenge)) + + assert _jwt_header(token)["alg"] == "RS256" + assert _jwt_header(token)["kid"].startswith("did:key:") + ok, err = _verify(live, token, challenge) + assert not ok, ( + "API accepted an RS256 did:key JWT; RS256 is did:web only for now" + ) + print(f"RS256 did:key JWT rejected as expected: {err}") From 43678b93b5be6f1c5450485a3aeb5e6ba936055e Mon Sep 17 00:00:00 2001 From: Sneha Edula Date: Tue, 1 Dec 2026 20:54:25 -0500 Subject: [PATCH 2/2] ruff --- ce/iir/did_ops.py | 6 +++--- tests/test_iir_csv_processor.py | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/ce/iir/did_ops.py b/ce/iir/did_ops.py index 49b38e5..7ab70cf 100644 --- a/ce/iir/did_ops.py +++ b/ce/iir/did_ops.py @@ -209,11 +209,11 @@ def validate_did_key_prefix(did: str, algorithm: str) -> tuple[bool, str]: key_type, expected = entry if expected != algorithm: - return ( - False, + message = ( f"algorithm mismatch: did:key holds an {key_type} key (use {expected}) " - f"but CSV declares '{algorithm}'", + f"but CSV declares '{algorithm}'" ) + return False, message return True, "" diff --git a/tests/test_iir_csv_processor.py b/tests/test_iir_csv_processor.py index 7f6d342..110d015 100644 --- a/tests/test_iir_csv_processor.py +++ b/tests/test_iir_csv_processor.py @@ -559,6 +559,7 @@ def test_real_signing_wrong_rsa_key_fails_verification( assert errors[0]["Error"].startswith("JWT signing failed:") assert errors[0]["Algorithm"] == "RS256" + @pytest.mark.parametrize( "failure,result", [