Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions ce.code-workspace
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"extensions": {
"recommendations": [
"ms-python.python",
"ms-python.vscode-pylance",
"charliermarsh.ruff"
]
},
"folders": [
{
"path": "."
}
],
"settings": {
"[json]": {
"editor.codeActionsOnSave": {
"source.fixAll.sortJSON": "explicit"
},
"editor.defaultFormatter": "vscode.json-language-features",
"editor.detectIndentation": false,
"editor.formatOnSave": true,
"editor.insertSpaces": true,
"editor.tabSize": 4
},
"[jsonc]": {
"editor.codeActionsOnSave": {
"source.sort.json": "explicit"
},
"editor.defaultFormatter": "vscode.json-language-features",
"editor.detectIndentation": false,
"editor.formatOnSave": true,
"editor.insertSpaces": true,
"editor.tabSize": 4
},
"[python]": {
"editor.codeActionsOnSave": {
"source.fixAll.ruff": "explicit",
"source.organizeImports.ruff": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true,
"editor.insertSpaces": true,
"editor.tabSize": 4
},
"editor.detectIndentation": false,
"editor.insertSpaces": true,
"editor.rulers": [
80
],
"editor.tabSize": 4,
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"python.analysis.typeCheckingMode": "basic",
"python.terminal.activateEnvironment": true,
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false,
"ruff.enable": true,
"ruff.fixAll": true,
"ruff.organizeImports": true
}
}
6 changes: 3 additions & 3 deletions ce/commands/iir.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""IIR command group:

ce iir challenge sign # single challenge
ce iir challenge sign # single challenge (--algorithm Ed25519 | RS256)
ce iir challenge bulk-sign # bulk DID challenge signing
ce iir issuer-did publish # publish signed challenges to IIR
"""
Expand All @@ -13,7 +13,7 @@
import click
from rich.console import Console

from ce.commands.iir_sign_challenge import sign_individual_challenge
from ce.iir.challenge.sign import main as sign_command

from ce.auth.token_manager import require_login
from ce.config.context import require_environment
Expand Down Expand Up @@ -46,7 +46,7 @@ def issuer_did_group() -> None:

# ce iir challenge sign (single)

challenge_group.add_command(sign_individual_challenge, name="sign")
challenge_group.add_command(sign_command, name="sign")


# ce iir challenge bulk-sign
Expand Down
Empty file added ce/iir/challenge/__init__.py
Empty file.
159 changes: 159 additions & 0 deletions ce/iir/challenge/sign.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
"""ce iir challenge sign

ce iir challenge sign --algorithm Ed25519 --private-key zABC... \
--challenge-file challenge.json --output signed-challenge.jwt

ce iir challenge sign --algorithm RS256 --private-key rsa-key.pem \
--challenge-file challenge.json --output signed-challenge.jwt

Signs one CE challenge and produces a Proof JWT, then verifies it against the
public key resolved from the DID (did:key or did:web). No login required.
--algorithm picks the implementation:

Ed25519 alg=EdDSA, --private-key is a multibase seed (z...).
ce.implementations.iir_challenge_sign_ed25519
RS256 alg=RS256, --private-key is a PEM file path or the PEM text.
ce.implementations.iir_challenge_sign_rs256
"""

from __future__ import annotations

import json
from typing import Any, Dict

import click
from rich.console import Console

from ce.implementations import iir_challenge_sign_ed25519 as _ed25519
from ce.implementations import iir_challenge_sign_rs256 as _rs256

err_console = Console(stderr=True)

ALGORITHM_ED25519 = "Ed25519"
ALGORITHM_RS256 = "RS256"

REQUIRED_FIELDS = ["did", "challenge", "aud", "iat", "exp"]



# Input checks

def read_challenge(challenge_file: str) -> Dict[str, Any]:
"""Load the challenge JSON and check it has the fields a Proof JWT needs."""
try:
with open(challenge_file, "r", encoding="utf-8") as f:
payload_obj = json.load(f)
except json.JSONDecodeError as e:
raise click.ClickException(f"Challenge file is not valid JSON: {e}")

if not isinstance(payload_obj, dict):
raise click.ClickException("Challenge payload must be a JSON object.")

missing = [k for k in REQUIRED_FIELDS if k not in payload_obj]
if missing:
raise click.ClickException(
f"Challenge JSON missing required field(s): {', '.join(missing)}"
)

did_value = payload_obj.get("did")
if not isinstance(did_value, str) or not did_value.strip():
raise click.ClickException(
'Challenge JSON must include a non-empty string field "did".'
)

return payload_obj


def looks_like_rsa_key(value: str) -> bool:
"""True when an Ed25519 --private-key value looks like a PEM key or a key file path."""
if "-----BEGIN" in value or "\\n" in value:
return True
return _rs256.is_existing_file(value)



# Click command

@click.command(name="sign")
@click.option(
"--algorithm",
"algorithm",
required=True,
type=click.Choice([ALGORITHM_ED25519, ALGORITHM_RS256]),
help="Signing algorithm: Ed25519 (alg=EdDSA) or RS256 (RSA).",
)
@click.option(
"--private-key",
"private_key",
required=True,
metavar="KEY",
help=(
"Ed25519: private seed (multibase base58btc, starts with 'z'). "
"RS256: path to an unencrypted PEM/DER key file, or the PEM text."
),
)
@click.option(
"--challenge-file",
"challenge_file",
required=True,
type=click.Path(exists=True, dir_okay=False, readable=True),
metavar="PATH",
help="Path to CE-generated challenge JSON file.",
)
@click.option(
"--output", "-o",
"out_path",
default=None,
type=click.Path(dir_okay=False, writable=True),
metavar="PATH",
help="Write JWT to this file (otherwise printed to stdout).",
)
def main(
algorithm: str,
private_key: str,
challenge_file: str,
out_path: str | None,
) -> None:
"""Sign a single CE challenge JSON file and produce a Proof JWT.

