diff --git a/docs/quickstart/own-2026-11-21/own-ending.png b/docs/quickstart/own-2026-11-21/own-ending.png new file mode 100644 index 0000000000..25e4ecfcda Binary files /dev/null and b/docs/quickstart/own-2026-11-21/own-ending.png differ diff --git a/openadapt/cli.py b/openadapt/cli.py index ead1c56b8f..3e5e00f9fa 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -344,6 +344,38 @@ def __getattr__(self, name): return getattr(self._stream, name) +def _is_login(argv: list[str]) -> bool: + """``login`` or ``setup login``, not its help.""" + if argv[:1] == ["login"]: + rest = argv[1:] + elif argv[:2] == ["setup", "login"]: + rest = argv[2:] + else: + return False + return not any(token in ("-h", "--help") for token in rest) + + +def _option_values(argv: list[str], name: str) -> Optional[list[str]]: + """Every value of a repeatable ``--name VALUE`` option, or None.""" + values = [] + for index, token in enumerate(argv): + if token == name and index + 1 < len(argv): + values.append(argv[index + 1]) + elif token.startswith(name + "="): + values.append(token[len(name) + 1 :]) + return values or None + + +def _option_value(argv: list[str], name: str) -> Optional[str]: + """The value of ``--name VALUE`` or ``--name=VALUE`` in ``argv``, if any.""" + for index, token in enumerate(argv): + if token == name and index + 1 < len(argv): + return argv[index + 1] + if token.startswith(name + "="): + return token[len(name) + 1 :] + return None + + def _invoke_flow(argv: list[str]) -> int: """Invoke the canonical engine once and return its exit code.""" if not _python_supported(): @@ -368,6 +400,17 @@ def _invoke_flow(argv: list[str]) -> int: alias_context = suppress_alias_notices() with alias_context: _correct_released_flow_x11_sonames() + if _is_login(argv): + code = int(flow_main(argv)) + if code == 0: + from openadapt.seal_claim import after_login + + after_login( + _option_value(argv, "--host"), + destination_kind=_option_value(argv, "--destination-kind"), + trusted_hosts=_option_values(argv, "--trusted-host"), + ) + return code if argv[:1] != ["tutorial"]: return int(flow_main(argv)) # The tutorial is the first-run path and ends by printing next steps. @@ -709,6 +752,39 @@ def _quickstart_root(out: Optional[Path]) -> Path: return root +def _quickstart_own(root: Path, url: Optional[str], watch: bool) -> None: + """`openadapt quickstart --own`: see openadapt/quickstart/own.py.""" + from functools import partial + + from openadapt.quickstart.engine import display_available + from openadapt.quickstart.own import OwnTaskError, run_own, share_runs + + def ask(prompt: str) -> str: + return input(prompt) + + from contextlib import nullcontext + + context = _synthetic_scrub_off() if url is None else nullcontext() + try: + with context: + run_own( + root, + url=url, + visible=_watch_window(watch), + can_record_here=sys.stdin.isatty() and display_available(), + ask=ask, + say=click.echo, + hint=_hint, + quote=_shell_quote, + share=partial(share_runs, ask=ask, say=click.echo, command=_hint), + ) + except OwnTaskError as error: + raise click.ClickException(str(error)) from error + except KeyboardInterrupt: + click.echo(f"\nStopped. Anything written so far is in {root}", err=True) + raise click.exceptions.Exit(130) + + @main.command( "quickstart", context_settings={ @@ -775,6 +851,19 @@ def _quickstart_root(out: Optional[Path]) -> Path: # --headed is the older spelling of --watch. --headless was the opt-out when # the window showed by default; hidden is the default now, so it changes # nothing and is kept so older commands still run. +@click.option( + "--own", + is_flag=True, + help=( + "Your own task: record it once (in the sample app, or your web app " + "with --url), run it with new inputs, and end with an agent tool." + ), +) +@click.option( + "--url", + default=None, + help="With --own: your web app's address. Recording opens a browser window.", +) @click.option("--headed", is_flag=True, hidden=True) @click.option("--headless", is_flag=True, hidden=True) @click.option("--break-it", "break_it", is_flag=True, hidden=True) @@ -788,6 +877,8 @@ def quickstart( no_break: bool, verbose: bool, more: bool, + own: bool, + url: Optional[str], headed: bool, headless: bool, break_it: bool, @@ -814,6 +905,11 @@ def quickstart( _quickstart_more(out, app) return _require_supported_python() + if url is not None and not own: + raise click.UsageError("--url works with --own.") + if own: + _quickstart_own(_quickstart_root(out), url, watch or headed) + return _refuse_unknown_tutorial_options(command_ctx.args) openemr = _openemr_checkout(command_ctx.args) if app == "openemr" else None root = _quickstart_root(out) @@ -1533,6 +1629,26 @@ def flow(command_ctx: click.Context) -> None: ) +@main.command( + "login", + context_settings={ + "ignore_unknown_options": True, + "allow_extra_args": True, + "help_option_names": [], + }, +) +@click.pass_context +def login(command_ctx: click.Context) -> None: + """Sign in to OpenAdapt Cloud: `openadapt login` (same as `setup login`). + + Every argument passes to `openadapt-flow login` unchanged. After a + successful sign-in, Seals this computer published are claimed into your + workspace when Cloud supports it. + """ + _require_supported_python() + _run_flow(["login", *command_ctx.args]) + + @main.command( "pull", context_settings={ @@ -2024,7 +2140,8 @@ def seal(command_ctx: click.Context) -> None: [RUN_DIR]` uploads the run's public Seal (counts, outcomes and digests only) after you say yes and prints its link; `openadapt seal unpublish RUN_DIR` takes it down, and `openadapt seal verify ` checks a hosted - Seal's signature here. Also `openadapt seal keys pin` to pin Cloud's Seal + Seal's signature here. `openadapt seal claim` puts the Seals you published + in your Cloud workspace after `openadapt login` (login does it for you). Also `openadapt seal keys pin` to pin Cloud's Seal keys after a person confirms them. Every other argument passes to `openadapt-agent seal` unchanged. """ @@ -2036,6 +2153,8 @@ def seal(command_ctx: click.Context) -> None: sys.exit(_publish_seal(args[1:])) if args[:1] == ["unpublish"]: sys.exit(_unpublish_seal(args[1:])) + if args[:1] == ["claim"]: + sys.exit(_claim_seals(args[1:])) if len(args) >= 2 and args[0] == "verify" and _is_seal_link(args[1]): sys.exit(_verify_seal_link(args[1], args[2:])) if len(args) >= 2 and args[0] == "verify" and Path(args[1]).is_dir(): @@ -2254,6 +2373,73 @@ def _publish_seal(argv: list[str]) -> int: return 0 +def _claim_seals(argv: list[str]) -> int: + """`openadapt seal claim [RUN_DIR...]`: claim published Seals into your workspace.""" + from openadapt.seal_claim import claim_published, claims_live + from openadapt.seal_publish import host_of, urllib_transport + + parser = argparse.ArgumentParser( + prog="openadapt seal claim", + description=( + "Claim the Seals this computer published into the Cloud workspace " + "you signed in to with `openadapt login`, so they show on the " + "dashboard. The proof is a signature by this computer's Seal key; " + "the delete token is never sent. `openadapt login` does this for " + "you. Name run folders (or a quickstart folder) to include Seals " + "published by an older openadapt." + ), + allow_abbrev=False, + ) + parser.add_argument( + "run_dirs", nargs="*", type=Path, help="published run folders to include" + ) + parser.add_argument("--host", default=None, help="the Cloud you signed in to") + parser.add_argument( + "--destination-kind", + default=None, + help="as for `openadapt login`: the trust class of --host", + ) + parser.add_argument( + "--trusted-host", + action="append", + default=None, + help="as for `openadapt login`: an allowlisted customer origin", + ) + options = parser.parse_args(argv) + try: + from openadapt_flow.hosted import HostedError, resolve_host, resolve_token + except ImportError: + click.echo("This openadapt-flow cannot sign in to Cloud.", err=True) + return 1 + from openadapt.seal_claim import check_destination + + try: + origin = resolve_host(options.host) + check_destination( + origin, + destination_kind=options.destination_kind, + trusted_hosts=options.trusted_host, + ) + token = resolve_token(None, host=origin) + except HostedError as exc: + click.echo(f"Not claimed: {exc}", err=True) + click.echo(f"Sign in first: {_hint('login')}", err=True) + return 1 + if not claims_live(origin, transport=urllib_transport): + click.echo(f"{host_of(origin)} does not take Seal claims yet.", err=True) + return 1 + try: + return claim_published( + origin, + token, + run_dirs=[p.expanduser() for p in options.run_dirs], + transport=urllib_transport, + ) + except Exception as exc: # noqa: BLE001 - e.g. no Seal key on this computer + click.echo(f"Not claimed: {type(exc).__name__}: {exc}", err=True) + return 1 + + def _unpublish_seal(argv: list[str]) -> int: """`openadapt seal unpublish RUN_DIR`: delete the hosted Seal.""" from openadapt.seal_publish import ( diff --git a/openadapt/quickstart/own.py b/openadapt/quickstart/own.py new file mode 100644 index 0000000000..8a4ed005bf --- /dev/null +++ b/openadapt/quickstart/own.py @@ -0,0 +1,312 @@ +"""``openadapt quickstart --own``: your own task, from recording to a tool. + +The demo quickstart shows OpenAdapt on a task it brings. This path is the +next step: you record a task once, OpenAdapt compiles it into a program, +runs it with two new inputs and checks each save, and the run ends with +what to do with the program. + +1. **Record.** In the bundled sample app (synthetic data, on this computer), + or in your own web app with ``--url``. Recording yourself opens a browser + window, so it happens only after you say yes at a terminal with a screen. + Without one, OpenAdapt records the sample task itself in a hidden browser + and says so. ``--url`` always needs you, so without a screen it stops with + one line. +2. **Compile** the recording into a program. Healthy runs make no model calls. +3. **Run** it twice with new inputs, hidden (``--watch`` shows the window). + Each run reads the save back from the app's records and gets a receipt. +4. **Share** (sample app only). One y/N question, default No, uploads the two + runs' signed summaries; if you're signed in, they're claimed into your + workspace. Nothing is uploaded without that yes. +5. **Next.** Give your agent the program as an MCP tool, or publish a program + as an API endpoint. + +Every effect goes through an injected engine, ``ask`` and ``say``, so tests +drive the whole path without a browser or a network. +""" + +from __future__ import annotations + +import contextlib +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Optional + +#: The two new inputs for the sample app's runs (synthetic notes). +OWN_NOTES = ( + "Synthetic note: follow-up call booked for Tuesday", + "Synthetic note: lab results reviewed, no change", +) +#: Cloud's guide for publishing a program as an endpoint; publish prints the +#: endpoint and a curl example (Cloud's dashboardNextStep.ts uses the same). +WRAP_PUBLISH_GUIDE_URL = ( + "https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/" + "WRAP_PUBLISH.md" +) +YES = ("y", "yes") + + +class OwnTaskError(RuntimeError): + """A reason the own-task path stopped, in one plain line.""" + + +@dataclass +class OwnResult: + bundle_dir: Path + runs: list[Any] = field(default_factory=list) + link: Optional[str] = None + claimed: bool = False + + +def _answer(ask: Callable[[str], str], prompt: str) -> bool: + try: + return ask(prompt).strip().lower() in YES + except EOFError: + return False + + +class SampleApp: + """The sample app and the engine around it: the demo's own FlowEngine.""" + + def __init__(self, root: Path, *, visible: bool) -> None: + from openadapt.quickstart.engine import FlowEngine + + self.engine = FlowEngine(root, visible=visible) + + def __enter__(self) -> "SampleApp": + self.engine.__enter__() + return self + + def __exit__(self, *exc: object) -> None: + self.engine.__exit__(*exc) + + @property + def bundle_dir(self) -> Path: + return self.engine.bundle_dir + + @property + def app_url(self) -> Optional[str]: + return self.engine._base_url + + def record_yourself(self) -> None: + from openadapt_flow.tutorial import record_tutorial_interactive + + assert self.engine._base_url is not None + record_tutorial_interactive(self.engine._base_url, self.engine.recording_dir) + + def record_for_you(self, on_step: Callable[[Any], None]) -> None: + self.engine.record(on_step) + + def compile(self) -> int: + return self.engine.compile() + + def run(self, index: int, note: str) -> Any: + return self.engine.run(index, note, folder=f"own-run-{index}") + + def seal(self, runs: list[Any]) -> Any: + return self.engine.seal(runs) + + +def run_own( + root: Path, + *, + url: Optional[str] = None, + visible: bool = False, + can_record_here: bool, + ask: Callable[[str], str], + say: Callable[[str], None], + hint: Callable[[str], str], + quote: Callable[[Path], str], + sample_factory: Callable[..., Any] = SampleApp, + own_app: Optional[Callable[..., OwnResult]] = None, + share: Optional[Callable[[list[Path]], tuple[Optional[str], bool]]] = None, +) -> OwnResult: + """Run the own-task path; returns what it made. Raises OwnTaskError.""" + if url is not None: + if not can_record_here: + raise OwnTaskError( + "Recording your own app opens a browser window, and this " + "terminal has no screen. Run it on a computer with one." + ) + if own_app is None: + own_app = record_own_app + result = own_app(root, url=url, visible=visible, ask=ask, say=say) + _ending(result, say=say, hint=hint, quote=quote, app_url=url) + return result + + say("Your own task, in the sample app (synthetic data, on this computer).") + with sample_factory(root, visible=visible) as app: + say("") + say("1. Record the task once") + if can_record_here and _answer( + ask, " Do it yourself in a browser window? [y/N] " + ): + app.record_yourself() + else: + say(" OpenAdapt does it once in a hidden browser:") + app.record_for_you(lambda step: say(f" {step.label}")) + steps = app.compile() + say("") + say(f"2. Compiled into a {steps}-step program. Runs make no AI model calls.") + say("") + say("3. Run it with two new inputs") + runs = [] + for index, note in enumerate(OWN_NOTES, start=1): + run = app.run(index, note) + runs.append(run) + say(f' "{note}"') + say( + f" {run.plain_label}: {run.effects_confirmed} of " + f"{run.effects_required} record checks, {run.model_calls} model calls" + ) + app.seal(runs) + result = OwnResult(bundle_dir=app.bundle_dir, runs=runs) + app_url = app.app_url + if share is not None and all(getattr(r, "checked", False) for r in runs): + say("") + say("4. Share the runs") + result.link, result.claimed = share([Path(r.run_dir) for r in runs]) + _ending(result, say=say, hint=hint, quote=quote, app_url=app_url, sample=True) + return result + + +def record_own_app( + root: Path, + *, + url: str, + visible: bool, + ask: Callable[[str], str], + say: Callable[[str], None], + params: tuple[str, ...] = (), + script: Optional[Callable[[Any, Callable[[], None]], None]] = None, +) -> OwnResult: + """Record a task in your own web app, compile it and run it once. + + ``script`` drives the recording headless (tests); otherwise a browser + window opens on ``url`` after a yes, and the recording ends when you + close it. + """ + from openadapt_flow.compiler import compile_recording + from openadapt_flow.interactive_recorder import record_interactive + + recording_dir = root / "recording" + bundle_dir = root / "bundle" + say(f"Your own task, in {url}.") + say("") + say("1. Record the task once") + if script is None: + if not _answer( + ask, + " A browser window opens on your app. Do the task once, then " + "close the window. Open it? [y/N] ", + ): + raise OwnTaskError("Not recorded: no window was opened.") + root.mkdir(parents=True, exist_ok=True) + record_interactive( + url, + recording_dir, + param_fields=params, + headless=script is not None, + script=script, + ) + workflow = compile_recording(recording_dir, bundle_dir, name="own-task") + say("") + say( + f"2. Compiled into a {len(workflow.steps)}-step program. " + "Runs make no AI model calls." + ) + return OwnResult(bundle_dir=bundle_dir) + + +def _ending( + result: OwnResult, + *, + say: Callable[[str], None], + hint: Callable[[str], str], + quote: Callable[[Path], str], + app_url: Optional[str], + sample: bool = False, +) -> None: + serve = ( + f"agent serve --bundles {quote(result.bundle_dir)} --mode production " + "--allow-run" + ) + if not sample and app_url: + serve += f" --url {app_url}" + say("") + say("Next: put your program to work") + say(" Give your agent this program as a tool:") + say(f" claude mcp add openadapt -- {hint(serve)}") + if sample: + say( + " The sample app runs only during the quickstart. With your own " + "app the tool works any time:" + ) + say(f" {hint('quickstart --own --url https://your-app.example')}") + say(" Or publish a program as an API endpoint. Publishing prints the") + say(" endpoint and a curl example, and each call returns a receipt:") + say(f" {WRAP_PUBLISH_GUIDE_URL}") + if result.link: + say(f" Your runs: {result.link}") + elif sample: + say( + f" Keep the runs in your workspace: {hint('login')}, then " + f"{hint('seal publish')} for each run folder." + ) + + +def share_runs( + run_dirs: list[Path], + *, + ask: Callable[[str], str], + say: Callable[[str], None], + command: Callable[[str], str], +) -> tuple[Optional[str], bool]: + """Offer the runs' Seals (one y/N, default No), then claim them if signed in. + + Returns the link (or None when nothing was sent) and whether the runs are + now in a workspace. Never raises: the runs already worked.""" + from openadapt import seal_claim, seal_publish + + try: + origin = seal_publish.endpoint() + if not seal_publish.hosted_seals_live(origin): + say( + " Sharing is not available right now; the runs stay on this computer." + ) + return None, False + link = seal_publish.publish_quickstart( + run_dirs, ask=ask, say=say, command=command + ) + except seal_publish.PublishError as exc: + say(f" {exc}") + return None, False + if link is None: + return None, False + with contextlib.suppress(Exception): + from openadapt_flow.hosted import resolve_host, resolve_token + + if resolve_host(None) == origin: + token = resolve_token(None, host=origin) + seal_claim.check_destination(origin) + if seal_claim.claims_live(origin, transport=seal_publish.urllib_transport): + code = seal_claim.claim_published( + origin, + token, + transport=seal_publish.urllib_transport, + say=lambda line: say(f" {line}"), + automatic=True, + quiet_when_none=True, + ) + return link, code == 0 + say(f" Sign in to keep them in your workspace: {command('login')}") + return link, False + + +__all__ = [ + "OWN_NOTES", + "OwnResult", + "OwnTaskError", + "record_own_app", + "run_own", + "share_runs", +] diff --git a/openadapt/seal_claim.py b/openadapt/seal_claim.py new file mode 100644 index 0000000000..44134f682a --- /dev/null +++ b/openadapt/seal_claim.py @@ -0,0 +1,518 @@ +"""Claim published Seals into your Cloud workspace: ``openadapt seal claim``. + +``openadapt seal publish`` and the quickstart upload Seals anonymously: Cloud +stores each one with no account. After ``openadapt login``, this module +claims the Seals this computer published into the signed-in workspace, so +they show on the dashboard. + +The proof is a signature by the Seal key that signed them, over bytes that +name the Cloud origin, a five-minute challenge Cloud minted for this +workspace and ingest token, and each Seal's id and digest (Cloud's +``src/lib/localSealClaims.ts``). Nothing new is trusted: only the key in a +Seal can claim it. The delete token in ``seal.publish.json`` is never sent. + +Which Seals: each upload is noted in ``published-seals.json`` next to the +Seal key (``~/.openadapt/seal``, or ``$OPENADAPT_SEAL_HOME``), mode 0600, +holding the id, the origin, the digest and the run folder. Only Seals +published to the Cloud you signed in to and signed by this computer's +current key are claimed. ``openadapt seal claim RUN_DIR...`` also takes run +folders (or a quickstart folder) published before that note existed. + +Every network call goes through :data:`openadapt.seal_publish.Transport`. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import stat +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Mapping, Optional + +from openadapt.seal_publish import ( + _ID, + PUBLISH_FILE, + STATUS_TIMEOUT_S, + PublishError, + Transport, + host_of, + read_record, +) + +INDEX_FILE = "published-seals.json" +#: The quickstart's Seals: the only ones claimed without being asked. +TUTORIAL = "synthetic-tutorial" +SCHEMA = "openadapt.local-seal-claim/v1" +_DOMAIN = (SCHEMA + "\0").encode("utf-8") +STATUS_PATH = "/api/local-seal-claims/status" +CHALLENGE_PATH = "/api/local-seal-claims/challenge" +CLAIM_PATH = "/api/local-seal-claims" +#: Cloud accepts at most this many ids in one claim. +MAX_PER_CLAIM = 8 +_SHA256 = len(hashlib.sha256().hexdigest()) + + +class SealsGone(PublishError): + """Cloud no longer has these Seals (taken down, or never there).""" + + def __init__(self, seal_ids: list[str]) -> None: + super().__init__("Not claimed: a Seal is no longer online.") + self.seal_ids = seal_ids + + +@dataclass(frozen=True) +class Claimable: + id: str + origin: str + seal_sha256: str + key_id: str + run_dir: Optional[str] = None + provenance: Optional[str] = None + + +def canonical(value: Any) -> bytes: + """Sorted-key compact JSON, as Cloud's canonicalJson writes it.""" + return json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=False + ).encode("utf-8") + + +def seal_sha256(seal: Mapping[str, Any]) -> str: + """The digest Cloud stores for a Seal: SHA-256 of its canonical JSON.""" + return hashlib.sha256(canonical(dict(seal))).hexdigest() + + +def claim_payload(origin: str, challenge: str, seals: list[Claimable]) -> bytes: + """The exact bytes the Seal key signs: a domain tag, then canonical JSON.""" + return _DOMAIN + canonical( + { + "schema": SCHEMA, + "origin": origin, + "challenge": challenge, + "seals": [{"id": s.id, "seal_sha256": s.seal_sha256} for s in seals], + } + ) + + +# -- the local note of published Seals ----------------------------------------- + + +def _home(home: Optional[Path]) -> Path: + if home is not None: + return home + from openadapt_flow.offline_seal import seal_home + + return seal_home() + + +def read_index(home: Optional[Path] = None) -> list[dict[str, Any]]: + try: + data = json.loads((_home(home) / INDEX_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError, ImportError): + return [] + entries = data.get("seals") if isinstance(data, dict) else None + return ( + [e for e in entries if isinstance(e, dict)] if isinstance(entries, list) else [] + ) + + +def _write_index(folder: Path, entries: list[dict[str, Any]]) -> Path: + folder.mkdir(parents=True, exist_ok=True) + path = folder / INDEX_FILE + tmp = path.with_name(path.name + ".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(json.dumps({"seals": entries}, indent=2, sort_keys=True) + "\n") + os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR) + os.replace(tmp, path) + return path + + +def remember( + run_dir: Path, + record: Mapping[str, Any], + doc: Mapping[str, Any], + origin: str, + *, + home: Optional[Path] = None, +) -> Optional[Path]: + """Note an upload so ``login`` can claim it. Never raises: publishing + already succeeded, and a missing note only means no automatic claim.""" + try: + folder = _home(home) + entry = { + "id": str(record["id"]), + "origin": origin, + "seal_sha256": seal_sha256(doc["seal"]), + "key_id": str(doc["seal"]["key_id"]), + "run_dir": str(Path(run_dir).resolve()), + "provenance": (doc.get("card") or {}).get("provenance"), + } + entries = [e for e in read_index(folder) if e.get("id") != entry["id"]] + entries.append(entry) + return _write_index(folder, entries) + except Exception: # noqa: BLE001 - see docstring + return None + + +def mark_claimed(seal_ids: list[str], *, home: Optional[Path] = None) -> None: + """Note that Cloud holds these Seals for a workspace, so the next login + does not claim them again. Never raises.""" + try: + folder = _home(home) + entries = read_index(folder) + for entry in entries: + if entry.get("id") in set(seal_ids): + entry["claimed"] = True + _write_index(folder, entries) + except Exception: # noqa: BLE001 - the note is a convenience + return + + +def forget(seal_ids: list[str], *, home: Optional[Path] = None) -> None: + """Drop Seals that were taken down (or are gone) from the note. Never raises.""" + try: + folder = _home(home) + entries = read_index(folder) + kept = [e for e in entries if e.get("id") not in set(seal_ids)] + if len(kept) != len(entries): + _write_index(folder, kept) + except Exception: # noqa: BLE001 - the note is a convenience + return + + +def _from_run_dir(run_dir: Path) -> Optional[Claimable]: + """A published run folder's Seal, from seal.publish.json and public-seal.json.""" + record = read_record(run_dir) + if not record or not _ID.match(str(record.get("id", ""))): + return None + try: + doc = json.loads((run_dir / "public-seal.json").read_text(encoding="utf-8")) + seal = doc["seal"] + from urllib.parse import urlsplit + + url = urlsplit(str(record.get("url", ""))) + origin = f"{url.scheme}://{url.netloc}" + return Claimable( + id=str(record["id"]), + origin=origin, + seal_sha256=seal_sha256(seal), + key_id=str(seal["key_id"]), + run_dir=str(run_dir.resolve()), + provenance=(doc.get("card") or {}).get("provenance"), + ) + except (OSError, ValueError, KeyError, TypeError): + return None + + +def _run_dirs(paths: list[Path]) -> list[Path]: + """Each path, or the run folders inside it that were published.""" + out: list[Path] = [] + for path in paths: + if (path / PUBLISH_FILE).is_file(): + out.append(path) + continue + try: + out += sorted(p for p in path.iterdir() if (p / PUBLISH_FILE).is_file()) + except OSError: + continue + return out + + +def find_claimable( + origin: str, + key_id: str, + *, + run_dirs: Optional[list[Path]] = None, + home: Optional[Path] = None, + automatic: bool = False, +) -> tuple[list[Claimable], int]: + """Seals published to ``origin`` and signed by ``key_id``, oldest first. + + ``automatic`` (the claim after login) takes only quickstart Seals + (provenance ``synthetic-tutorial``) not claimed before; any other Seal is + claimed only by an explicit ``openadapt seal claim``. + + Returns the Seals and how many published to ``origin`` were skipped + because another key signed them (a key replaced since).""" + found: dict[str, Claimable] = {} + for entry in read_index(home): + if automatic and (entry.get("claimed") or entry.get("provenance") != TUTORIAL): + continue + try: + item = Claimable( + id=str(entry["id"]), + origin=str(entry["origin"]).rstrip("/"), + seal_sha256=str(entry["seal_sha256"]), + key_id=str(entry["key_id"]), + run_dir=entry.get("run_dir"), + provenance=entry.get("provenance"), + ) + except KeyError: + continue + if _ID.match(item.id) and len(item.seal_sha256) == _SHA256: + found.setdefault(item.id, item) + for run_dir in _run_dirs(run_dirs or []): + item = _from_run_dir(run_dir) + if item is not None: + found.setdefault(item.id, item) + here = [s for s in found.values() if s.origin == origin.rstrip("/")] + mine = [s for s in here if s.key_id == key_id] + return mine, len(here) - len(mine) + + +# -- talking to Cloud ---------------------------------------------------------- + + +def claims_live( + origin: str, + *, + transport: Transport, + timeout_s: float = STATUS_TIMEOUT_S, +) -> bool: + """True only when Cloud's claim status route answers 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 + + answer: list[Any] = [] + + def ask() -> None: + try: + answer.append( + transport( + "GET", origin + STATUS_PATH, None, {"Accept": "application/json"} + ) + ) + except Exception: # noqa: BLE001 - any failure means "no" + pass + + worker = threading.Thread(target=ask, name="seal-claim-status", daemon=True) + worker.start() + worker.join(timeout_s) + if not answer or answer[0].status != 200: + return False + return _json(answer[0].body) == {"enabled": True} + + +def _json(body: bytes) -> dict[str, Any]: + try: + data = json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def claim( + seals: list[Claimable], + *, + origin: str, + token: str, + sign: Callable[[bytes], bytes], + transport: Transport, +) -> int: + """Claim ``seals`` (at most :data:`MAX_PER_CLAIM`, one key) in one request. + + Returns how many Cloud now holds for this workspace. Raises + :class:`PublishError` with one plain line otherwise.""" + if not seals: + return 0 + seals = seals[:MAX_PER_CLAIM] + auth = { + "Authorization": f"Bearer {token}", + "Accept": "application/json", + "Content-Type": "application/json", + } + try: + answer = transport("POST", origin + CHALLENGE_PATH, b"{}", auth) + except OSError as exc: + raise PublishError(f"Not claimed: could not reach {host_of(origin)} ({exc}).") + if answer.status == 401: + raise PublishError("Not claimed: Cloud did not accept this computer's sign-in.") + challenge = _json(answer.body).get("challenge") + if answer.status != 200 or not isinstance(challenge, str): + raise PublishError(f"Not claimed: Cloud answered HTTP {answer.status}.") + signature = base64.b64encode(sign(claim_payload(origin, challenge, seals))) + body = json.dumps( + { + "challenge": challenge, + "seal_ids": [s.id for s in seals], + "signature": signature.decode("ascii"), + } + ).encode("utf-8") + try: + answer = transport("POST", origin + CLAIM_PATH, body, auth) + except OSError as exc: + raise PublishError(f"Not claimed: could not reach {host_of(origin)} ({exc}).") + if answer.status == 200: + return len(seals) + if answer.status == 404: + ids = {s.id for s in seals} + missing = _json(answer.body).get("missing") + if isinstance(missing, list) and missing and set(missing) <= ids: + raise SealsGone([str(m) for m in missing]) + reasons = { + 404: "a Seal is no longer online", + 409: "another workspace already claimed one of these Seals", + 403: "the signature did not match the Seal key", + } + reason = reasons.get(answer.status, f"Cloud answered HTTP {answer.status}") + raise PublishError(f"Not claimed: {reason}.") + + +def _claim( + seals: list[Claimable], origin: str, token: str, signer: Any, transport: Transport +) -> int: + return claim( + seals, origin=origin, token=token, sign=signer.sign, transport=transport + ) + + +def _signer() -> Any: + from openadapt_flow.offline_seal import seal_home, signer_for + + return signer_for(seal_home()) + + +def claim_published( + origin: str, + token: str, + *, + run_dirs: Optional[list[Path]] = None, + transport: Transport, + signer: Any = None, + home: Optional[Path] = None, + say: Callable[[str], None] = print, + quiet_when_none: bool = False, + automatic: bool = False, +) -> int: + """Find this computer's published Seals for ``origin`` and claim them. + + Returns 0 on success (including nothing to claim), 1 on a refusal.""" + signer = signer or _signer() + seals, other_key = find_claimable( + origin, + signer.key_id, + run_dirs=run_dirs, + home=home, + automatic=automatic, + ) + if other_key: + say( + f"Skipped {other_key} published Seal{'s' if other_key != 1 else ''} " + "signed by a different Seal key than this computer's." + ) + if not seals: + if not quiet_when_none: + say(f"No published Seals to claim on {host_of(origin)}.") + return 0 + claimed: list[str] = [] + gone: list[str] = [] + try: + for start in range(0, len(seals), MAX_PER_CLAIM): + batch = seals[start : start + MAX_PER_CLAIM] + try: + _claim(batch, origin, token, signer, transport) + except SealsGone as exc: + # Drop the Seals Cloud no longer has, then claim the rest once. + gone += exc.seal_ids + batch = [s for s in batch if s.id not in exc.seal_ids] + if batch: + _claim(batch, origin, token, signer, transport) + claimed += [s.id for s in batch] + except PublishError as exc: + say(str(exc)) + return 1 + finally: + if gone: + forget(gone, home=home) + if claimed: + mark_claimed(claimed, home=home) + if gone: + say( + f"Skipped {len(gone)} Seal{'s' if len(gone) != 1 else ''} that " + f"{'are' if len(gone) != 1 else 'is'} no longer online." + ) + if not claimed: + return 0 + what = ( + "Your published run is" + if len(claimed) == 1 + else f"Your {len(claimed)} published runs are" + ) + say(f"{what} in your workspace: {origin}/dashboard") + return 0 + + +def check_destination( + origin: str, + *, + destination_kind: Optional[str] = None, + trusted_hosts: Optional[list[str]] = None, +) -> None: + """Apply the same destination rule ``login`` applies before a token is + sent. Raises the engine's ``HostedError`` when ``origin`` is not trusted.""" + from openadapt_flow.hosted import resolve_destination_policy + + resolve_destination_policy( + origin, destination_kind=destination_kind, trusted_hosts=trusted_hosts + ) + + +def after_login( + host: Optional[str] = None, + *, + destination_kind: Optional[str] = None, + trusted_hosts: Optional[list[str]] = None, + transport: Optional[Transport] = None, + say: Callable[[str], None] = print, +) -> None: + """Run after ``openadapt login`` succeeds: claim the quickstart's Seals. + + Silent unless Cloud takes claims and there is a quickstart Seal not yet + claimed; never raises, so login's result stands. The token goes only to + the host login used, under the same destination rule.""" + try: + from openadapt_flow.hosted import resolve_host, resolve_token + + from openadapt.seal_publish import _module_transport + + origin = resolve_host(host) + check_destination( + origin, destination_kind=destination_kind, trusted_hosts=trusted_hosts + ) + sender = transport or _module_transport() + if not claims_live(origin, transport=sender): + return + signer = _signer() + if not find_claimable(origin, signer.key_id, automatic=True)[0]: + return + claim_published( + origin, + resolve_token(None, host=origin), + transport=sender, + signer=signer, + say=say, + quiet_when_none=True, + automatic=True, + ) + except Exception: # noqa: BLE001 - claiming is a convenience after login + return + + +__all__ = [ + "Claimable", + "after_login", + "claim", + "claim_payload", + "claim_published", + "check_destination", + "claims_live", + "find_claimable", + "read_index", + "remember", + "seal_sha256", +] diff --git a/openadapt/seal_publish.py b/openadapt/seal_publish.py index 6f42326b75..f19993ec82 100644 --- a/openadapt/seal_publish.py +++ b/openadapt/seal_publish.py @@ -417,6 +417,10 @@ def upload( "delete_token": token, } _write_record(run_dir, record) + # Noted next to the Seal key, so `openadapt login` can claim it later. + from openadapt.seal_claim import remember + + remember(run_dir, record, doc, origin) return record @@ -444,6 +448,9 @@ def unpublish(run_dir: Path, *, origin: Optional[str], transport: Transport) -> ) if response.status in (204, 410): (run_dir / PUBLISH_FILE).unlink(missing_ok=True) + from openadapt.seal_claim import forget + + forget([seal_id]) if response.status == 204: return f"Unpublished. {link_for(origin, seal_id)} no longer shows the Seal." return f"Already gone: {link_for(origin, seal_id)} shows no Seal." diff --git a/tests/test_quickstart_own.py b/tests/test_quickstart_own.py new file mode 100644 index 0000000000..e6fb6beb57 --- /dev/null +++ b/tests/test_quickstart_own.py @@ -0,0 +1,300 @@ +"""`openadapt quickstart --own`: record, compile, two new runs, share, next steps. + +The engine, the questions and sharing are fakes, so no browser, sample app +or network is used, except in the one test that records through the real +interactive recorder in a headless browser. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +import pytest +from click.testing import CliRunner + +from openadapt import cli +from openadapt.quickstart import own +from openadapt.quickstart.own import OWN_NOTES, OwnTaskError, run_own + + +@dataclass +class Step: + label: str + + +@dataclass +class Run: + run_dir: Path + note: str + checked: bool = True + plain_label: str = "Done and checked" + effects_confirmed: int = 2 + effects_required: int = 2 + model_calls: int = 0 + + +class FakeSample: + def __init__(self, root: Path, *, visible: bool) -> None: + self.root = root + self.visible = visible + self.calls: list[str] = [] + FakeSample.last = self + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.calls.append("closed") + + bundle_dir = Path("/tmp/oa/bundle") + app_url = "http://127.0.0.1:5000" + + def record_yourself(self): + self.calls.append("record_yourself") + + def record_for_you(self, on_step): + self.calls.append("record_for_you") + on_step(Step("Click Save")) + + def compile(self): + self.calls.append("compile") + return 6 + + def run(self, index, note): + self.calls.append(f"run {index}") + return Run(self.root / f"own-run-{index}", note) + + def seal(self, runs): + self.calls.append("seal") + + +def _go(tmp_path, *, answers=(), can_record_here=False, share=None, url=None): + lines: list[str] = [] + asked: list[str] = [] + queue = list(answers) + + def ask(prompt): + asked.append(prompt) + if not queue: + raise EOFError + return queue.pop(0) + + result = run_own( + tmp_path, + url=url, + can_record_here=can_record_here, + ask=ask, + say=lines.append, + hint=lambda rest: f"openadapt {rest}", + quote=str, + sample_factory=FakeSample, + share=share, + ) + return result, "\n".join(lines), asked + + +def test_without_a_screen_openadapt_records_the_sample_and_asks_nothing(tmp_path): + result, out, asked = _go(tmp_path) + assert asked == [] + assert FakeSample.last.calls == [ + "record_for_you", + "compile", + "run 1", + "run 2", + "seal", + "closed", + ] + assert FakeSample.last.visible is False + assert "OpenAdapt does it once in a hidden browser" in out + assert [r.note for r in result.runs] == list(OWN_NOTES) + assert "6-step program" in out + + +def test_a_window_opens_only_after_a_yes_at_a_screen(tmp_path): + _go(tmp_path, can_record_here=True, answers=["n"]) + assert "record_for_you" in FakeSample.last.calls + _go(tmp_path, can_record_here=True, answers=[""]) + assert "record_for_you" in FakeSample.last.calls + _, _, asked = _go(tmp_path, can_record_here=True, answers=["y"]) + assert FakeSample.last.calls[0] == "record_yourself" + assert "browser window" in asked[0] + + +def test_the_ending_names_a_working_mcp_command_and_the_publish_guide(tmp_path): + _, out, _ = _go(tmp_path) + assert ( + "claude mcp add openadapt -- openadapt agent serve --bundles " + "/tmp/oa/bundle --mode production --allow-run" + ) in out + assert own.WRAP_PUBLISH_GUIDE_URL in out + assert "openadapt login" in out # nothing was shared, so how to keep them + + +def test_sharing_is_offered_only_when_both_runs_checked(tmp_path, monkeypatch): + shared: list = [] + + def share(run_dirs): + shared.append(run_dirs) + return "https://cloud.test/seal#a,b", True + + result, out, _ = _go(tmp_path, share=share) + assert shared == [[tmp_path / "own-run-1", tmp_path / "own-run-2"]] + assert result.link == "https://cloud.test/seal#a,b" and result.claimed + assert "Your runs: https://cloud.test/seal#a,b" in out + + shared.clear() + monkeypatch.setattr( + FakeSample, + "run", + lambda self, index, note: Run( + self.root / f"own-run-{index}", note, checked=False + ), + ) + _go(tmp_path, share=share) + assert shared == [] + + +def test_own_app_needs_a_screen_and_says_so_in_one_line(tmp_path): + with pytest.raises(OwnTaskError, match="no screen"): + _go(tmp_path, url="https://app.example") + + +def test_own_app_ending_targets_that_app(tmp_path, monkeypatch): + def fake_own_app(root, *, url, visible, ask, say): + say(f"recorded {url}") + return own.OwnResult(bundle_dir=root / "bundle") + + lines: list[str] = [] + run_own( + tmp_path, + url="https://app.example", + can_record_here=True, + ask=lambda _p: "y", + say=lines.append, + hint=lambda rest: f"openadapt {rest}", + quote=str, + own_app=fake_own_app, + ) + out = "\n".join(lines) + assert ( + f"--bundles {tmp_path / 'bundle'} --mode production --allow-run --url https://app.example" + in out + ) + assert "sample app" not in out + + +def test_own_app_recording_without_a_yes_opens_nothing(tmp_path, monkeypatch): + opened: list = [] + monkeypatch.setattr( + "openadapt_flow.interactive_recorder.record_interactive", + lambda *a, **k: opened.append(a), + ) + with pytest.raises(OwnTaskError, match="no window"): + own.record_own_app( + tmp_path, + url="https://app.example", + visible=False, + ask=lambda _p: "", + say=print, + ) + assert opened == [] + + +def test_cli_routes_own_and_refuses_url_without_it(monkeypatch, tmp_path): + seen: list = [] + monkeypatch.setattr( + cli, "_quickstart_own", lambda root, url, watch: seen.append((root, url, watch)) + ) + runner = CliRunner() + result = runner.invoke( + cli.main, ["quickstart", "--own", "--out", str(tmp_path / "q")] + ) + assert result.exit_code == 0, result.output + assert seen == [(tmp_path / "q", None, False)] + result = runner.invoke(cli.main, ["quickstart", "--url", "https://app.example"]) + assert result.exit_code == 2 + assert "--url works with --own" in result.output + + +def test_share_runs_never_raises_and_asks_before_any_upload(monkeypatch, tmp_path): + from openadapt import seal_publish + + monkeypatch.setattr(seal_publish, "hosted_seals_live", lambda origin: True) + sent: list = [] + monkeypatch.setattr( + seal_publish, + "publish_quickstart", + lambda run_dirs, *, ask, say, command: ( + sent.append(ask("Publish? [y/N] ")) or None + ), + ) + lines: list[str] = [] + link, claimed = own.share_runs( + [tmp_path], ask=lambda _p: "n", say=lines.append, command=lambda r: r + ) + assert (link, claimed) == (None, False) + assert sent == ["n"] + + def refuse(*_a, **_k): + raise seal_publish.PublishError("Not published: the service is busy.") + + monkeypatch.setattr(seal_publish, "publish_quickstart", refuse) + assert own.share_runs( + [tmp_path], ask=lambda _p: "y", say=lines.append, command=str + ) == (None, False) + assert "Not published: the service is busy." in lines[-1] + + +@pytest.mark.timeout(600) +def test_own_app_records_through_the_real_recorder_and_compiles(tmp_path): + """The --url path end to end in a headless browser: the real capture + listeners watch a scripted user in the bundled sample app, then compile.""" + pytest.importorskip("playwright") + from openadapt_flow.mockmed.server import serve + + def drive(page, pump): + def click(selector): + page.wait_for_selector(selector, state="visible", timeout=20000) + page.click(selector) + pump() + pump() + + click("#username") + page.keyboard.type("nurse.demo") + pump() + click("#password") + page.keyboard.type("synthetic-password") + pump() + click("#signin") + click(".open-btn") + click("#new-encounter") + click("#type-triage") + click("#note") + page.keyboard.type("Synthetic note for the own-task test") + pump() + pump() + click("#save-encounter") + for _ in range(4): + pump() + + url, stop = serve(port=0) + lines: list[str] = [] + try: + result = own.record_own_app( + tmp_path, + url=url, + visible=False, + ask=lambda _p: pytest.fail("a scripted recording asks nothing"), + say=lines.append, + params=("note",), + script=drive, + ) + finally: + stop() + assert (result.bundle_dir / "workflow.json").is_file() + assert any("step program" in line for line in lines) + assert ( + "synthetic-password" + not in (tmp_path / "recording" / "events.jsonl").read_text() + ) diff --git a/tests/test_seal_claim.py b/tests/test_seal_claim.py new file mode 100644 index 0000000000..7ca8bc5303 --- /dev/null +++ b/tests/test_seal_claim.py @@ -0,0 +1,425 @@ +"""`openadapt seal claim` and the claim after `openadapt login`. + +A fake Cloud below checks claims the way ``src/lib/localSealClaims.ts`` does: +it mints a challenge, rebuilds the signed bytes from its own stored digests +and verifies the Ed25519 signature under the key in the stored Seal. Real +sockets are blocked. +""" + +from __future__ import annotations + +import base64 +import json +import socket +import stat +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PrivateKey, + Ed25519PublicKey, +) +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat + +from openadapt import cli, seal_claim, seal_publish +from openadapt.seal_claim import Claimable, claim_payload, find_claimable, remember +from openadapt.seal_publish import PublishError, Response + +ORIGIN = "https://cloud.test" +TOKEN = "oai_ingest_" + "x" * 40 + + +def _id(n: int) -> str: + return (f"{n:02d}" + "A" * 43)[:43] + + +class Signer: + def __init__(self) -> None: + self.key = Ed25519PrivateKey.generate() + raw = self.key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + self.public_key = base64.b64encode(raw).decode() + self.key_id = "seal-ed25519-" + "a" * 16 + + def sign(self, payload: bytes) -> bytes: + return self.key.sign(payload) + + +class FakeCloud: + """The claim routes, with stored Seals keyed by id.""" + + def __init__(self, *, enabled: bool = True) -> None: + self.enabled = enabled + self.seals: dict[str, tuple[str, str]] = {} # id -> (public_key, sha256) + self.claims: dict[str, str] = {} # id -> org + self.org = "org-1" + self.calls: list[tuple[str, str, dict]] = [] + + def store(self, seal_id: str, signer: Signer, sha: str) -> None: + self.seals[seal_id] = (signer.public_key, sha) + + def __call__(self, method, url, body, headers): + self.calls.append((method, url, dict(headers))) + path = url[len(ORIGIN) :] + reply = lambda status, data: Response(status, {}, json.dumps(data).encode()) # noqa: E731 + if path == seal_claim.STATUS_PATH: + return reply(200, {"enabled": self.enabled}) + if headers.get("Authorization") != f"Bearer {TOKEN}": + return reply(401, {"error": "unauthorized"}) + if path == seal_claim.CHALLENGE_PATH: + return reply(200, {"challenge": f"v1.challenge-for-{self.org}"}) + if path == seal_claim.CLAIM_PATH: + request = json.loads(body) + ids = request["seal_ids"] + missing = [i for i in ids if i not in self.seals] + if missing: + return reply(404, {"error": "not_found", "missing": missing}) + keys = {self.seals[i][0] for i in ids} + if len(keys) != 1: + return reply(403, {"error": "bad_proof"}) + payload = claim_payload( + ORIGIN, + request["challenge"], + [Claimable(i, ORIGIN, self.seals[i][1], "") for i in ids], + ) + try: + Ed25519PublicKey.from_public_bytes(base64.b64decode(keys.pop())).verify( + base64.b64decode(request["signature"]), payload + ) + except Exception: + return reply(403, {"error": "bad_proof"}) + if any(self.claims.get(i, self.org) != self.org for i in ids): + return reply(409, {"error": "claimed_elsewhere"}) + for i in ids: + self.claims[i] = self.org + return reply(200, {"claimed": len(ids), "already_yours": False}) + return reply(404, {"error": "not_found"}) + + +@pytest.fixture(autouse=True) +def _isolated(monkeypatch, tmp_path): + def refuse(*_args, **_kwargs): + raise AssertionError("a test tried to open a real network connection") + + monkeypatch.setattr(socket.socket, "connect", refuse) + monkeypatch.setattr(socket, "create_connection", refuse) + monkeypatch.setattr(seal_publish, "urllib_transport", refuse) + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(tmp_path / "seal-home")) + + +def _published( + tmp_path: Path, + signer: Signer, + n: int, + origin: str = ORIGIN, + provenance: str = "synthetic-tutorial", +) -> Claimable: + seal = {"key_id": signer.key_id, "public_key": signer.public_key, "n": n} + record = {"id": _id(n), "url": f"{origin}/seal#{_id(n)}", "delete_token": "secret"} + run = tmp_path / f"run-{n}" + run.mkdir(exist_ok=True) + doc = {"seal": seal, "card": {"provenance": provenance}} + remember(run, record, doc, origin, home=tmp_path / "seal-home") + return Claimable(_id(n), origin, seal_claim.seal_sha256(seal), signer.key_id) + + +def test_signed_bytes_match_cloud_exactly(): + # The same vector as tests/unit/local-seal-claims.test.mjs in openadapt-cloud. + payload = claim_payload( + "https://app.openadapt.ai", "v1.x", [Claimable("a", "", "b", "")] + ) + assert payload == ( + b"openadapt.local-seal-claim/v1\x00" + b'{"challenge":"v1.x","origin":"https://app.openadapt.ai",' + b'"schema":"openadapt.local-seal-claim/v1","seals":[{"id":"a","seal_sha256":"b"}]}' + ) + + +def test_publishing_notes_the_seal_privately_without_the_delete_token(tmp_path): + signer = Signer() + _published(tmp_path, signer, 1) + path = tmp_path / "seal-home" / seal_claim.INDEX_FILE + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + text = path.read_text() + assert "secret" not in text + (entry,) = json.loads(text)["seals"] + assert entry["id"] == _id(1) and entry["origin"] == ORIGIN + # Noting the same Seal again keeps one entry. + _published(tmp_path, signer, 1) + assert len(seal_claim.read_index(tmp_path / "seal-home")) == 1 + + +def test_claims_only_this_clouds_seals_signed_by_this_key(tmp_path): + signer, old = Signer(), Signer() + old.key_id = "seal-ed25519-" + "b" * 16 + mine = _published(tmp_path, signer, 1) + _published(tmp_path, old, 2) + _published(tmp_path, signer, 3, origin="https://staging.test") + found, other_key = find_claimable( + ORIGIN, signer.key_id, home=tmp_path / "seal-home" + ) + assert [s.id for s in found] == [mine.id] + assert other_key == 1 + + +def test_claim_sends_a_signature_and_never_the_delete_token(tmp_path): + signer = Signer() + a, b = _published(tmp_path, signer, 1), _published(tmp_path, signer, 2) + cloud = FakeCloud() + cloud.store(a.id, signer, a.seal_sha256) + cloud.store(b.id, signer, b.seal_sha256) + lines: list[str] = [] + code = seal_claim.claim_published( + ORIGIN, + TOKEN, + transport=cloud, + signer=signer, + home=tmp_path / "seal-home", + say=lines.append, + ) + assert code == 0 + assert set(cloud.claims) == {a.id, b.id} + assert lines == [f"Your 2 published runs are in your workspace: {ORIGIN}/dashboard"] + assert all("secret" not in json.dumps(headers) for _, _, headers in cloud.calls) + + +def test_a_wrong_key_or_a_taken_seal_is_one_plain_line(tmp_path): + signer = Signer() + a = _published(tmp_path, signer, 1) + cloud = FakeCloud() + cloud.store(a.id, Signer(), a.seal_sha256) # Cloud holds a different key + lines: list[str] = [] + assert ( + seal_claim.claim_published( + ORIGIN, + TOKEN, + transport=cloud, + signer=signer, + home=tmp_path / "seal-home", + say=lines.append, + ) + == 1 + ) + assert lines == ["Not claimed: the signature did not match the Seal key."] + + cloud.store(a.id, signer, a.seal_sha256) + cloud.claims[a.id] = "org-2" + lines.clear() + seal_claim.claim_published( + ORIGIN, + TOKEN, + transport=cloud, + signer=signer, + home=tmp_path / "seal-home", + say=lines.append, + ) + assert lines == [ + "Not claimed: another workspace already claimed one of these Seals." + ] + + +def test_claim_refuses_a_bad_token_without_retrying(tmp_path): + signer = Signer() + a = _published(tmp_path, signer, 1) + cloud = FakeCloud() + with pytest.raises(PublishError, match="sign-in"): + seal_claim.claim( + [a], origin=ORIGIN, token="wrong", sign=signer.sign, transport=cloud + ) + assert [url for _, url, _ in cloud.calls] == [ORIGIN + seal_claim.CHALLENGE_PATH] + + +def test_after_login_is_silent_when_cloud_does_not_take_claims(tmp_path, monkeypatch): + signer = Signer() + _published(tmp_path, signer, 1) + cloud = FakeCloud(enabled=False) + monkeypatch.setattr(seal_claim, "_signer", lambda: signer) + monkeypatch.setattr(seal_claim, "check_destination", lambda origin, **kw: None) + monkeypatch.setattr("openadapt_flow.hosted.resolve_host", lambda host=None: ORIGIN) + lines: list[str] = [] + seal_claim.after_login(transport=cloud, say=lines.append) + assert lines == [] + assert [url for _, url, _ in cloud.calls] == [ORIGIN + seal_claim.STATUS_PATH] + + +def test_after_login_claims_and_never_raises(tmp_path, monkeypatch): + signer = Signer() + a = _published(tmp_path, signer, 1) + cloud = FakeCloud() + cloud.store(a.id, signer, a.seal_sha256) + monkeypatch.setattr(seal_claim, "_signer", lambda: signer) + monkeypatch.setattr(seal_claim, "check_destination", lambda origin, **kw: None) + monkeypatch.setattr("openadapt_flow.hosted.resolve_host", lambda host=None: ORIGIN) + monkeypatch.setattr( + "openadapt_flow.hosted.resolve_token", lambda token=None, host=None: TOKEN + ) + lines: list[str] = [] + seal_claim.after_login(transport=cloud, say=lines.append) + assert lines == [f"Your published run is in your workspace: {ORIGIN}/dashboard"] + # The next login has nothing new to claim and says nothing. + calls = len(cloud.calls) + seal_claim.after_login(transport=cloud, say=lines.append) + assert len(lines) == 1 + assert [url for _, url, _ in cloud.calls[calls:]] == [ + ORIGIN + seal_claim.STATUS_PATH + ] + + def boom(*_a, **_k): + raise RuntimeError("keychain locked") + + monkeypatch.setattr(seal_claim, "_signer", boom) + seal_claim.after_login(transport=cloud, say=lines.append) # does not raise + + +def test_run_folders_published_before_the_note_can_be_named(tmp_path): + signer = Signer() + run = tmp_path / "openadapt-quickstart" / "run-1" + run.mkdir(parents=True) + seal = {"key_id": signer.key_id, "public_key": signer.public_key} + (run / "public-seal.json").write_text(json.dumps({"card": {}, "seal": seal})) + (run / seal_publish.PUBLISH_FILE).write_text( + json.dumps( + {"id": _id(7), "url": f"{ORIGIN}/seal#{_id(7)}", "delete_token": "secret"} + ) + ) + found, _ = find_claimable( + ORIGIN, + signer.key_id, + run_dirs=[tmp_path / "openadapt-quickstart"], + home=tmp_path / "none", + ) + assert [s.id for s in found] == [_id(7)] + assert found[0].seal_sha256 == seal_claim.seal_sha256(seal) + + +@pytest.mark.parametrize( + ("argv", "expected"), + [ + (["login"], True), + (["login", "--host", "https://x.test"], True), + (["setup", "login"], True), + (["login", "--help"], False), + (["setup", "login", "-h"], False), + (["push"], False), + (["setup", "connect"], False), + ], +) +def test_only_a_real_login_triggers_the_claim(argv, expected): + assert cli._is_login(argv) is expected + + +def test_the_login_hook_runs_only_after_a_successful_login(monkeypatch): + calls: list = [] + monkeypatch.setattr("openadapt_flow.__main__.main", lambda argv: 3) + monkeypatch.setattr( + seal_claim, "after_login", lambda host=None, **kw: calls.append((host, kw)) + ) + assert cli._invoke_flow(["login"]) == 3 + assert calls == [] + monkeypatch.setattr("openadapt_flow.__main__.main", lambda argv: 0) + argv = ["login", "--host=https://x.test", "--destination-kind", "byoc"] + assert cli._invoke_flow(argv + ["--trusted-host", "https://x.test"]) == 0 + assert calls == [ + ( + "https://x.test", + {"destination_kind": "byoc", "trusted_hosts": ["https://x.test"]}, + ) + ] + + +def test_seals_taken_down_are_dropped_and_the_rest_claimed(tmp_path): + signer = Signer() + _published(tmp_path, signer, 1) # taken down: Cloud no longer has it + b = _published(tmp_path, signer, 2) + cloud = FakeCloud() + cloud.store(b.id, signer, b.seal_sha256) + lines: list[str] = [] + home = tmp_path / "seal-home" + code = seal_claim.claim_published( + ORIGIN, TOKEN, transport=cloud, signer=signer, home=home, say=lines.append + ) + assert code == 0 + assert set(cloud.claims) == {b.id} + assert lines == [ + "Skipped 1 Seal that is no longer online.", + f"Your published run is in your workspace: {ORIGIN}/dashboard", + ] + assert [e["id"] for e in seal_claim.read_index(home)] == [b.id] + + +def test_unpublish_forgets_the_seal(tmp_path): + signer = Signer() + a = _published(tmp_path, signer, 1) + run = tmp_path / "run-1" + (run / seal_publish.PUBLISH_FILE).write_text( + json.dumps( + {"id": a.id, "url": f"{ORIGIN}/seal#{a.id}", "delete_token": "t" * 43} + ) + ) + deleted = lambda *_a: Response(204, {}, b"") # noqa: E731 + seal_publish.unpublish(run, origin=ORIGIN, transport=deleted) + assert seal_claim.read_index(tmp_path / "seal-home") == [] + + +def test_openadapt_login_is_a_command_that_reaches_flow_login(monkeypatch): + from click.testing import CliRunner + + seen: list = [] + + def fake_run_flow(argv): + seen.append(argv) + raise SystemExit(0) + + monkeypatch.setattr(cli, "_run_flow", fake_run_flow) + result = CliRunner().invoke( + cli.main, ["login", "--no-browser", "--host", "https://x.test"] + ) + assert result.exit_code == 0 + assert seen == [["login", "--no-browser", "--host", "https://x.test"]] + + +def test_after_login_claims_only_quickstart_seals(tmp_path, monkeypatch): + signer = Signer() + practice = _published(tmp_path, signer, 1) + real = _published(tmp_path, signer, 2, provenance="production") + cloud = FakeCloud() + cloud.store(practice.id, signer, practice.seal_sha256) + cloud.store(real.id, signer, real.seal_sha256) + monkeypatch.setattr(seal_claim, "_signer", lambda: signer) + monkeypatch.setattr(seal_claim, "check_destination", lambda origin, **kw: None) + monkeypatch.setattr("openadapt_flow.hosted.resolve_host", lambda host=None: ORIGIN) + monkeypatch.setattr( + "openadapt_flow.hosted.resolve_token", lambda token=None, host=None: TOKEN + ) + seal_claim.after_login(transport=cloud, say=lambda _line: None) + assert set(cloud.claims) == {practice.id} + # An explicit claim takes the rest. + seal_claim.claim_published( + ORIGIN, + TOKEN, + transport=cloud, + signer=signer, + home=tmp_path / "seal-home", + say=lambda _line: None, + ) + assert set(cloud.claims) == {practice.id, real.id} + + +def test_no_token_goes_to_an_untrusted_host(tmp_path, monkeypatch): + signer = Signer() + _published(tmp_path, signer, 1, origin="http://evil.test") + cloud = FakeCloud() + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path / "home")) + monkeypatch.setenv("OPENADAPT_INGEST_TOKEN", TOKEN) + monkeypatch.setattr(seal_claim, "_signer", lambda: signer) + seal_claim.after_login("http://evil.test", transport=cloud, say=lambda _l: None) + assert cloud.calls == [] + + from click.testing import CliRunner + + monkeypatch.setattr(seal_publish, "urllib_transport", cloud) + result = CliRunner().invoke( + cli.main, ["seal", "claim", "--host", "http://evil.test"] + ) + assert result.exit_code == 1 + assert "trust" in result.output + assert cloud.calls == []