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
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,67 @@ ce-87654321-...,did:web:example.com,did:web:example.com#key-1,,z3u2en...,,

`ValidFrom` and `ValidUntil` are optional.

### Publisher — API publishing (`ce publisher`)

Publish to the Credential Registry through a **project**: create it, add files, validate them, fix what validation
finds, then complete it. The Publisher has three kinds of project; ce-cli works with two:

- **Bulk upload (BU)**, the default and the standard project: **BU template CSVs**. The columns are the ones of the
Publisher's BU templates, for example the Credentials template. One class of file per `add`. A CSV you upload with
ce-cli is a BU project, the same project the Publisher UI makes.
- **API publishing**, created with `--jsonld`: **JSON-LD only**, in the shape the CSV transform produces, an array of
graphs, each with `@context`, `@id` and `@graph`. CSVs are refused.
- **Ruby Registry sync** is made by the Ruby Registry when it uploads a changeset. `ce publisher project list` shows
it; ce-cli adds no files to it, validates it or completes it.

| Command | Description |
| ------- | ----------- |
| `ce publisher project create --name <name> [--jsonld]` | Create a project. A BU project is the default; `--jsonld` makes an API publishing project |
| `ce publisher project add --project-id <id> --file <file or folder> [--type <template>]` | Add files, or replace the files of the same name. A BU project needs `--type`, the BU template the files follow: `credentials`, `learning-opportunities`, `assessments`, `jobs`, … Repeat `--file` for several; `--recursive` for subfolders |
| `ce publisher project validation run --project-id <id>` | Validate the latest iteration, including the CTIDs it refers to. A BU project starts validating when files are added, so this waits for it (`--no-wait` to return at once) |
| `ce publisher project validation status show --project-id <id>` | How many files passed and how many have errors (`--verbose` lists each one) |
| `ce publisher project validation errors show --project-id <id>` | The errors to fix |
| `ce publisher project status show --project-id <id>` | The project, its latest iteration and each publishing stage |
| `ce publisher project audit show --project-id <id>` | Who did what, oldest first |
| `ce publisher project complete --project-id <id>` | Approve the project and publish it (`--no-wait` to return at once). Run again to retry a failed publish |
| `ce publisher project list` | Your projects |
| `ce publisher project abandon --project-id <id>` | Abandon a project that was not published |

Every `show` command takes `-o json`.

```text
ce publisher project create --name "Welding certificates"
ce publisher project add --project-id 23 --file credentials.csv --type credentials
ce publisher project validation run --project-id 23
ce publisher project validation errors show --project-id 23
ce publisher project add --project-id 23 --file fixed\credentials.csv --type credentials
ce publisher project validation run --project-id 23
ce publisher project complete --project-id 23
ce publisher project audit show --project-id 23
```

How it behaves:

- **Adding** a CSV to a BU project starts validation at once. Adding a JSON-LD file to an API publishing project only stores it; run validation when you have
added everything.
- **Validation** checks the files and also looks up every CTID they refer to, with the same rules as the bulk
upload.
- **A change after validation** starts a new iteration, which begins as a copy of the last one. A file with the same
name replaces the earlier one.
- **Completing** needs a latest iteration that validated without errors. For a BU project it first transforms the
CSV files to JSON-LD and makes you a reviewer, so you can approve; then it approves and publishes. Each step is
recorded in the audit log.
- **Only you** can change an API publishing project you created.
- **Exit status** is 1 when a file was refused, validation found errors, or the project did not publish.

The Publisher API address comes from the environment (`publisher_api_base`); override it with `--publisher-url` or
`CE_PUBLISHER_API_URL`. Your account needs the Publisher user role and a tenant on its profile.

The commands call the Publisher through a client generated from its Swagger document
(`src/sdks/publisher-api/generated-client/publisher_client`, laid out as in ceops). `src/sdks/publisher-api/README.md` says how to regenerate it. The legacy Registry Assistant request format is
a Publisher feature flag that is off by default; ce-cli does not offer it, and a client generated while it is off has
no call for it.

## Project structure

```
Expand All @@ -245,6 +306,7 @@ ce-cli/
│ ├── 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
│ ├── publisher.py # ce publisher project ... / format
│ └── resource.py # ce resource list / show / create / delete
├── config/
│ ├── settings.py # OIDCSettings, token I/O, paths
Expand All @@ -254,6 +316,10 @@ ce-cli/
│ └── did_ops.py # DID validation, challenges, JWT signing
└── utils/
├── http.py # Authenticated httpx2 wrapper + APIError
├── display.py # Plain consoles and tables (no boxes or colours)
├── output.py # table/json/yaml/tsv renderer + @output_option
└── errors.py # @handle_api_errors decorator
```