\b
--algorithm Ed25519 : --private-key is the multibase seed (z...).
--algorithm RS256 : --private-key is a PEM file path or the PEM text.
The challenge JSON must include: did, challenge, aud, iat, exp.
Signature verification uses did:key (offline) or did:web (HTTPS).

\b
Examples:
ce iir challenge sign --algorithm Ed25519 \\
--private-key zABC... \\
--challenge-file challenge.json \\
--output signed-challenge.jwt

\b
ce iir challenge sign --algorithm RS256 \\
--private-key rsa-key.pem \\
--challenge-file challenge.json \\
--output signed-challenge.jwt
"""
payload_obj = read_challenge(challenge_file)
kid = payload_obj["did"].strip()

if algorithm == ALGORITHM_RS256:
token = _rs256.sign_and_verify(private_key, kid, payload_obj)
else:
if looks_like_rsa_key(private_key):
raise click.ClickException(
"This looks like an RSA/PEM key. Use --algorithm RS256 for RSA keys."
)
token = _ed25519.sign_and_verify(private_key, kid, payload_obj)

if out_path:
with open(out_path, "w", encoding="utf-8") as f:
f.write(token)
err_console.print(f"Wrote Proof JWT to: [cyan]{out_path}[/cyan]")
else:
click.echo(token)


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions ce/implementations/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Reusable implementations behind the CLI commands (not CLI wrappers)."""
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""`ce iir challenge sign` - sign and verify a Proof JWT for a single CE challenge.
"""Ed25519 signing for `ce iir challenge sign --algorithm Ed25519`.

Reads a challenge JSON file produced by CE, signs it with an Ed25519 private key
(alg=EdDSA), and verifies the resulting JWT against the public key resolved from
the DID (did:key or did:web). No login required.
Signs a CE challenge with an Ed25519 private key (alg=EdDSA) and verifies the
resulting JWT against the public key resolved from the DID (did:key or did:web).
The RS256 path lives in ce.implementations.iir_challenge_sign_rs256.
The command is ce.iir.challenge.sign.
"""

from __future__ import annotations

import json
from typing import Any, Dict, Tuple

import base58
Expand Down Expand Up @@ -231,76 +231,12 @@ def _assert_signature_verifiable(token: str, kid: str) -> None:



# Click command

@click.command("sign")
@click.option(
"--private-key",
"private_key",
required=True,
metavar="MULTIBASE",
help="Ed25519 private seed (multibase base58btc, starts with 'z').",
)
@click.option(
"--challenge-file",
"challenge_file",
required=True,
type=click.Path(exists=True, dir_okay=False, readable=True),
metavar="PATH",
help="Path to CE-generated challenge JSON file.",
)
@click.option(
"--output", "-o",
"out_path",
default=None,
type=click.Path(dir_okay=False, writable=True),
metavar="PATH",
help="Write JWT to this file (otherwise printed to stdout).",
)
def sign_individual_challenge(
private_key: str,
challenge_file: str,
out_path: str | None,
) -> None:
"""Sign a single CE challenge JSON file and produce a Proof JWT (EdDSA/Ed25519).

\b
The challenge JSON must include: did, challenge, aud, iat, exp.
Signature verification uses did:key (offline) or did:web (HTTPS).

\b
Example:
ce iir challenge sign \\
--private-key zABC... \\
--challenge-file challenge.json \\
--output signed-challenge.jwt
"""
try:
with open(challenge_file, "r", encoding="utf-8") as f:
payload_obj = json.load(f)
except json.JSONDecodeError as e:
raise click.ClickException(f"Challenge file is not valid JSON: {e}")

if not isinstance(payload_obj, dict):
raise click.ClickException("Challenge payload must be a JSON object.")

required_fields = ["did", "challenge", "aud", "iat", "exp"]
missing = [k for k in required_fields if k not in payload_obj]
if missing:
raise click.ClickException(
f"Challenge JSON missing required field(s): {', '.join(missing)}"
)

did_value = payload_obj.get("did")
if not isinstance(did_value, str) or not did_value.strip():
raise click.ClickException(
'Challenge JSON must include a non-empty string field "did".'
)

kid = did_value.strip()
# Entry point used by `ce iir challenge sign --algorithm Ed25519`

def sign_and_verify(private_key_value: str, kid: str, payload_obj: Dict[str, Any]) -> str:
"""Sign the challenge with the Ed25519 seed (EdDSA) and verify it against the DID."""
try:
token = _sign_payload(private_key, kid, payload_obj)
token = _sign_payload(private_key_value, kid, payload_obj)
except ValueError as e:
raise click.ClickException(f"Signing failed: {e}")

Expand All @@ -311,9 +247,4 @@ def sign_individual_challenge(
except ValueError as e:
raise click.ClickException(f"DID resolution error: {e}")

if out_path:
with open(out_path, "w", encoding="utf-8") as f:
f.write(token)
err_console.print(f"Wrote Proof JWT to: [cyan]{out_path}[/cyan]")
else:
click.echo(token)
return token
Loading
Loading