diff --git a/openadapt/cli.py b/openadapt/cli.py index 0d589300fa..8422820d38 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -342,6 +342,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(): @@ -365,6 +397,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. @@ -1435,6 +1478,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={ @@ -1926,7 +1989,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. """ @@ -1938,6 +2002,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(): @@ -2156,6 +2222,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/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 1fc232374a..741e2104a1 100644 --- a/openadapt/seal_publish.py +++ b/openadapt/seal_publish.py @@ -405,6 +405,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 @@ -432,6 +436,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_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 == []