Output is plain text: no boxes, no colours, no highlighting. Spinners are the only decoration. Use `ce.utils.display`
(`new_console`, `plain_table`, `print_pairs`) for anything new; `tests/test_plain_output.py` fails if styling comes back.
91 changes: 38 additions & 53 deletions ce/commands/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
from __future__ import annotations

import click
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from ce.auth.device_flow import (
AccessDeniedError,
Expand All @@ -19,11 +16,12 @@
login_required_message,
resolve_access_token,
)
from ce.config.context import get_current_environment, load_cli_config, require_environment
from ce.config.context import get_current_environment, load_cli_config
from ce.config.settings import delete_tokens, load_tokens, save_tokens
from ce.utils.display import new_console, print_pairs

console = Console()
err_console = Console(stderr=True)
console = new_console()
err_console = new_console(stderr=True)


@click.group("account")
Expand All @@ -46,59 +44,49 @@ def login(env_name: str | None) -> None:

if env_name:
if env_name not in config.environments:
err_console.print(f"Unknown environment [bold]{env_name}[/bold]. "
f"Run [bold]ce env list[/bold] to see available environments.")
err_console.print(f"Unknown environment {env_name}. "
f"Run ce env list to see available environments.")
raise SystemExit(1)
env = config.environments[env_name]
active_name = env_name
else:
result = get_current_environment()
if result is None:
err_console.print("No active environment. Run [bold]ce env use <name>[/bold] first.")
err_console.print("No active environment. Run ce env use <name> first.")
raise SystemExit(1)
active_name, env = result

# Reuse this environment's session rather than starting a second sign-in.
# An expired access token is renewed here; if it cannot be, sign-in goes ahead.
if is_logged_in(active_name):
console.print(f"Already signed in to [bold]{active_name}[/bold] "
f"([dim]{env.label}[/dim]). Run [bold]ce account show[/bold] for details.")
console.print(" To switch accounts, run [bold]ce account logout[/bold] first.")
console.print(f"Already signed in to {active_name} "
f"({env.label}). Run ce account show for details.")
console.print(" To switch accounts, run ce account logout first.")
return

client = KeycloakDeviceFlowClient(env)

console.print()
with console.status(f"[bold]Contacting {env.label} Keycloak...[/bold]"):
with console.status(f"Contacting {env.label} Keycloak..."):
try:
device_auth = client.request_device_code()
except DeviceFlowError as exc:
err_console.print(f"Error: {exc}")
raise SystemExit(1)

panel_content = (
f"[dim]Environment:[/dim] [bold]{active_name}[/bold] ({env.label})\n\n"
f"[dim]Open a browser and navigate to:[/dim]\n\n"
f" [bold underline]{device_auth.verification_uri}[/bold underline]\n\n"
f"[dim]Then enter the code:[/dim]\n\n"
f" [bold cyan]{device_auth.user_code}[/bold cyan]\n"
)
console.print(f"Sign in to Credential Engine: {active_name} ({env.label})")
console.print()
console.print("Open a browser and go to:")
console.print(f" {device_auth.verification_uri}")
console.print("Then enter the code:")
console.print(f" {device_auth.user_code}")
if device_auth.verification_uri_complete:
panel_content += (
f"\n[dim]Or visit the direct link:[/dim]\n"
f" [link={device_auth.verification_uri_complete}]"
f"{device_auth.verification_uri_complete}[/link]\n"
)

console.print(Panel(
panel_content,
title="[bold]Credential Engine - Device Sign-In[/bold]",
border_style="blue",
padding=(1, 2),
))
console.print("Or open the direct link:")
console.print(f" {device_auth.verification_uri_complete}")
console.print()

