From d095994a68388bfa2ec22105ce6dd61cc9a6234d Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 18:32:48 -0500 Subject: [PATCH 1/3] Show the complete public Seal before publication consent --- openadapt/cli.py | 8 +++---- openadapt/seal_publish.py | 20 ++++++++--------- tests/test_seal_publish.py | 45 +++++++++++++++++++++++++++++++------- 3 files changed, 51 insertions(+), 22 deletions(-) diff --git a/openadapt/cli.py b/openadapt/cli.py index 0d589300fa..d2aadb6080 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -2041,10 +2041,10 @@ def _seal_publish_parser() -> argparse.ArgumentParser: "and the hour the run started, signed by this computer's Seal key. " "It never holds inputs, typed values, screenshots or record " "contents. The program name is left out unless you pass --names " - "(the synthetic tutorial includes it). The exact card is printed " - "first, and nothing is uploaded until you say yes: at the prompt, " - "or with --yes when there is no terminal. --yes skips the " - "question, not the printed card." + "(the synthetic tutorial includes it). The preview shows the full " + "public Seal. Seals signed by the same key have the same public " + "key ID. Confirm at the prompt, or pass --yes to publish without " + "a prompt." ), allow_abbrev=False, ) diff --git a/openadapt/seal_publish.py b/openadapt/seal_publish.py index 1fc232374a..dff12be08b 100644 --- a/openadapt/seal_publish.py +++ b/openadapt/seal_publish.py @@ -5,7 +5,7 @@ :mod:`openadapt_flow.public_seal`): counts, outcomes, the step strip, digests and the hour the run started, signed by the same key. The program name is in it only with ``--names`` (or for the synthetic tutorial), because a program -name can be a person's name. The exact card is always printed first; only +name can be a person's name. The full public Seal is always printed first; only that file is uploaded, and only after the person says yes: * in a terminal, a y/N prompt that defaults to No; @@ -46,7 +46,7 @@ #: The exact consent question; ``{host}`` is the endpoint's host. PROMPT = ( - "This uploads the summary above to {host} and gives you a link. Anyone " + "This uploads the signed Seal above to {host} and gives you a link. Anyone " "with the link can see it. It does not upload your inputs, screenshots or " "records. Publish? [y/N] " ) @@ -295,12 +295,8 @@ def build( def card_text(doc: Mapping[str, Any]) -> str: - """The exact card that is uploaded, and the key that signs it.""" - return json.dumps( - {"card": doc["card"], "signed_by": doc["seal"]["key_id"]}, - indent=2, - sort_keys=True, - ) + """Show every field in the public Seal before consent.""" + return json.dumps(dict(doc), indent=2, sort_keys=True) # -- publishing --------------------------------------------------------------- @@ -571,8 +567,8 @@ def publish( ) -> Optional[str]: """Build, show, ask, upload. Returns the link, or None when nothing was sent. - The exact card is always printed before anything is asked or sent; - ``yes`` skips the question, never the card. Raises :class:`PublishError` + The full public Seal is always printed before anything is asked or sent; + ``yes`` skips the question, never the preview. Raises :class:`PublishError` with an exit code for each refusal. """ run_dir = Path(run_dir) @@ -584,6 +580,10 @@ def publish( return str(existing["url"]) doc = build(run_dir, names=names, github=github, provenance=provenance) say(card_text(doc)) + say( + "Anyone who sees two Seals can compare their key IDs to see " + "if the same key signed both." + ) if dry_run: say(f"Dry run: wrote {run_dir / 'public-seal.json'}. Nothing was uploaded.") return None diff --git a/tests/test_seal_publish.py b/tests/test_seal_publish.py index d0d369cbcd..95edebd433 100644 --- a/tests/test_seal_publish.py +++ b/tests/test_seal_publish.py @@ -167,9 +167,37 @@ def test_publish_uploads_the_public_seal_bytes_and_saves_the_token(make_run, tmp assert record == {"id": SEAL_ID, "url": url, "delete_token": TOKEN} assert stat.S_IMODE((run / "seal.publish.json").stat().st_mode) == 0o600 assert f"Published: {url}" in said - # The exact card is shown before anything is sent. - shown = json.loads(said[0]) - assert shown["card"] == json.loads(body)["card"] + assert json.loads(said[0]) == json.loads(body) + assert "the same key signed both" in said[1] + + +@needs_engine +def test_authorized_run_previews_scope_digest_and_issue_time_before_consent(make_run): + from openadapt_flow.offline_seal import seal_run + + run = make_run() + seal_run( + run, + authorization=("a" * 64, "r3"), + replace_unanchored=True, + enqueue=False, + ) + transport = Recorder() + shown = [] + + def decline(_question): + seal = json.loads(shown[0])["seal"] + assert seal["authorization_sha256"] == "a" * 64 + assert seal["scope_item"] == "r3" + saved = json.loads((run / "public-seal.json").read_text()) + assert seal["issued_at"] == saved["seal"]["issued_at"] + return "no" + + url = publish( + run, interactive=True, ask=decline, say=shown.append, transport=transport + ) + assert url is None + assert transport.requests == [] def test_no_terminal_and_no_yes_refuses_without_a_request(make_run, tmp_path): @@ -208,7 +236,7 @@ def test_the_prompt_defaults_to_no(make_run, tmp_path, answer): def test_the_prompt_text_is_the_agreed_one(): assert PROMPT.format(host="app.openadapt.ai") == ( - "This uploads the summary above to app.openadapt.ai and gives you a link. " + "This uploads the signed Seal above to app.openadapt.ai and gives you a link. " "Anyone with the link can see it. It does not upload your inputs, " "screenshots or records. Publish? [y/N] " ) @@ -710,13 +738,14 @@ def test_the_quickstart_offer_shows_the_card_then_asks_once( ) asks = [i for i, (kind, _) in enumerate(events) if kind == "ask"] assert len(asks) == 1 and events[asks[0]][1].endswith("Publish? [y/N] ") - # The exact card that would be uploaded is printed before the question. - card = json.loads((run / "public-seal.json").read_text())["card"] + # The complete document and key disclosure precede consent, even on refusal. + doc = json.loads((run / "public-seal.json").read_text()) shown = [ json.loads(line) for kind, line in events[: asks[0]] if line.startswith("{") ] - assert shown and shown[0]["card"] == card - assert card["provenance"] == "synthetic-tutorial" + assert shown == [doc] + assert any("the same key signed both" in line for _, line in events[: asks[0]]) + assert doc["card"]["provenance"] == "synthetic-tutorial" assert events[-1] == ("say", "Not published.") assert not (run / "seal.publish.json").exists() # Only the status check was sent; a No uploads nothing. From 5a3c5e09c7e477b9f960418ed66e6b8b0d588714 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 20:13:25 -0500 Subject: [PATCH 2/3] List public Seal fields before consent and show exact bytes on request --- CHANGELOG.md | 10 +++ openadapt/cli.py | 22 ++++--- openadapt/seal_publish.py | 66 ++++++++++++++++--- tests/test_seal_publish.py | 126 ++++++++++++++++++++++++++++++++----- 4 files changed, 192 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e7871aaf4..bbb176ef38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ +## Unreleased + +### Fixes + +- Before publishing a Seal, the quickstart and `openadapt seal publish` list + each public field and explain how readers can link Seals signed by the same + key. Type `show` at the prompt to inspect the exact upload, or run + `openadapt seal publish --show` to write its bytes to standard output without + publishing. + ## v1.23.0 (2026-11-19) ### Fixes diff --git a/openadapt/cli.py b/openadapt/cli.py index d2aadb6080..02436eff79 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -819,10 +819,7 @@ def offer(run_dir: Path, say, ask) -> bool: return False except PublishError: return False - say( - "Put this Seal online? This is the exact summary that would be " - f"uploaded ({run_dir / 'public-seal.json'}):" - ) + say("Put this Seal online? These fields would be shared:") try: publish( run_dir, @@ -2041,8 +2038,8 @@ def _seal_publish_parser() -> argparse.ArgumentParser: "and the hour the run started, signed by this computer's Seal key. " "It never holds inputs, typed values, screenshots or record " "contents. The program name is left out unless you pass --names " - "(the synthetic tutorial includes it). The preview shows the full " - "public Seal. Seals signed by the same key have the same public " + "(the synthetic tutorial includes it). The preview lists every field; " + "--show prints the exact upload. Seals signed by the same key have the same public " "key ID. Confirm at the prompt, or pass --yes to publish without " "a prompt." ), @@ -2064,7 +2061,12 @@ def _seal_publish_parser() -> argparse.ArgumentParser: parser.add_argument( "--dry-run", action="store_true", - help="write and print public-seal.json; upload nothing", + help="preview all public fields and write public-seal.json; upload nothing", + ) + parser.add_argument( + "--show", + action="store_true", + help="write the exact upload bytes to standard output and exit without publishing", ) parser.add_argument( "--github", @@ -2124,7 +2126,7 @@ def _ask_line(prompt: str) -> str: def _publish_seal(argv: list[str]) -> int: """`openadapt seal publish [RUN_DIR]`.""" - from openadapt.seal_publish import PublishError, publish + from openadapt.seal_publish import PublishError, build, public_bytes, publish options = _seal_publish_parser().parse_args(argv) run_dir = options.run_dir or _newest_sealed_run() @@ -2138,6 +2140,10 @@ def _publish_seal(argv: list[str]) -> int: click.echo(f"Not published: {run_dir} has no seal.json.", err=True) return 2 try: + if options.show: + doc = build(run_dir, names=options.names, github=options.github) + click.get_binary_stream("stdout").write(public_bytes(doc)) + return 0 publish( run_dir, yes=options.yes, diff --git a/openadapt/seal_publish.py b/openadapt/seal_publish.py index dff12be08b..3c527e06e0 100644 --- a/openadapt/seal_publish.py +++ b/openadapt/seal_publish.py @@ -5,7 +5,7 @@ :mod:`openadapt_flow.public_seal`): counts, outcomes, the step strip, digests and the hour the run started, signed by the same key. The program name is in it only with ``--names`` (or for the synthetic tutorial), because a program -name can be a person's name. The full public Seal is always printed first; only +name can be a person's name. Every public field is listed before consent; only that file is uploaded, and only after the person says yes: * in a terminal, a y/N prompt that defaults to No; @@ -20,6 +20,7 @@ from __future__ import annotations +import itertools import json import os import re @@ -29,7 +30,7 @@ import urllib.request from dataclasses import dataclass from pathlib import Path -from typing import Any, Callable, Mapping, Optional +from typing import Any, Callable, Iterator, Mapping, Optional from urllib.parse import urlsplit DEFAULT_ENDPOINT = "https://app.openadapt.ai" @@ -46,9 +47,9 @@ #: The exact consent question; ``{host}`` is the endpoint's host. PROMPT = ( - "This uploads the signed Seal above to {host} and gives you a link. Anyone " + "This uploads the signed Seal to {host} and gives you a link. Anyone " "with the link can see it. It does not upload your inputs, screenshots or " - "records. Publish? [y/N] " + "records. Type show for the exact bytes. Publish? [y/N] " ) @@ -192,6 +193,7 @@ def consent( interactive: bool, ask: Callable[[str], str], host: str, + show: Optional[Callable[[], None]] = None, env: Optional[Mapping[str, str]] = None, ) -> bool: """True only on an explicit yes. Raises PublishError (exit 2) when none can be had. @@ -212,10 +214,14 @@ def consent( "Not published: no terminal to ask. Pass --yes to publish.", 2 ) try: - answer = ask(PROMPT.format(host=host)) + while True: + answer = ask(PROMPT.format(host=host)).strip().lower() + if show is None or answer not in ("show", "s", "--show"): + break + show() except EOFError: return False - return answer.strip().lower() in ("y", "yes") + return answer in ("y", "yes") # -- building --------------------------------------------------------------- @@ -295,8 +301,45 @@ def build( def card_text(doc: Mapping[str, Any]) -> str: - """Show every field in the public Seal before consent.""" - return json.dumps(dict(doc), indent=2, sort_keys=True) + """List the actual public fields. Repeated step fields share a line in run order.""" + lines = [] + for section, fields in doc.items(): + lines.append(section.title()) + values: dict[str, list[str]] = {} + for name, value in fields.items(): + for label, shown in _preview_fields(name, value): + values.setdefault(label, []).append(shown) + for label, items in values.items(): + runs = [] + for item, group in itertools.groupby(items): + count = sum(1 for _ in group) + runs.append(item if count == 1 else f"{item} × {count}") + label = label.replace("[]", " (in order)").replace(".", " / ") + label = label.replace("_", " ").capitalize().replace("sha256", "SHA-256") + if label.endswith(" id"): + label = label[:-2] + "ID" + lines.append(f" {label}: {', '.join(runs)}") + return "\n".join(lines) + + +def _preview_fields(name: str, value: Any) -> Iterator[tuple[str, str]]: + """Yield a path and value for each leaf, including explicit nulls and empty lists.""" + if isinstance(value, dict) and value: + for key, child in value.items(): + yield from _preview_fields(f"{name}.{key}", child) + elif isinstance(value, list) and value: + for child in value: + yield from _preview_fields(f"{name}[]", child) + else: + if isinstance(value, str): + shown = value + if name.endswith(("_sha256", "_digest")) and re.fullmatch( + "[0-9a-f]{64}", value + ): + shown = f"{value[:8]}…{value[-8:]}" + else: + shown = json.dumps(value) + yield name, shown # -- publishing --------------------------------------------------------------- @@ -567,7 +610,7 @@ def publish( ) -> Optional[str]: """Build, show, ask, upload. Returns the link, or None when nothing was sent. - The full public Seal is always printed before anything is asked or sent; + All public fields are shown before anything is asked or sent; ``yes`` skips the question, never the preview. Raises :class:`PublishError` with an exit code for each refusal. """ @@ -580,6 +623,10 @@ def publish( return str(existing["url"]) doc = build(run_dir, names=names, github=github, provenance=provenance) say(card_text(doc)) + public_file = run_dir / "public-seal.json" + if public_file.is_relative_to(Path.cwd()): + public_file = public_file.relative_to(Path.cwd()) + say(f"Exact upload: {public_file} (or add --show to the same publish command).") say( "Anyone who sees two Seals can compare their key IDs to see " "if the same key signed both." @@ -595,6 +642,7 @@ def publish( interactive=interactive, ask=ask, host=host_of(origin), + show=lambda: say(public_bytes(doc).decode("utf-8")), ): say("Not published.") return None diff --git a/tests/test_seal_publish.py b/tests/test_seal_publish.py index 95edebd433..bf263acc50 100644 --- a/tests/test_seal_publish.py +++ b/tests/test_seal_publish.py @@ -152,6 +152,33 @@ def _publish(run: Path, transport: Recorder, **kwargs) -> tuple[str | None, list # -- upload -------------------------------------------------------------------- +def _assert_preview_covers_document(preview: str, doc: dict) -> None: + def fields(value, path): + if isinstance(value, dict) and value: + return set().union( + *(fields(child, f"{path}.{key}") for key, child in value.items()) + ) + if isinstance(value, list) and value: + return set().union(*(fields(child, f"{path}[]") for child in value)) + return {path} + + found = [] + for line in preview.splitlines(): + if not line.startswith(" "): + section = line.lower() + else: + field, value = line.strip().split(": ", 1) + assert value + wire = ( + field.lower().replace("sha-256", "sha256").replace(" (in order)", "[]") + ) + wire = wire.replace(" / ", ".").replace(" ", "_") + found.append(f"{section}.{wire}") + assert len(found) == len(set(found)) + expected = set().union(*(fields(value, key) for key, value in doc.items())) + assert set(found) == expected + + def test_publish_uploads_the_public_seal_bytes_and_saves_the_token(make_run, tmp_path): run = make_run() transport = Recorder(created()) @@ -167,8 +194,11 @@ def test_publish_uploads_the_public_seal_bytes_and_saves_the_token(make_run, tmp assert record == {"id": SEAL_ID, "url": url, "delete_token": TOKEN} assert stat.S_IMODE((run / "seal.publish.json").stat().st_mode) == 0o600 assert f"Published: {url}" in said - assert json.loads(said[0]) == json.loads(body) - assert "the same key signed both" in said[1] + doc = json.loads(body) + _assert_preview_covers_document(said[0], doc) + assert doc["card"]["report_sha256"] not in said[0] + assert f" Signature: {doc['seal']['signature']}" in said[0].splitlines() + assert any("the same key signed both" in line for line in said) @needs_engine @@ -186,11 +216,14 @@ def test_authorized_run_previews_scope_digest_and_issue_time_before_consent(make shown = [] def decline(_question): - seal = json.loads(shown[0])["seal"] - assert seal["authorization_sha256"] == "a" * 64 - assert seal["scope_item"] == "r3" saved = json.loads((run / "public-seal.json").read_text()) - assert seal["issued_at"] == saved["seal"]["issued_at"] + _assert_preview_covers_document(shown[0], saved) + rows = shown[0].splitlines() + assert " Authorization SHA-256: aaaaaaaa…aaaaaaaa" in rows + assert " Scope item: r3" in rows + assert f" Issued at: {saved['seal']['issued_at']}" in rows + assert " Program name: null" in rows + assert "Identity claim" not in shown[0] return "no" url = publish( @@ -236,9 +269,9 @@ def test_the_prompt_defaults_to_no(make_run, tmp_path, answer): def test_the_prompt_text_is_the_agreed_one(): assert PROMPT.format(host="app.openadapt.ai") == ( - "This uploads the signed Seal above to app.openadapt.ai and gives you a link. " + "This uploads the signed Seal to app.openadapt.ai and gives you a link. " "Anyone with the link can see it. It does not upload your inputs, " - "screenshots or records. Publish? [y/N] " + "screenshots or records. Type show for the exact bytes. Publish? [y/N] " ) @@ -405,7 +438,11 @@ def test_cli_dry_run_defaults_to_the_newest_quickstart_run( result = CliRunner().invoke(cli.main, ["seal", "publish", "--dry-run"]) assert result.exit_code == 0, result.output assert (newest / "public-seal.json").is_file() - assert '"steps_total":' in result.output + newest_doc = json.loads((newest / "public-seal.json").read_bytes()) + assert ( + f" Steps total: {newest_doc['card']['steps_total']}" + in result.output.splitlines() + ) def test_cli_publish_with_yes_uses_the_transport(make_run, tmp_path, monkeypatch): @@ -417,11 +454,34 @@ def test_cli_publish_with_yes_uses_the_transport(make_run, tmp_path, monkeypatch ) assert result.exit_code == 0, result.output assert f"Published: {ORIGIN}/seal#{SEAL_ID}" in result.output - # --yes skips the question, not the card: it is printed before the upload. - assert result.output.index('"card"') < result.output.index("Published:") + assert result.output.index("Card\n") < result.output.index("Published:") + assert '{"card"' not in result.output assert "Publish? [y/N]" not in result.output +def test_cli_show_stdout_is_the_exact_upload_and_never_publishes(make_run, monkeypatch): + run = make_run() + transport = Recorder(created()) + monkeypatch.setattr(seal_publish, "urllib_transport", transport) + args = ["seal", "publish", str(run), "--github", "sample-org", "--names"] + result = CliRunner().invoke(cli.main, [*args, "--show", "--yes"]) + assert result.exit_code == 0, result.output + exact = (run / "public-seal.json").read_bytes() + assert result.stdout_bytes == exact + assert transport.requests == [] + + posted = CliRunner().invoke(cli.main, [*args, "--yes", "--endpoint", ORIGIN]) + assert posted.exit_code == 0, posted.output + assert transport.requests[0][2] == exact + if ENGINE: + assert " Identity claim / login: sample-org" in posted.output.splitlines() + + # Reading an already published Seal still writes only the upload bytes. + again = CliRunner().invoke(cli.main, [*args, "--show"]) + assert again.exit_code == 0 and again.stdout_bytes == exact + assert len(transport.requests) == 1 + + def test_cli_publish_help_runs_nothing(tmp_path): result = CliRunner().invoke(cli.main, ["seal", "publish", "--help"]) assert result.exit_code == 0 @@ -740,10 +800,9 @@ def test_the_quickstart_offer_shows_the_card_then_asks_once( assert len(asks) == 1 and events[asks[0]][1].endswith("Publish? [y/N] ") # The complete document and key disclosure precede consent, even on refusal. doc = json.loads((run / "public-seal.json").read_text()) - shown = [ - json.loads(line) for kind, line in events[: asks[0]] if line.startswith("{") - ] - assert shown == [doc] + preview = next(line for _, line in events[: asks[0]] if line.startswith("Card\n")) + _assert_preview_covers_document(preview, doc) + assert not any(line.startswith("{") for _, line in events[: asks[0]]) assert any("the same key signed both" in line for _, line in events[: asks[0]]) assert doc["card"]["provenance"] == "synthetic-tutorial" assert events[-1] == ("say", "Not published.") @@ -752,6 +811,43 @@ def test_the_quickstart_offer_shows_the_card_then_asks_once( assert [r[0] for r in transport.requests] == ["GET"] +def test_show_at_the_quickstart_question_displays_exact_upload_then_asks_again( + make_run, monkeypatch +): + run = make_run() + _terminal(monkeypatch) + transport = Recorder(_status(True)) + monkeypatch.setattr(seal_publish, "urllib_transport", transport) + events = [] + answers = iter(["show", "n"]) + cli._quickstart_publish_offer()( + run, + lambda line: events.append(("say", line)), + lambda prompt: events.append(("ask", prompt)) or next(answers), + ) + asks = [i for i, (event, _) in enumerate(events) if event == "ask"] + assert len(asks) == 2 + assert events[asks[0] + 1 : asks[1]] == [ + ("say", (run / "public-seal.json").read_bytes().decode("utf-8")) + ] + assert events[-1] == ("say", "Not published.") + assert [request[0] for request in transport.requests] == ["GET"] + + +def test_compact_preview_keeps_empty_lists_and_groups_repeated_step_values(): + doc = _golden_doc() + doc["card"]["steps"] = [] + empty = seal_publish.card_text(doc) + _assert_preview_covers_document(empty, doc) + assert " Steps: []" in empty.splitlines() + step = {"ok": True, "rung": "api", "evidence_class": "effect"} + doc["card"]["steps"] = [step, step, {**step, "ok": False}] + preview = seal_publish.card_text(doc) + _assert_preview_covers_document(preview, doc) + assert " Steps (in order) / ok: true × 2, false" in preview.splitlines() + assert " Steps (in order) / rung: api × 3" in preview.splitlines() + + @needs_engine def test_the_tutorial_card_carries_the_program_name(make_run, tmp_path, monkeypatch): run = make_run() From 4c5b6d72433cb39d9fdfa80bd1818d3bf9c1dc5a Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 22:40:25 -0500 Subject: [PATCH 3/3] =?UTF-8?q?Show=20each=20signed=20Seal=20before=20the?= =?UTF-8?q?=20quickstart=E2=80=99s=20shared=20consent=20question?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Integrate the paired publication flow from #2381. Both entry points preview all public fields and full canonical paths, inspect the exact local bytes, and upload only after an explicit decision. --- CAPABILITIES.md | 2 +- CHANGELOG.md | 3 +- llms-full.txt | 2 +- openadapt/cli.py | 16 +-- openadapt/quickstart/__init__.py | 6 +- openadapt/quickstart/story.py | 8 +- openadapt/quickstart/view.py | 28 ++-- openadapt/seal_publish.py | 139 ++++++++++++++++++-- tests/test_seal_publish.py | 215 ++++++++++++++++++++++++++----- 9 files changed, 341 insertions(+), 78 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 7f7a85d526..de6034f131 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -353,7 +353,7 @@ improvising or retrying when something is off. | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](packages/flow/docs/WRITE_RECEIPTS.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](packages/seal-view/README.md) | -| Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | +| Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here. The quickstart offers its checked and its stopped run's Seals in one question, showing every public field and the full path to each file; `--show` prints the exact upload | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | | Run authorizations signed with the authorizer's GitHub SSH key (`ssh-keygen -Y sign`, after a summary of what it allows), naming the signing key and bound to the bundle digest, items, profile and Seal keys, and referenced by each Seal; the identity checked against github.com (`--live`) or pinned allowed signers; a pseudonymous operator profile counted from anchored Seals only | Released ([#1401](https://github.com/OpenAdaptAI/OpenAdapt/pull/1401)) | Unit tests with synthetic data; signatures checked against OpenSSH's `ssh-keygen` both ways | `openadapt-flow local-seal authorize`, `local-seal run --authorization`, `local-seal profile`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#run-authorizations-who-authorized-the-runs) | | Run reports redacted before they are sealed: session and CSRF tokens, OAuth grants and credential headers become `` and are listed in `redactions`; a Seal refuses a report that still holds one; per-app policy | Released ([#1407](https://github.com/OpenAdaptAI/OpenAdapt/pull/1407)) | Unit tests with generated tokens; 7,773 local reports scanned, only OpenEMR `token_main` matched | `openadapt-flow redact-report`, `local-seal run --allow-unredacted`; [REPORT_REDACTION.md](packages/flow/docs/REPORT_REDACTION.md) | | Strict no-outbound mode and an unattended on-prem service | Released | Synthetic | `openadapt-flow no-outbound`, `service`; [ON_PREM.md](packages/flow/docs/ON_PREM.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index bbb176ef38..84a5dbbba8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,8 @@ - Before publishing a Seal, the quickstart and `openadapt seal publish` list each public field and explain how readers can link Seals signed by the same - key. Type `show` at the prompt to inspect the exact upload, or run + key. The quickstart shows the checked and stopped Seals, with both file + paths, before asking once. Type `show` at the prompt to inspect the exact upload, or run `openadapt seal publish --show` to write its bytes to standard output without publishing. diff --git a/llms-full.txt b/llms-full.txt index c74a23a193..db93bf7ab5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -787,7 +787,7 @@ improvising or retrying when something is off. | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRITE_RECEIPTS.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/seal-view/README.md) | -| Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | +| Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here. The quickstart offers its checked and its stopped run's Seals in one question, showing every public field and the full path to each file; `--show` prints the exact upload | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | | Run authorizations signed with the authorizer's GitHub SSH key (`ssh-keygen -Y sign`, after a summary of what it allows), naming the signing key and bound to the bundle digest, items, profile and Seal keys, and referenced by each Seal; the identity checked against github.com (`--live`) or pinned allowed signers; a pseudonymous operator profile counted from anchored Seals only | Released ([#1401](https://github.com/OpenAdaptAI/OpenAdapt/pull/1401)) | Unit tests with synthetic data; signatures checked against OpenSSH's `ssh-keygen` both ways | `openadapt-flow local-seal authorize`, `local-seal run --authorization`, `local-seal profile`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#run-authorizations-who-authorized-the-runs) | | Run reports redacted before they are sealed: session and CSRF tokens, OAuth grants and credential headers become `` and are listed in `redactions`; a Seal refuses a report that still holds one; per-app policy | Released ([#1407](https://github.com/OpenAdaptAI/OpenAdapt/pull/1407)) | Unit tests with generated tokens; 7,773 local reports scanned, only OpenEMR `token_main` matched | `openadapt-flow redact-report`, `local-seal run --allow-unredacted`; [REPORT_REDACTION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/REPORT_REDACTION.md) | | Strict no-outbound mode and an unattended on-prem service | Released | Synthetic | `openadapt-flow no-outbound`, `service`; [ON_PREM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ON_PREM.md) | diff --git a/openadapt/cli.py b/openadapt/cli.py index 02436eff79..f5fb4e95f8 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -806,12 +806,12 @@ def _quickstart_publish_offer(): if not _public_seals_available(): return None - def offer(run_dir: Path, say, ask) -> bool: + def offer(run_dirs: list[Path] | Path, say, ask) -> bool: from openadapt.seal_publish import ( PublishError, endpoint, hosted_seals_live, - publish, + publish_quickstart, ) try: @@ -819,16 +819,10 @@ def offer(run_dir: Path, say, ask) -> bool: return False except PublishError: return False - say("Put this Seal online? These fields would be shared:") + if isinstance(run_dirs, Path): + run_dirs = [run_dirs] try: - publish( - run_dir, - interactive=True, - ask=ask, - say=say, - provenance="synthetic-tutorial", - command=_hint, - ) + publish_quickstart(run_dirs, ask=ask, say=say, command=_hint) except PublishError as exc: say(str(exc)) except (KeyboardInterrupt, EOFError): diff --git a/openadapt/quickstart/__init__.py b/openadapt/quickstart/__init__.py index 4bcf4e28ab..9a09af572d 100644 --- a/openadapt/quickstart/__init__.py +++ b/openadapt/quickstart/__init__.py @@ -32,7 +32,7 @@ def next_steps( keep: Optional[str] = None, shadow: Optional[Callable[[], Optional[str]]] = None, offer_publish: Optional[ - Callable[[Path, Callable[[str], None], Callable[[str], str]], bool] + Callable[[list[Path], Callable[[str], None], Callable[[str], str]], bool] ] = None, ) -> Callable[[Outcome], NextSteps]: """The finale's commands, spelled by the launcher's ``hint`` helper. @@ -41,8 +41,8 @@ def next_steps( check (run once, at the finale) for an older ``openadapt`` on PATH. ``offer_publish`` is given only in a terminal outside CI, with an engine that can build public Seals. At the finale it asks once whether to put - the Seal online, and only when Cloud says hosted Seals are live. Otherwise - the finale says nothing about publishing. + the checked and stopped runs' Seals online. The offer appears only + when Cloud accepts hosted Seals. """ def build(outcome: Outcome) -> NextSteps: diff --git a/openadapt/quickstart/story.py b/openadapt/quickstart/story.py index 78bac2054b..369b3f1b5a 100644 --- a/openadapt/quickstart/story.py +++ b/openadapt/quickstart/story.py @@ -110,11 +110,11 @@ class NextSteps: #: The command that checks one run folder, for its Seal page. verify_run: Optional[Callable[[Path], str]] = None #: In a terminal and outside CI only: asks once whether to publish the - #: run's public Seal, and does so on a yes. Called as - #: ``offer_publish(run_dir, say, ask)``; returns False, having said - #: nothing, when hosted Seals are not live. + #: public Seals of the checked run and the stopped run, and does so on a + #: yes. Called as ``offer_publish(run_dirs, say, ask)``; returns False, + #: having said nothing, when hosted Seals are not live. offer_publish: Optional[ - Callable[[Path, Callable[[str], None], Callable[[str], str]], bool] + Callable[[list[Path], Callable[[str], None], Callable[[str], str]], bool] ] = None diff --git a/openadapt/quickstart/view.py b/openadapt/quickstart/view.py index 37c230da43..c90a39dfc3 100644 --- a/openadapt/quickstart/view.py +++ b/openadapt/quickstart/view.py @@ -318,13 +318,19 @@ def seal_page_note(outcome: Outcome) -> str: return note -def publish_run(outcome: Outcome) -> Optional[Path]: - """The run whose Seal the finale offers to publish: the first checked run.""" +def publish_runs(outcome: Outcome) -> list[Path]: + """The runs whose Seals the finale offers: the first checked run, then the + stopped run when Act 3 signed one. The stopped run is the point of the + quickstart, so it goes online with the checked run or not at all.""" page = outcome.seal_pages.verified if outcome.seal is None or page is None: - return None - return page.parent + return [] + runs = [page.parent] + broken = outcome.seal_pages.broken + if broken is not None and (broken.parent / "seal.json").is_file(): + runs.append(broken.parent) + return runs def next_step(steps: NextSteps) -> tuple[str, str, str]: @@ -575,11 +581,9 @@ def _ask(self, prompt: str) -> str: return input() def _publish(self, outcome: Outcome, steps: NextSteps) -> None: - run = publish_run(outcome) - if run is None: - return - if steps.offer_publish is not None: - steps.offer_publish(run, lambda line: self._say(f" {line}"), self._ask) + runs = publish_runs(outcome) + if runs and steps.offer_publish is not None: + steps.offer_publish(runs, lambda line: self._say(f" {line}"), self._ask) def confirm(self, prompt: str) -> None: self.stream.write(f" {prompt} ") @@ -1237,8 +1241,8 @@ def finale(self, outcome: Outcome, steps: NextSteps) -> None: self.console.print() if outcome.seal is not None: self._seal(outcome, seal_card(outcome)) - run = publish_run(outcome) - if run is not None and steps.offer_publish is not None: + runs = publish_runs(outcome) + if runs and steps.offer_publish is not None: spoken: list[bool] = [] def say(line: str) -> None: @@ -1248,7 +1252,7 @@ def say(line: str) -> None: self.console.print() self.console.print(_escape(line), soft_wrap=True) - steps.offer_publish(run, say, self._ask) + steps.offer_publish(runs, say, self._ask) self.console.print() self.console.print(Rule(style="cyan")) if all_clear(outcome): diff --git a/openadapt/seal_publish.py b/openadapt/seal_publish.py index 3c527e06e0..f37df12b06 100644 --- a/openadapt/seal_publish.py +++ b/openadapt/seal_publish.py @@ -144,12 +144,24 @@ def hosted_seals_live( """True only when ``origin`` answers 200 ``{"enabled": true}`` within ``timeout_s``. Anything else (an error, a timeout, a 404 from a Cloud without the route, - ``{"enabled": false}``) is False. The wait is bounded with a thread, since - a socket timeout does not bound the DNS lookup. + ``{"enabled": false}``) is False. + """ + return _status_true(origin + STATUS_PATH, transport=transport, timeout_s=timeout_s) + + +def _status_true( + url: str, + *, + transport: Optional[Transport] = None, + timeout_s: float = STATUS_TIMEOUT_S, +) -> bool: + """GET ``url``; True only for 200 ``{"enabled": true}`` within ``timeout_s``. + + The wait is bounded with a thread, since a socket timeout does not bound + the DNS lookup. """ import threading - url = origin + STATUS_PATH headers = {"Accept": "application/json"} if transport is None: real = _module_transport() @@ -162,7 +174,7 @@ def transport(method, url, body, headers): # type: ignore[no-redef] def ask() -> None: try: answer.append(transport("GET", url, None, headers)) - except Exception: # noqa: BLE001 - any failure means "do not offer" + except Exception: # noqa: BLE001 - any failure means "no" pass worker = threading.Thread(target=ask, name="seal-status", daemon=True) @@ -213,9 +225,16 @@ def consent( raise PublishError( "Not published: no terminal to ask. Pass --yes to publish.", 2 ) + return _ask_consent(PROMPT.format(host=host), ask, show) + + +def _ask_consent( + prompt: str, ask: Callable[[str], str], show: Optional[Callable[[], None]] +) -> bool: + """Inspect locally as often as requested; only an explicit yes authorizes a send.""" try: while True: - answer = ask(PROMPT.format(host=host)).strip().lower() + answer = ask(prompt).strip().lower() if show is None or answer not in ("show", "s", "--show"): break show() @@ -322,6 +341,22 @@ def card_text(doc: Mapping[str, Any]) -> str: return "\n".join(lines) +def _preview_seals( + docs: list[tuple[Path, dict[str, Any]]], say: Callable[[str], None] +) -> None: + for run_dir, doc in docs: + say(card_text(doc)) + say(f"Exact upload: {run_dir.resolve() / 'public-seal.json'}") + say( + "Type --show at the prompt to read the exact bytes. " + "For the seal publish command, add --show to inspect without uploading." + ) + say( + "Anyone who sees two Seals can compare their key IDs to see " + "if the same key signed both." + ) + + def _preview_fields(name: str, value: Any) -> Iterator[tuple[str, str]]: """Yield a path and value for each leaf, including explicit nulls and empty lists.""" if isinstance(value, dict) and value: @@ -622,15 +657,7 @@ def publish( say(f"To take it down: {command(f'seal unpublish {_quote(run_dir)}')}") return str(existing["url"]) doc = build(run_dir, names=names, github=github, provenance=provenance) - say(card_text(doc)) - public_file = run_dir / "public-seal.json" - if public_file.is_relative_to(Path.cwd()): - public_file = public_file.relative_to(Path.cwd()) - say(f"Exact upload: {public_file} (or add --show to the same publish command).") - say( - "Anyone who sees two Seals can compare their key IDs to see " - "if the same key signed both." - ) + _preview_seals([(run_dir, doc)], say) if dry_run: say(f"Dry run: wrote {run_dir / 'public-seal.json'}. Nothing was uploaded.") return None @@ -655,6 +682,87 @@ def publish( return str(record["url"]) +#: Answers ``{"enabled": true}`` only while Cloud shows two Seals on one page +#: (``/seal#,``). Older Clouds answer 404, and the CLI prints one link +#: per Seal instead. +PAIRS_STATUS_PATH = "/api/public/local-seal-pairs/status" + +#: The quickstart's one question, for both of its Seals. +QUICKSTART_PROMPT = ( + "This uploads {subjects} to {host} and gives you a link. " + "Anyone with the link can see the public fields above. They hold no inputs, screenshots or " + "records, and the runs used synthetic data. Publish? [y/N] " +) + + +def pair_link(origin: str, seal_ids: list[str]) -> str: + return f"{origin}/seal#{','.join(seal_ids)}" + + +def pairs_live(origin: str, *, transport: Optional[Transport] = None) -> bool: + """True only when Cloud's pair status route answers ``{"enabled": true}``.""" + return _status_true(origin + PAIRS_STATUS_PATH, transport=transport) + + +def publish_quickstart( + run_dirs: list[Path], + *, + ask: Callable[[str], str], + say: Callable[[str], None] = print, + endpoint_value: Optional[str] = None, + transport: Optional[Transport] = None, + command: Callable[[str], str] = lambda rest: f"openadapt {rest}", +) -> Optional[str]: + """Offer the quickstart's Seals (the checked run, then the stopped run) at once. + + Each card is built and written to its run's ``public-seal.json`` first, and + every public field is shown with the full path to its file, so the exact + bytes can be read before answering. One y/N question, default No, covers + both. Returns the link to open (one page for both when Cloud supports it), + or None when nothing was sent. + """ + origin = endpoint(endpoint_value) + docs = [] + for run_dir in run_dirs: + docs.append( + (Path(run_dir), build(Path(run_dir), provenance="synthetic-tutorial")) + ) + if not docs: + return None + _preview_seals(docs, say) + + def show() -> None: + for _, doc in docs: + say(public_bytes(doc).decode("utf-8")) + + subjects = "1 signed Seal" if len(docs) == 1 else f"{len(docs)} signed Seals" + if not _ask_consent( + QUICKSTART_PROMPT.format(subjects=subjects, host=host_of(origin)), ask, show + ): + say("Not published.") + return None + sender = transport or _module_transport() + records = [] + for run_dir, doc in docs: + existing = read_record(run_dir) + if existing is not None and existing.get("id"): + records.append(existing) + continue + records.append(upload(run_dir, doc, origin=origin, transport=sender)) + ids = [str(record["id"]) for record in records] + if len(ids) > 1 and pairs_live(origin, transport=transport): + link = pair_link(origin, ids) + say(f"Published. Both runs on one page: {link}") + else: + link = str(records[-1]["url"]) + for (run_dir, doc), record in zip(docs, records): + say(f"Published {doc['card'].get('outcome', '')}: {record['url']}") + say("Each run folder keeps its delete token. To take one down:") + for run_dir, _ in docs: + say(f" {command(f'seal unpublish {_quote(run_dir)}')}") + return link + + __all__ = [ "DEFAULT_ENDPOINT", "ENV_ENDPOINT", @@ -671,7 +779,10 @@ def publish( "hosted_seals_live", "in_ci", "parse_link", + "pair_link", + "pairs_live", "publish", + "publish_quickstart", "unpublish", "upload", ] diff --git a/tests/test_seal_publish.py b/tests/test_seal_publish.py index bf263acc50..8a9a04be45 100644 --- a/tests/test_seal_publish.py +++ b/tests/test_seal_publish.py @@ -196,6 +196,8 @@ def test_publish_uploads_the_public_seal_bytes_and_saves_the_token(make_run, tmp assert f"Published: {url}" in said doc = json.loads(body) _assert_preview_covers_document(said[0], doc) + assert f"Exact upload: {(run / 'public-seal.json').resolve()}" in said + assert any("--show" in line for line in said) assert doc["card"]["report_sha256"] not in said[0] assert f" Signature: {doc['seal']['signature']}" in said[0].splitlines() assert any("the same key signed both" in line for line in said) @@ -773,7 +775,7 @@ def transport(method, url, body, headers, *_timeout): def ask(_question): raise AssertionError("asked while hosted Seals are not live") - assert offer(run, said.append, ask) is False + assert offer([run], said.append, ask) is False assert said == [] assert not (run / "public-seal.json").exists() # One status check, to production's status route, and nothing else. @@ -782,56 +784,87 @@ def ask(_question): ] -def test_the_quickstart_offer_shows_the_card_then_asks_once( +def test_the_quickstart_offer_shows_each_card_then_asks_once( make_run, tmp_path, monkeypatch ): - run = make_run() + checked = make_run() + stopped = make_run("run-broken", execution_outcome="HALTED", success=False) _terminal(monkeypatch) transport = Recorder(_status(True)) monkeypatch.setattr(seal_publish, "urllib_transport", transport) offer = cli._quickstart_publish_offer() events: list[tuple[str, str]] = [] + monkeypatch.chdir(tmp_path) offer( - run, + [run.relative_to(tmp_path) for run in (checked, stopped)], lambda line: events.append(("say", line)), lambda q: events.append(("ask", q)) or "", ) asks = [i for i, (kind, _) in enumerate(events) if kind == "ask"] assert len(asks) == 1 and events[asks[0]][1].endswith("Publish? [y/N] ") - # The complete document and key disclosure precede consent, even on refusal. - doc = json.loads((run / "public-seal.json").read_text()) - preview = next(line for _, line in events[: asks[0]] if line.startswith("Card\n")) - _assert_preview_covers_document(preview, doc) - assert not any(line.startswith("{") for _, line in events[: asks[0]]) - assert any("the same key signed both" in line for _, line in events[: asks[0]]) - assert doc["card"]["provenance"] == "synthetic-tutorial" + assert "2 signed Seals" in events[asks[0]][1] and "synthetic" in events[asks[0]][1] + before = [line for kind, line in events[: asks[0]] if kind == "say"] + previews = [line for line in before if line.startswith("Card\n")] + assert len(previews) == 2 + for run, preview in zip((checked, stopped), previews): + path = (run / "public-seal.json").resolve() + doc = json.loads(path.read_bytes()) + assert doc["card"]["provenance"] == "synthetic-tutorial" + _assert_preview_covers_document(preview, doc) + assert f"Exact upload: {path}" in before + assert not any(line.startswith("{") for line in before) + assert any("the same key signed both" in line for line in before) + assert any("--show" in line for line in before) assert events[-1] == ("say", "Not published.") - assert not (run / "seal.publish.json").exists() + assert not (checked / "seal.publish.json").exists() + assert not (stopped / "seal.publish.json").exists() # Only the status check was sent; a No uploads nothing. assert [r[0] for r in transport.requests] == ["GET"] -def test_show_at_the_quickstart_question_displays_exact_upload_then_asks_again( - make_run, monkeypatch +@pytest.mark.parametrize("accept", [False, True]) +def test_inspecting_both_seals_shows_the_exact_uploads_before_the_decision( + make_run, monkeypatch, accept ): - run = make_run() + runs = _quickstart_pair(make_run) + (runs[0] / "receipt.json").write_text( + json.dumps({"provenance": "synthetic-tutorial"}) + ) _terminal(monkeypatch) - transport = Recorder(_status(True)) + responses = [_status(True)] + if accept: + responses.extend([_created(SEAL_ID), _created(OTHER_ID), _status(True)]) + transport = Recorder(*responses) monkeypatch.setattr(seal_publish, "urllib_transport", transport) events = [] - answers = iter(["show", "n"]) + answers = iter(["--show", "y" if accept else ""]) + + def ask(prompt): + events.append(("ask", prompt)) + assert [r[0] for r in transport.requests] == ["GET"] + return next(answers) + cli._quickstart_publish_offer()( - run, - lambda line: events.append(("say", line)), - lambda prompt: events.append(("ask", prompt)) or next(answers), + runs, lambda line: events.append(("say", line)), ask ) asks = [i for i, (event, _) in enumerate(events) if event == "ask"] assert len(asks) == 2 - assert events[asks[0] + 1 : asks[1]] == [ - ("say", (run / "public-seal.json").read_bytes().decode("utf-8")) - ] - assert events[-1] == ("say", "Not published.") - assert [request[0] for request in transport.requests] == ["GET"] + exact = [(run / "public-seal.json").read_bytes() for run in runs] + assert events[asks[0] + 1 : asks[1]] == [("say", data.decode()) for data in exact] + for run, data in zip(runs, exact): + result = CliRunner().invoke( + cli.main, ["seal", "publish", str(run), "--show", "--yes"] + ) + assert result.exit_code == 0 and result.stdout_bytes == data + if ENGINE: + assert [json.loads(data)["card"]["outcome"] for data in exact] == [ + "VERIFIED", + "HALTED", + ] + assert exact[0] != exact[1] + posts = [r[2] for r in transport.requests if r[0] == "POST"] + assert posts == (exact if accept else []) + assert all((run / "seal.publish.json").exists() == accept for run in runs) def test_compact_preview_keeps_empty_lists_and_groups_repeated_step_values(): @@ -868,8 +901,8 @@ def test_the_finale_offers_once_after_the_seal_card(tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) calls: list[Path] = [] - def offer(run_dir, say, ask): - calls.append(run_dir) + def offer(run_dirs, say, ask): + calls.append(run_dirs) say("offer shown") return True @@ -881,7 +914,7 @@ def offer(run_dir, say, ask): next_steps=next_steps(cli._hint, cli._shell_quote, True, offer_publish=offer), clock=_clock(), ) - assert calls == [root / "run-1"] + assert calls == [[root / "run-1"]] text = stream.getvalue() assert text.index("Your Seal:") < text.index("offer shown") < text.index("Next:") assert "seal publish" not in text @@ -931,13 +964,13 @@ def test_the_terminal_finale_offers_once_between_the_seal_and_next( monkeypatch.chdir(tmp_path) calls: list[Path] = [] - def offer(run_dir, say, ask): - calls.append(run_dir) + def offer(run_dirs, say, ask): + calls.append(run_dirs) say("offer shown") return True text = _rich_finale(tmp_path, offer) - assert calls == [tmp_path / "openadapt-quickstart" / "run-1"] + assert calls == [[tmp_path / "openadapt-quickstart" / "run-1"]] assert text.index("Your Seal") < text.index("offer shown") < text.index("Next ") assert "Put it online" not in text @@ -983,3 +1016,123 @@ def test_read_card_needs_both_files(tmp_path): assert card is not None assert (card.steps_ok, card.effects_confirmed, card.model_calls) == (6, 2, 0) assert card.short_digest == "6dd4a7f2d1ea" + + +# -- the quickstart's two Seals ------------------------------------------------- + +OTHER_ID = "C" * 43 + + +def _created(seal_id: str) -> Response: + body = {"id": seal_id, "url": f"{ORIGIN}/seal#{seal_id}", "delete_token": TOKEN} + return Response(201, {}, json.dumps(body).encode()) + + +def _quickstart_pair(make_run): + return [ + make_run(), + make_run("run-broken", execution_outcome="HALTED", success=False), + ] + + +def test_a_yes_uploads_both_and_gives_one_page_when_cloud_has_pairs(make_run): + runs = _quickstart_pair(make_run) + transport = Recorder(_created(SEAL_ID), _created(OTHER_ID), _status(True)) + said: list[str] = [] + link = seal_publish.publish_quickstart( + runs, + ask=lambda _q: "y", + say=said.append, + endpoint_value=ORIGIN, + transport=transport, + ) + assert link == f"{ORIGIN}/seal#{SEAL_ID},{OTHER_ID}" + posts = [r for r in transport.requests if r[0] == "POST"] + assert [r[2] for r in posts] == [ + (run / "public-seal.json").read_bytes() for run in runs + ] + assert transport.requests[-1][:2] == ( + "GET", + f"{ORIGIN}{seal_publish.PAIRS_STATUS_PATH}", + ) + assert any(link in line for line in said) + for run in runs: + assert json.loads((run / "seal.publish.json").read_text())["delete_token"] + assert any(f"seal unpublish {run}" in line for line in said) + + +@pytest.mark.parametrize( + "pairs", [Response(404, {}, b'{"error":"not_found"}'), _status(False)] +) +def test_an_older_cloud_gets_one_link_per_seal(make_run, pairs): + runs = _quickstart_pair(make_run) + transport = Recorder(_created(SEAL_ID), _created(OTHER_ID), pairs) + said: list[str] = [] + link = seal_publish.publish_quickstart( + runs, + ask=lambda _q: "yes", + say=said.append, + endpoint_value=ORIGIN, + transport=transport, + ) + assert link == f"{ORIGIN}/seal#{OTHER_ID}" + assert any(f"/seal#{SEAL_ID}" in line for line in said) + assert any(f"/seal#{OTHER_ID}" in line for line in said) + assert not any("," in line and "/seal#" in line for line in said) + + +def test_a_quickstart_run_already_online_is_not_uploaded_twice(make_run): + runs = _quickstart_pair(make_run) + (runs[0] / "seal.publish.json").write_text( + json.dumps( + {"id": SEAL_ID, "url": f"{ORIGIN}/seal#{SEAL_ID}", "delete_token": TOKEN} + ) + ) + transport = Recorder(_created(OTHER_ID), _status(True)) + link = seal_publish.publish_quickstart( + runs, + ask=lambda _q: "y", + say=lambda _l: None, + endpoint_value=ORIGIN, + transport=transport, + ) + assert link == f"{ORIGIN}/seal#{SEAL_ID},{OTHER_ID}" + assert [r[0] for r in transport.requests] == ["POST", "GET"] + + +@pytest.mark.parametrize("answer", ["", "n", "no", "anything"]) +def test_anything_but_yes_uploads_nothing(make_run, answer): + runs = _quickstart_pair(make_run) + transport = Recorder() + said: list[str] = [] + assert ( + seal_publish.publish_quickstart( + runs, + ask=lambda _q: answer, + say=said.append, + endpoint_value=ORIGIN, + transport=transport, + ) + is None + ) + assert transport.requests == [] and said[-1] == "Not published." + + +def test_the_finale_offers_the_stopped_run_with_the_checked_one(tmp_path): + from openadapt.quickstart.engine import SealFacts, SealPages + from openadapt.quickstart.story import Outcome + from openadapt.quickstart.view import publish_runs + + root = tmp_path / "openadapt-quickstart" + for name in ("run-1", "run-broken"): + (root / name).mkdir(parents=True) + (root / name / "seal.html").write_text("") + pages = SealPages( + verified=root / "run-1" / "seal.html", broken=root / "run-broken" / "seal.html" + ) + outcome = Outcome(root=root, seal=SealFacts("", 1), seal_pages=pages) + # The stopped run is offered only once it has its own Seal. + assert publish_runs(outcome) == [root / "run-1"] + (root / "run-broken" / "seal.json").write_text("{}") + assert publish_runs(outcome) == [root / "run-1", root / "run-broken"] + assert publish_runs(Outcome(root=root, seal=None, seal_pages=pages)) == []