try:
with console.status("[dim]Waiting for you to approve in the browser...[/dim]", spinner="dots"):
with console.status("Waiting for you to approve in the browser...", spinner="dots"):
token_resp = client.poll_for_token(
device_code=device_auth.device_code,
interval=device_auth.interval,
Expand All @@ -110,7 +98,7 @@ def login(env_name: str | None) -> None:
raise SystemExit(1)
except TokenExpiredError:
console.print()
err_console.print("The device code expired. Run [bold]ce login[/bold] again.")
err_console.print("The device code expired. Run ce login again.")
raise SystemExit(1)
except DeviceFlowError as exc:
console.print()
Expand All @@ -128,12 +116,12 @@ def login(env_name: str | None) -> None:
name, email = "there", ""

console.print()
greeting = f"Signed in as [bold]{name}[/bold]"
greeting = f"Signed in as {name}"
if email:
greeting += f" [dim]({email})[/dim]"
greeting += f" [dim]-> {active_name} ({env.label})[/dim]"
greeting += f" ({email})"
greeting += f" -> {active_name} ({env.label})"
console.print(greeting)
console.print(" Run [bold]ce whoami[/bold] to view your account details.")
console.print(" Run ce whoami to view your account details.")
console.print()


Expand Down Expand Up @@ -174,7 +162,7 @@ def account_show() -> None:
"""Show the currently signed-in account."""
tokens = load_tokens()
if tokens is None:
console.print("Not signed in. Run [bold]ce login[/bold].")
console.print("Not signed in. Run ce login.")
return

result = get_current_environment()
Expand All @@ -201,26 +189,23 @@ def account_show() -> None:
err_console.print(f"Error fetching account info: {exc}")
return

table = Table(show_header=False, box=None, padding=(0, 2))
table.add_column("Key", style="dim")
table.add_column("Value", style="bold")

table.add_row("Environment", f"{active_name} ({env.label})")
table.add_row("API endpoint base", env.publisher_base)
table.add_row("Name", userinfo.get("name", "-"))
table.add_row("Username", userinfo.get("preferred_username", "-"))
table.add_row("Email", userinfo.get("email", "-"))
table.add_row("UserId", userinfo.get("sub", "-"))

rows = [
("Environment", f"{active_name} ({env.label})"),
("API endpoint base", env.publisher_base),
("Name", userinfo.get("name", "-")),
("Username", userinfo.get("preferred_username", "-")),
("Email", userinfo.get("email", "-")),
("UserId", userinfo.get("sub", "-")),
]
if tokens.scope:
table.add_row("Scopes", tokens.scope)
rows.append(("Scopes", tokens.scope))
if tokens.expires_at:
import datetime
exp = datetime.datetime.fromtimestamp(tokens.expires_at).strftime("%Y-%m-%d %H:%M:%S")
table.add_row("Token expires", exp)
rows.append(("Token expires", exp))

console.print()
console.print(Panel(table, title="[bold]Account[/bold]", border_style="blue", padding=(1, 2)))
print_pairs(console, rows)
console.print()


Expand Down
22 changes: 9 additions & 13 deletions ce/commands/config.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
from __future__ import annotations

import click
from rich.console import Console
from rich.table import Table, box

from ce.config.context import CLIConfig, load_cli_config, save_cli_config
from ce.utils.display import new_console, plain_table
from ce.utils.output import OUTPUT_FORMATS

console = Console()
err_console = Console(stderr=True)
console = new_console()
err_console = new_console(stderr=True)


_SETTABLE_KEYS = {
Expand Down Expand Up @@ -68,12 +67,12 @@ def config_set(assignments: tuple[str, ...]) -> None:
changed.append(f"{key} = {value}")

for err in errors:
err_console.print(f"[red]✗[/red] {err}")
err_console.print(f"Error: {err}")

if changed:
save_cli_config(cli_config)
for line in changed:
console.print(f"[green]✓[/green] {line}")
console.print(f"{line}")

if errors:
raise SystemExit(1)
Expand All @@ -95,7 +94,7 @@ def config_get(key: str) -> None:

if key not in _SETTABLE_KEYS:
err_console.print(
f"[red]✗[/red] Unknown key '{key}'. "
f"Error: Unknown key '{key}'. "
f"Valid keys: {', '.join(sorted(_SETTABLE_KEYS))}."
)
raise SystemExit(1)
Expand All @@ -110,16 +109,13 @@ def config_list() -> None:
"""List all CLI configuration values."""
cli_config = load_cli_config()

table = Table(box=box.SIMPLE_HEAD, header_style="bold", border_style="dim")
table.add_column("Key")
table.add_column("Value")
table.add_column("Description", style="dim")
table = plain_table(["Key", "Value", "Description"])

for key, field in sorted(_SETTABLE_KEYS.items()):
value = getattr(cli_config, field, "")
table.add_row(
key,
str(value) if value else "[dim]—[/dim]",
str(value) if value else "-",
_KEY_HELP.get(key, ""),
)

Expand All @@ -146,7 +142,7 @@ def config_reset(yes: bool) -> None:
environments=current.environments,
)
save_cli_config(reset)
console.print("[green]✓[/green] Configuration reset to defaults.")
console.print("Configuration reset to defaults.")


config_group.add_command(config_set)
Expand Down
Loading
Loading