diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 26b7e6e..4c914cf 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -26,9 +26,10 @@ jobs: - name: Test installed package outside checkout run: | mkdir "$RUNNER_TEMP/qualification" - cp -R tests protocol "$RUNNER_TEMP/qualification/" + cp -R tests protocol scripts "$RUNNER_TEMP/qualification/" cp pytest.ini "$RUNNER_TEMP/qualification/" cd "$RUNNER_TEMP/qualification" + export EOA_VERIFIER_WHEEL="$(find "$GITHUB_WORKSPACE/dist" -name 'eoa_verifier-*.whl' -print -quit)" anvil --version "$RUNNER_TEMP/verifier-tests/bin/eoa-verifier" server start --help "$RUNNER_TEMP/verifier-tests/bin/python" -m pytest -q tests diff --git a/README.md b/README.md index 47cc4de..9da2653 100644 --- a/README.md +++ b/README.md @@ -176,3 +176,5 @@ its sole packaged schema, proof vectors, generator and conformance tests, plus [verifier-api-v1](protocol/verifier-api-v1/README.md) and the shared signed webhook/ACK profile. Oracle owns its selection/publication API; Comply owns the registry ABI and calldata fixtures. + +For an independent witnessed local environment, see [the integration commands](scripts/integration/README.md). diff --git a/scripts/__init__.py b/scripts/__init__.py new file mode 100644 index 0000000..fd8856b --- /dev/null +++ b/scripts/__init__.py @@ -0,0 +1 @@ +"""Repository-owned operational tools; excluded from application wheels.""" diff --git a/scripts/integration/README.md b/scripts/integration/README.md new file mode 100644 index 0000000..dd928ff --- /dev/null +++ b/scripts/integration/README.md @@ -0,0 +1,69 @@ +# Standalone Verifier environment + +Run from this repository root with Python 3.12.6+ and Anvil 1.5.1 on PATH. No +Oracle, Comply, Solidity checkout or external schema service is required. +Application code runs from an installed wheel in a run-owned virtual environment. + +```sh +python -m scripts.integration.env prepare --run-dir /tmp/verifier-demo +python -m scripts.integration.env start --run-dir /tmp/verifier-demo +python -m scripts.integration.env flow --run-dir /tmp/verifier-demo +python -m scripts.integration.env status --run-dir /tmp/verifier-demo +python -m scripts.integration.env logs --run-dir /tmp/verifier-demo --service verifier +python -m scripts.integration.env stop --run-dir /tmp/verifier-demo +python -m scripts.integration.env start --run-dir /tmp/verifier-demo +python -m scripts.integration.env stop --run-dir /tmp/verifier-demo +python -m scripts.integration.env clean --run-dir /tmp/verifier-demo +``` + +`qualify --run-dir FRESH` performs prepare/start/flow/stop. Add `--local-only` +for target-free acceptance; use a fresh directory when changing mode. `flow` +requires an unused scenario: it issues associations, proves nonce reuse rejection, +loses one post-commit ACK, reopens persistent stores and verifies exact revocation. +Stop retains all state and logs. Start reuses identities, chain and acceptance; +it does not repeat issuance. Clean refuses live owned processes and removes only +the explicit stopped run. Never use an operator's KERI directory as a run root. +Keep run roots outside source checkouts. One controller operates a run at a time; there is no concurrent controller API. + +Prepare defaults to six real native witness identities/listeners in one HIO +process. Issuance uses the first witness, matching the maintained credential +profile. `--witness-count 1` is the automated qualification topology. Six available +witnesses do not establish a six-witness credential qualification. + +The run manifest records ports, public identities, source revision/content hash, +wheel hash and selected interpreter. Run-owned directories contain native issuer, +witness, receiver and Verifier stores, Anvil state, public CESR/JSON credentials, +source snapshots, wheels and append-only service logs. Source snapshots use Git's +tracked/unignored inventory, omit Git internals and ignored data, and reject +symlinks. Private keys remain inside native stores; the two numbered wallet keys +are public local test constants. Only loopback Anvil URLs are supported. + +For a local candidate use `--verifier-source PATH` during preparation. For an +already built wheel supply `--verifier-wheel FILE --tool-revision REVISION` with +its matching tooling source. Those inputs are fixed for the lifetime of a run. +The installed-wheel suite uses this same interface outside the source checkout. + +## Fixture boundary + +```sh +python -m scripts.integration.env issue --run-dir RUN --wallet 1 --nonce fresh_nonce +python -m scripts.integration.env present --run-dir RUN --said SAID +python -m scripts.integration.env revoke --run-dir RUN --said SAID +``` + +Issue/revoke open native issuer contexts, wait for witnessed completion, export +exact bytes under `credentials/`, close the contexts, and return a JSON descriptor +on stdout. Progress goes to stderr. Present sends source-chain and credential +bytes to the public CESR endpoint. Neither operation writes application acceptance +records. Nonces are passed unchanged; issuance permits reuse so Verifier policy +can reject it during acceptance. + +A caller owning the full stack can start this fixture with `--rpc-url URL +--webhook-url URL --webhook-aid AID --peer-kel FILE`. The caller owns that chain +and receiver; this mode starts neither Anvil nor the focused receipt fixture. +Repeat the original options on restart. Configuration changes require a new run. + +The modules keep CLI dispatch, artifact/build selection, process lifetimes, +native infrastructure, issuer ceremonies and scenario assertions separate. Native +Habery/Regery contexts and Doist task ownership follow the pinned KERIpy patterns. +No tooling is included in the application wheel. diff --git a/scripts/integration/__init__.py b/scripts/integration/__init__.py new file mode 100644 index 0000000..839d1d7 --- /dev/null +++ b/scripts/integration/__init__.py @@ -0,0 +1 @@ +"""Standalone witnessed Verifier integration environment.""" diff --git a/scripts/integration/artifacts.py b/scripts/integration/artifacts.py new file mode 100644 index 0000000..73db7f6 --- /dev/null +++ b/scripts/integration/artifacts.py @@ -0,0 +1,124 @@ +"""Explicit JSON artifacts and isolated candidate source snapshots. + +These helpers never copy Git internals, ignored operator data or live stores. +They record what was built so a local dirty candidate is distinguishable from a +published revision. They are tooling only, outside application wheels. +""" + +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + + +def load_json(path: Path) -> dict: + """Read an explicit UTF-8 JSON artifact; malformed or missing input fails.""" + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def save_json(path: Path, value) -> None: + """Atomically replace one run-owned JSON file with private file permissions.""" + path = Path(path) + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}-", + delete=False, + ) as stream: + temporary = Path(stream.name) + json.dump(value, stream, indent=2) + stream.write("\n") + try: + os.chmod(temporary, 0o600) + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + + +def source_revision(source: Path) -> str: + """Return the exact base commit of an explicitly selected source checkout.""" + return subprocess.check_output( + ["git", "-C", str(source), "rev-parse", "HEAD"], text=True + ).strip() + + +def snapshot_source(source: Path, destination: Path) -> dict: + """Copy tracked and unignored candidate inputs, including recorded submodules. + + The destination must be fresh. Git internals and ignored caches/stores are + excluded by Git's own file inventory; symlinks are refused rather than followed + into an operator directory. Return base revision and a content digest. + """ + source = source.resolve() + if destination.resolve().is_relative_to(source): + raise ValueError("Snapshot destination must be outside its source") + destination.mkdir(parents=True) + inputs = ( + subprocess.check_output( + [ + "git", + "-C", + str(source), + "ls-files", + "-z", + "--cached", + "--others", + "--exclude-standard", + ] + ) + .decode() + .split("\0") + ) + digest = hashlib.sha256() + submodules = {} + for relative in sorted(set(filter(None, inputs))): + original, copied = source / relative, destination / relative + if original.is_symlink(): + raise ValueError(f"Symlink source input is not supported: {original}") + if original.is_dir(): + provenance = snapshot_source(original, copied) + submodules[relative] = provenance + digest.update(b"directory\0" + relative.encode() + b"\0") + digest.update(bytes.fromhex(provenance["sha256"])) + elif original.is_file(): + copied.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(original, copied) + digest.update(b"file\0" + relative.encode() + b"\0") + digest.update(hashlib.sha256(original.read_bytes()).digest()) + return { + "revision": source_revision(source), + "sha256": digest.hexdigest(), + "submodules": submodules, + } + + +def copy_tool_inputs(source: Path, destination: Path) -> dict: + """Copy an external qualification root alongside an explicitly supplied wheel. + + Such a root is deliberately outside Git and contains only owned tooling, + tests and protocol fixtures copied by the caller. Application code is supplied + by the wheel, never imported from this directory. + """ + if destination.resolve().is_relative_to(source.resolve()): + raise ValueError("Snapshot destination must be outside its source") + destination.mkdir(parents=True) + for name in ("scripts", "tests", "protocol"): + if (source / name).is_dir(): + shutil.copytree( + source / name, + destination / name, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc"), + ) + for name in ("pytest.ini", "README.md"): + if (source / name).is_file(): + shutil.copy2(source / name, destination / name) + digest = hashlib.sha256() + for path in sorted(destination.rglob("*")): + if path.is_file(): + digest.update(str(path.relative_to(destination)).encode() + b"\0") + digest.update(hashlib.sha256(path.read_bytes()).digest()) + return {"sha256": digest.hexdigest()} diff --git a/scripts/integration/builds.py b/scripts/integration/builds.py new file mode 100644 index 0000000..64b7ae5 --- /dev/null +++ b/scripts/integration/builds.py @@ -0,0 +1,75 @@ +"""Build a Verifier wheel and its isolated tooling environment from explicit inputs.""" + +import hashlib +from pathlib import Path +import shutil +import subprocess +import sys + +from .artifacts import copy_tool_inputs, snapshot_source + + +def prepare_installation( + root: Path, + source: Path, + *, + wheel: Path | None = None, + tool_revision: str | None = None, +) -> dict: + """Install a fresh wheel and return interpreter/tool paths plus provenance. + + source is an explicit candidate checkout, or the copied qualification root + accompanying wheel. The latter requires tool_revision because it has no Git + metadata. Build/install output is retained in root/logs/build.log. + """ + snapshot = root / "tools/verifier" + if wheel is None: + provenance = snapshot_source(source, snapshot) + else: + if not tool_revision: + raise ValueError("--verifier-wheel requires --tool-revision") + provenance = ( + snapshot_source(source, snapshot) + if (source / ".git").exists() + else copy_tool_inputs(source, snapshot) + ) + provenance["revision"] = tool_revision + subprocess.run( + [sys.executable, "-m", "venv", "--symlinks", str(root / "venv")], check=True + ) + python = str(root / "venv/bin/python") + with (root / "logs/build.log").open("w") as log: + if wheel is None: + subprocess.run( + [ + python, + "-m", + "pip", + "wheel", + "--no-deps", + "--wheel-dir", + str(root / "wheels"), + str(snapshot), + ], + check=True, + stdout=log, + stderr=log, + ) + wheel = next((root / "wheels").glob("eoa_verifier-*.whl")) + else: + copied = root / "wheels" / wheel.name + shutil.copy2(wheel, copied) + wheel = copied + subprocess.run( + [python, "-m", "pip", "install", str(wheel) + "[test]"], + check=True, + stdout=log, + stderr=log, + ) + return { + "python": python, + "tool": str(snapshot / "scripts/integration/env.py"), + "sourceRevision": provenance["revision"], + "sourceSha256": provenance["sha256"], + "wheelSha256": hashlib.sha256(wheel.read_bytes()).hexdigest(), + } diff --git a/scripts/integration/ceremony.py b/scripts/integration/ceremony.py new file mode 100644 index 0000000..50e1901 --- /dev/null +++ b/scripts/integration/ceremony.py @@ -0,0 +1,272 @@ +"""Persistent witnessed issuer ceremonies used by the Verifier fixture CLI. + +One command borrows GEDA, delegated QVI and LE stores, advances one native +ceremony, exports public evidence, then closes those stores. Witnesses and the +Verifier are separate processes. No application acceptance records are written. +""" + +from contextlib import ExitStack, contextmanager +from dataclasses import dataclass +from importlib.resources import files +from pathlib import Path +from typing import Generator + +from eth_account import Account +from eth_account.messages import encode_typed_data +from hio.base import doing +from keri.app import httping, oobiing +from keri.core import coring, scheming, serdering +from keri.db import basing +from keri.help import helping + +from eoa_verifier.verification.constants import LE_SCHEMA, QVI_SCHEMA +from eoa_verifier.verification.eoa import build_challenge +from .artifacts import load_json, save_json +from .issuers import ( + IssuerEscrows, + anchor, + approve_qvi, + association_from_challenge, + grant, + issue_credential, + open_issuers, + receive, + replay, + revoke_credential, + rules, +) + + +@dataclass +class IssuerCeremony: + """Borrow native actors and scheduler tasks for one sequential ceremony. + + root owns only fixture artifacts. actors/issuers own native KERI state through + the surrounding context, and schemas are the installed Verifier resources. + """ + + root: Path + configuration: dict + actors: dict + issuers: dict + schemas: dict + resolvers: list + witness_oobi: str + + @property + def tasks(self) -> list: + """Return the native tasks required while advancing an issuer operation.""" + return [ + *(task for resolver in self.resolvers for task in resolver.doers), + *( + task + for issuer in self.issuers.values() + for task in (issuer.registrar, issuer) + ), + IssuerEscrows(list(self.issuers.values())), + ] + + def bootstrap_sources(self) -> Generator: + """Issue and retain the witnessed GEDA -> QVI -> LE credential chain. + + This operation requires fresh actor registries. Return public chain facts + only after delegation, registry anchors and both credentials are accepted. + """ + yield from self._resolve_witness() + yield from approve_qvi(self.actors, self.issuers) + registries = yield from self._create_registries() + credentials, streams = {}, {} + for issuer_name, holder_name, schema_said in ( + ("geda", "qvi", QVI_SCHEMA), + ("qvi", "le", LE_SCHEMA), + ): + source = ( + self._qvi_edge(credentials["geda"].said) + if issuer_name == "qvi" + else None + ) + holder_hby, holder, holder_rgy = self.actors[holder_name] + issuer = self.issuers[issuer_name] + credential = issuer.create( + regname=issuer_name, + recp=holder.pre, + schema=schema_said, + source=source, + rules=rules(self.schemas[schema_said]), + data={"LEI": "5493001KJTIIGC8Y1R12"}, + ) + yield from issue_credential(issuer, registries[issuer_name], credential) + credentials[issuer_name] = credential + registry = registries[issuer_name] + streams[issuer_name] = replay( + registry.hab, issuer.rgy, registry, credential + ) + evidence = streams["geda"] + ( + streams["qvi"] if issuer_name == "qvi" else b"" + ) + receive(holder_hby, holder_rgy, evidence) + if not holder_rgy.reger.saved.get(keys=(credential.said,)): + raise RuntimeError( + f"{holder_name} did not accept its source credential" + ) + + chain = { + "gedaAid": self.actors["geda"][1].pre, + "issuerAid": self.actors["le"][1].pre, + "leSaid": credentials["qvi"].said, + "registry": registries["le"].regk, + } + (self.root / "chain.cesr").write_bytes(streams["geda"] + streams["qvi"]) + save_json(self.root / "chain.json", chain) + return chain + + def issue_association(self, wallet_key: str, nonce: str) -> Generator: + """Sign and issue one association, returning its public descriptor. + + wallet_key is a local fixture key; nonce is passed unchanged to the owned + proof implementation. A valid reused nonce is allowed at issuance so the + Verifier can exercise its own acceptance policy. + """ + chain, registry = self._association_context() + challenge = build_challenge( + issuer_aid=chain["issuerAid"], + le_vlei_said=chain["leSaid"], + ext_id=f"eip155:{self.configuration['chainId']}:{Account.from_key(wallet_key).address.lower()}", + nonce=nonce, + ) + signature = Account.sign_message( + encode_typed_data(full_message=challenge), wallet_key + ).signature + credential = association_from_challenge( + challenge, "0x" + signature.hex(), registry.regk + ) + yield from issue_credential(self.issuers["le"], registry, credential) + (self.root / "credentials" / f"{credential.said}.json").write_bytes( + credential.raw + ) + return self._export_association(credential, registry) + + def revoke_association(self, said: str) -> Generator: + """Witness revocation of a previously exported SAID and refresh its evidence.""" + _, registry = self._association_context() + credential = serdering.SerderACDC( + raw=(self.root / "credentials" / f"{said}.json").read_bytes() + ) + yield from revoke_credential(self.issuers["le"], registry, credential) + return self._export_association(credential, registry) + + def _association_context(self): + """Read the completed chain and its native LE registry without creating one.""" + chain = load_json(self.root / "chain.json") + return chain, self.actors["le"][2].regs[chain["registry"]] + + def _export_association(self, credential, registry) -> dict: + """Export exact KEL/TEL/Grant bytes addressed to the prepared Verifier AID.""" + _, le, rgy = self.actors["le"] + evidence = replay(le, rgy, registry, credential) + grant( + le, rgy, credential, self.configuration["verifierAid"] + ) + (self.root / "credentials" / f"{credential.said}.cesr").write_bytes(evidence) + return { + "said": credential.said, + "issuerAid": le.pre, + "wallet": credential.sad["a"]["extId"].split(":")[2], + "nonce": credential.sad["u"], + } + + def _resolve_witness(self) -> Generator: + """Wait for each actor's actual native OOBI acceptance before issuing.""" + for hby, _, _ in self.actors.values(): + while hby.db.roobi.get(keys=(self.witness_oobi,)) is None: + yield 0.01 + if ( + hby.db.roobi.get(keys=(self.witness_oobi,)).state + != oobiing.Result.resolved + ): + raise RuntimeError("Witness OOBI did not resolve") + + def _create_registries(self) -> Generator: + """Create each actor's no-backer registry and wait for witnessed anchors.""" + registries = {} + for name, (_, hab, rgy) in self.actors.items(): + registry = rgy.makeRegistry(name=name, prefix=hab.pre, noBackers=True) + self.issuers[name].registrar.incept(registry.vcp, anchor(hab, registry.vcp)) + while not self.issuers[name].registrar.complete(registry.regk): + yield 0.01 + registries[name] = registry + return registries + + @staticmethod + def _qvi_edge(qvi_said: str) -> dict: + """Build the source edge for the LE credential using the owned QVI schema.""" + return coring.Saider.saidify( + sad={"d": "", "qvi": {"n": qvi_said, "s": QVI_SCHEMA}} + )[1] + + +@contextmanager +def open_ceremony(root: Path): + """Own native actor stores; yield a ceremony borrowing their HIO tasks. + + root must be a prepared fixture run with a running witness. All stores close + before returning to the caller, including when a native operation fails. + """ + configuration = load_json(root / "run.json") + schemas = [ + scheming.Schemer(raw=p.read_bytes()) + for p in files("eoa_verifier.verification").joinpath("schema_data").iterdir() + ] + witness = configuration["witnesses"][0] + oobi = f"{witness['url']}/oobi/{witness['aid']}/controller" + with ExitStack() as stack: + from types import SimpleNamespace + + actors, issuers = open_issuers( + stack, + schemas, + base="", + temp=False, + witness=SimpleNamespace(pre=witness["aid"]), + head_dir=str(root / "issuers"), + ) + resolvers = [] + for hby, _, _ in actors.values(): + if hby.db.roobi.get(keys=(oobi,)) is None: + hby.db.oobis.pin( + keys=(oobi,), val=basing.OobiRecord(date=helping.nowIso8601()) + ) + resolvers.append(oobiing.Oobiery(hby=hby, clienter=httping.Clienter())) + yield IssuerCeremony( + root, + configuration, + actors, + issuers, + {schema.said: schema for schema in schemas}, + resolvers, + oobi, + ) + + +def complete_ceremony(ceremony: IssuerCeremony, operation: Generator) -> dict: + """Drive one borrowed operation for at most 90 seconds and return its result. + + Scheduler shutdown precedes the caller closing the ceremony's native stores. + No domain branching or state mutation is hidden inside this scheduler adapter. + """ + results = [] + + def advance(tymth, tock=0.0, **kwargs): + """Bridge a native generator result to the owning HIO scheduler.""" + yield tock + try: + results.append((yield from operation)) + finally: + scheduler.remove(list(scheduler.doers[:-1])) + + scheduler = doing.DoDoer(doers=[*ceremony.tasks, doing.doify(advance)]) + doing.Doist(real=True, tock=0.01, limit=90).do(doers=[scheduler]) + if not results: + raise TimeoutError( + "Witnessed issuer ceremony did not complete within 90 seconds" + ) + return results[0] diff --git a/scripts/integration/env.py b/scripts/integration/env.py new file mode 100644 index 0000000..da83cd6 --- /dev/null +++ b/scripts/integration/env.py @@ -0,0 +1,191 @@ +"""CLI for the standalone Verifier environment and its public fixture operations. + +Preparation builds/installs a wheel; all native work re-executes in that isolated +interpreter. Lifecycle, native ceremonies and scenario assertions have separate +owners so the command dispatcher contains no business workflow. +""" + +import argparse +from contextlib import redirect_stdout +import json +import os +from pathlib import Path +import signal +import sys + +from .environment import clean_run, load_run, prepare_run, present_credential, start_run +from .processes import is_running, process_records, stop + +SOURCE = Path(__file__).resolve().parents[2] +COMMANDS = ( + "prepare", + "start", + "flow", + "qualify", + "status", + "logs", + "stop", + "clean", + "issue", + "present", + "revoke", + "_initialize", + "_infrastructure", + "_bootstrap", +) + + +def parser() -> argparse.ArgumentParser: + """Describe the explicit run, candidate/artifact inputs and operation parameters.""" + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("command", choices=COMMANDS) + result.add_argument("--run-dir", required=True, type=Path) + result.add_argument("--verifier-source", type=Path, default=SOURCE) + result.add_argument("--verifier-wheel", type=Path) + result.add_argument("--tool-revision") + result.add_argument("--witness-count", type=int, choices=(1, 6), default=6) + result.add_argument("--local-only", action="store_true") + result.add_argument("--rpc-url") + result.add_argument("--webhook-url") + result.add_argument("--webhook-aid") + result.add_argument("--peer-kel", type=Path) + result.add_argument("--said") + result.add_argument("--nonce") + result.add_argument("--wallet", type=int, choices=(1, 2), default=1) + result.add_argument("--service") + return result + + +def main() -> None: + """Validate inputs, select the prepared interpreter and dispatch one command.""" + arguments = parser().parse_args() + root = arguments.run_dir.expanduser().resolve() + if arguments.command in ("prepare", "qualify") and not root.exists(): + prepare_run( + root, + arguments.verifier_source.resolve(), + witness_count=arguments.witness_count, + wheel=arguments.verifier_wheel, + tool_revision=arguments.tool_revision, + ) + if arguments.command == "prepare": + print(f"Prepared {root}") + return + elif arguments.command == "prepare": + raise ValueError("Run already exists; choose a fresh directory") + configuration = load_run(root) + if arguments.command in ("status", "logs", "stop", "clean"): + inspect_or_stop(root, arguments) + return + if sys.prefix != str(root / "venv"): + os.chdir(Path(configuration["tool"]).parents[2]) + os.execv( + configuration["python"], + [configuration["python"], "-m", "scripts.integration.env", *sys.argv[1:]], + ) + execute(root, configuration, arguments) + + +def inspect_or_stop(root: Path, arguments) -> None: + """Handle resource inspection and deletion without importing application code.""" + if arguments.command == "stop": + stop(root, arguments.service) + elif arguments.command == "clean": + clean_run(root) + elif arguments.command == "status": + print( + json.dumps( + { + "run": load_run(root), + "processes": { + name: is_running(record) + for name, record in process_records(root).items() + }, + }, + indent=2, + ) + ) + else: + for path in sorted((root / "logs").glob((arguments.service or "*") + ".log")): + print(f"{path}\n{path.read_text(errors='replace')[-12000:]}") + + +def execute(root: Path, configuration: dict, arguments) -> None: + """Dispatch in the isolated interpreter; internal daemon commands stay narrow.""" + action = arguments.command + if action in ("issue", "revoke", "_bootstrap"): + issue_or_revoke(root, arguments) + elif action == "_initialize": + from .infrastructure import initialize + + initialize(root, configuration) + elif action == "_infrastructure": + from .infrastructure import serve_infrastructure + + serve_infrastructure(root, configuration) + elif action == "present": + if not arguments.said: + raise ValueError("present requires --said") + present_credential(root, configuration, arguments.said) + elif action == "start": + start(root, configuration, arguments) + elif action == "flow": + from .scenario import run_flow + + run_flow(root, configuration) + elif action == "qualify": + from .scenario import run_flow + + try: + start(root, configuration, arguments) + run_flow(root, configuration) + print("Witnessed Verifier qualification passed") + finally: + stop(root) + + +def start(root: Path, configuration: dict, arguments) -> None: + """Pass the explicit CLI mode and peer configuration to the lifecycle owner.""" + start_run( + root, + configuration, + local_only=arguments.local_only, + rpc_url=arguments.rpc_url, + webhook_url=arguments.webhook_url, + webhook_aid=arguments.webhook_aid, + peer_kel=arguments.peer_kel, + ) + + +def issue_or_revoke(root: Path, arguments) -> None: + """Run a single native ceremony and emit only its JSON descriptor to stdout.""" + from .ceremony import complete_ceremony, open_ceremony + + if arguments.command == "issue" and arguments.nonce is None: + raise ValueError("issue requires --nonce") + if arguments.command == "revoke" and not arguments.said: + raise ValueError("revoke requires --said") + with redirect_stdout(sys.stderr), open_ceremony(root) as ceremony: + if arguments.command == "_bootstrap": + operation = ceremony.bootstrap_sources() + elif arguments.command == "issue": + operation = ceremony.issue_association( + "0x" + "0" * 63 + str(arguments.wallet), arguments.nonce + ) + else: + operation = ceremony.revoke_association(arguments.said) + descriptor = complete_ceremony(ceremony, operation) + print(json.dumps(descriptor)) + + +def shutdown(signum, frame) -> None: + """Unwind native context managers on owned daemon termination.""" + raise KeyboardInterrupt + + +if __name__ == "__main__": + signal.signal(signal.SIGTERM, shutdown) + try: + main() + except KeyboardInterrupt: + pass diff --git a/scripts/integration/environment.py b/scripts/integration/environment.py new file mode 100644 index 0000000..168fbdf --- /dev/null +++ b/scripts/integration/environment.py @@ -0,0 +1,380 @@ +"""Concrete Verifier environment lifecycle, distinct from CLI and issuer policy. + +The run artifact fixes identity, trust, ports and installed code. Start/stop manage +only that run; they never retarget previously accepted delivery obligations. +""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from urllib.request import Request, urlopen + +from .artifacts import load_json, save_json +from .builds import prepare_installation +from .infrastructure import infrastructure +from .processes import free_port, is_running, launch, process_records, stop, wait_ready + +OWNER = "eoa-verifier-integration" + + +def tool_command(configuration: dict, *arguments: str) -> list[str]: + """Invoke this run's snapshotted tooling using its isolated interpreter.""" + return [ + configuration["python"], + "-m", + "scripts.integration.env", + *arguments, + "--run-dir", + configuration["root"], + ] + + +def request_json( + url: str, + body: bytes | None = None, + *, + method: str | None = None, + headers: dict | None = None, +): + """Perform a bounded local HTTP exchange; return decoded JSON or no content.""" + with urlopen( + Request(url, data=body, method=method, headers=headers or {}), timeout=5 + ) as response: + raw = response.read() + return json.loads(raw) if raw else None + + +def prepare_run( + root: Path, + source: Path, + *, + witness_count: int, + wheel: Path | None = None, + tool_revision: str | None = None, +) -> None: + """Create one fresh run, install its wheel, and issue its real source chain. + + Partial failures retain artifacts/logs but stop any owned infrastructure. + Existing directories are never overwritten or treated as completed runs. + """ + if root.resolve().is_relative_to(source.resolve()): + raise ValueError("Run directory must be outside its source checkout") + anvil = shutil.which("anvil") + if not anvil: + raise ValueError("Anvil is required; install Foundry 1.5.1") + if root.exists(): + raise ValueError(f"Run already exists; choose a fresh directory: {root}") + root.mkdir(mode=0o700, parents=True) + for name in ("logs", "wheels", "credentials", "tools"): + (root / name).mkdir() + installation = prepare_installation( + root, source, wheel=wheel, tool_revision=tool_revision + ) + ports = _ports(4 + witness_count) + configuration = { + "version": 1, + "owner": OWNER, + "root": str(root), + **installation, + "chainId": 31337, + "anvil": anvil, + "rpcPort": ports[0], + "verifierPort": ports[1], + "receiverPort": ports[2], + "schemaPort": ports[3], + "witnesses": [{"port": port} for port in ports[4:]], + "dropAck": True, + "rpcUrl": f"http://127.0.0.1:{ports[0]}", + "verifierUrl": f"http://127.0.0.1:{ports[1]}", + "webhookUrl": f"http://127.0.0.1:{ports[2]}/hook", + } + save_json(root / "run.json", configuration) + subprocess.run( + tool_command(configuration, "_initialize"), + check=True, + cwd=Path(configuration["tool"]).parents[2], + ) + configuration = load_run(root) + try: + infrastructure(root, configuration) + with (root / "logs/issuance.log").open("w") as log: + subprocess.run( + tool_command(configuration, "_bootstrap"), + check=True, + stdout=log, + stderr=log, + cwd=Path(configuration["tool"]).parents[2], + ) + configuration["gedaAid"] = load_json(root / "chain.json")["gedaAid"] + configuration["prepared"] = True + save_json(root / "run.json", configuration) + finally: + stop(root) + + +def load_run(root: Path) -> dict: + """Read and validate the explicit run ownership before operating on resources.""" + configuration = load_json(root / "run.json") + if configuration["owner"] != OWNER or configuration["root"] != str(root): + raise ValueError("Run ownership mismatch") + return configuration + + +def start_run( + root: Path, + configuration: dict, + *, + local_only: bool = False, + rpc_url: str | None = None, + webhook_url: str | None = None, + webhook_aid: str | None = None, + peer_kel: Path | None = None, +) -> None: + """Start/reopen this run with immutable mode, peer and chain configuration. + + An external RPC is owned by the caller. An external webhook replaces only the + fixture receiver, never verification or issuance. Failure stops owned services + while preserving data; it never stops the external RPC or webhook. + """ + if not configuration.get("prepared"): + raise ValueError("Run preparation did not complete; inspect retained logs") + requested = { + "localOnly": local_only, + "externalWebhook": bool(webhook_url), + "rpcUrl": rpc_url or configuration["rpcUrl"], + "externalRpc": bool(rpc_url), + } + if webhook_url: + if not webhook_aid or peer_kel is None: + raise ValueError("External webhook requires an explicit AID and KEL file") + requested.update(webhookUrl=webhook_url, receiverAid=webhook_aid) + if configuration.get("configured"): + if any(configuration.get(key) != value for key, value in requested.items()): + raise ValueError( + "Run configuration is immutable; use its original start options" + ) + configuration.update(requested) + if ( + peer_kel is not None + and peer_kel.resolve() != (root / "receiver.cesr").resolve() + ): + shutil.copyfile(peer_kel, root / "receiver.cesr") + configuration["configured"] = True + _validate_local_rpc(configuration["rpcUrl"]) + save_json(root / "run.json", configuration) + try: + infrastructure(root, configuration) + if rpc_url is None: + _start_anvil(root, configuration) + _check_chain(configuration) + if not local_only and webhook_url is None: + _start_receiver(root, configuration) + launch( + root, + "verifier", + _verifier_command(root, configuration), + port=configuration["verifierPort"], + env={ + key: value + for key, value in os.environ.items() + if key not in ("VLEI_ORACLE_POSTING_KEY", "PRIVATE_KEY", "ADMIN_PK") + }, + ) + wait_ready( + root, + "verifier", + lambda: request_json(configuration["verifierUrl"] + "/health"), + ) + if not local_only: + request_json( + configuration["verifierUrl"] + "/", + (root / "receiver.cesr").read_bytes(), + method="PUT", + ) + configuration["startedOnce"] = True + save_json(root / "run.json", configuration) + except BaseException: + stop(root) + raise + + +def restart_verifier(root: Path, configuration: dict) -> None: + """Restart the installed Verifier without presenting another Grant.""" + stop(root, "verifier") + start_run( + root, + configuration, + local_only=configuration["localOnly"], + rpc_url=configuration["rpcUrl"] if configuration["externalRpc"] else None, + webhook_url=configuration["webhookUrl"] + if configuration["externalWebhook"] + else None, + webhook_aid=configuration["receiverAid"], + peer_kel=root / "receiver.cesr", + ) + + +def present_credential(root: Path, configuration: dict, said: str) -> None: + """Send exported source/evidence bytes to the public CESR-stream endpoint.""" + evidence = (root / "chain.cesr").read_bytes() + ( + root / "credentials" / f"{said}.cesr" + ).read_bytes() + request_json(configuration["verifierUrl"] + "/", evidence, method="PUT") + + +def wait_for_status( + configuration: dict, said: str, expected: str, timeout: float = 25 +) -> dict: + """Wait for public stored state and, when present, its authenticated delivery ACK.""" + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + try: + last = request_json( + configuration["verifierUrl"] + f"/v1/associations/{said}/status" + ) + delivery = last.get("delivery") + if last["status"] == expected and ( + delivery is None or delivery["acknowledged"] + ): + return last + except OSError: + pass + time.sleep(0.1) + raise TimeoutError(f"{said} did not reach {expected}: {last}") + + +def clean_run(root: Path) -> None: + """Remove an explicitly owned stopped run, never a live process's state.""" + load_run(root) + if any(is_running(item) for item in process_records(root).values()): + raise ValueError("Stop the run before clean") + shutil.rmtree(root) + + +def _ports(count: int) -> list[int]: + """Choose distinct probe ports; the launch boundary checks them again.""" + ports = set() + while len(ports) < count: + ports.add(free_port()) + return list(ports) + + +def _start_anvil(root: Path, configuration: dict) -> None: + """Start only this run's local chain, retaining state for a persistent restart.""" + launch( + root, + "anvil", + [ + configuration["anvil"], + "--host", + "127.0.0.1", + "--port", + str(configuration["rpcPort"]), + "--chain-id", + "31337", + "--state", + str(root / "anvil.json"), + "--state-interval", + "1", + "--silent", + ], + port=configuration["rpcPort"], + ) + wait_ready(root, "anvil", lambda: _check_chain(configuration)) + + +def _check_chain(configuration: dict) -> bool: + """Require the expected chain ID before any Verifier can observe accounts.""" + body = json.dumps( + {"jsonrpc": "2.0", "id": 1, "method": "eth_chainId", "params": []} + ).encode() + response = request_json( + configuration["rpcUrl"], body, headers={"Content-Type": "application/json"} + ) + if response.get("result") != hex(configuration["chainId"]): + raise RuntimeError("RPC chain differs from the prepared run") + return True + + +def _start_receiver(root: Path, configuration: dict) -> None: + """Start the focused receiver and wait for its persisted-receipt read endpoint.""" + tool = Path(configuration["tool"]).with_name("receiver.py") + launch( + root, + "receiver", + [ + configuration["python"], + "-m", + "scripts.integration.receiver", + "--root", + str(root), + ], + port=configuration["receiverPort"], + cwd=tool.parents[2], + ) + wait_ready(root, "receiver", lambda: request_json(configuration["webhookUrl"])) + + +def _verifier_command(root: Path, configuration: dict) -> list[str]: + """Construct the supported installed CLI without posting keys or hidden peers.""" + command = [ + str(Path(configuration["python"]).with_name("eoa-verifier")), + "server", + "start", + "--name", + "verifier", + "--alias", + "verifier", + "--head-dir", + str(root / "services"), + "--host", + "127.0.0.1", + "--http-port", + str(configuration["verifierPort"]), + "--trusted-geda-aid", + configuration["gedaAid"], + "--chain-id", + "31337", + "--rpc-url", + configuration["rpcUrl"], + ] + if not configuration["localOnly"]: + command += [ + "--webhook-url", + configuration["webhookUrl"], + "--webhook-aid", + configuration["receiverAid"], + "--webhook-timeout", + "1", + "--webhook-interval", + ".1", + "--webhook-backoff-base", + ".1", + "--webhook-backoff-cap", + ".2", + ] + return command + + +def _validate_local_rpc(url: str) -> None: + """Refuse non-local RPC URLs before launching infrastructure or signing work.""" + from urllib.parse import urlsplit + + parsed = urlsplit(url) + if ( + parsed.scheme != "http" + or parsed.hostname not in ("127.0.0.1", "localhost") + or parsed.username is not None + or parsed.password is not None + or parsed.port is None + or parsed.path not in ("", "/") + or parsed.query + or parsed.fragment + ): + raise ValueError( + "Integration RPC must be an explicit loopback HTTP URL and port" + ) diff --git a/scripts/integration/infrastructure.py b/scripts/integration/infrastructure.py new file mode 100644 index 0000000..5aa2112 --- /dev/null +++ b/scripts/integration/infrastructure.py @@ -0,0 +1,121 @@ +"""Run-owned KERI witness identities and exact installed schema hosting. + +Native contexts own stores and HIO owns sockets. The daemon serves one witness +for automated qualification or six for the manual environment; issuance retains +the existing one-witness credential profile. +""" + +from pathlib import Path +import json +from urllib.request import urlopen +from .artifacts import save_json +from .processes import launch, wait_ready + + +def make_identity(root: Path, name: str, *, transferable: bool = True): + """Create/reopen a fixture AID and export its public inception before closing.""" + from keri.app import habbing + + with habbing.openHby(name=name, headDirPath=str(root), temp=False) as hby: + hab = hby.habByName(name) or hby.makeHab(name=name, transferable=transferable) + return hab.pre, bytes(hab.makeOwnEvent(sn=0)) + + +def initialize(root: Path, config: dict) -> None: + """Prepare independent witness, Verifier and receiver identities under root.""" + from importlib.metadata import version + import subprocess + import sys + + config["versions"] = { + "python": sys.version.split()[0], + **{name: version(name) for name in ("eoa-verifier", "gleif_keri", "gleif_hio")}, + "anvil": subprocess.check_output( + [config["anvil"], "--version"], text=True, timeout=5 + ).strip(), + } + for index, w in enumerate(config["witnesses"]): + aid, _ = make_identity(root / f"witness-{index}", "witness", transferable=False) + w.update(aid=aid, url=f"http://127.0.0.1:{w['port']}") + config["verifierAid"], kel = make_identity(root / "services", "verifier") + (root / "verifier.cesr").write_bytes(kel) + config["receiverAid"], kel = make_identity(root / "receiver", "receiver") + (root / "receiver.cesr").write_bytes(kel) + save_json(root / "run.json", config) + + +def infrastructure(root: Path, config: dict) -> None: + """Launch owned witnesses/schema hosting and verify each expected OOBI.""" + launch( + root, + "infrastructure", + [ + config["python"], + "-m", + "scripts.integration.env", + "_infrastructure", + "--run-dir", + str(root), + ], + port=config["witnesses"][0]["port"], + cwd=Path(config["tool"]).parents[2], + ) + for w in config["witnesses"]: + wait_ready( + root, + "infrastructure", + lambda w=w: bool( + urlopen( + w["url"] + "/oobi/" + w["aid"] + "/controller", timeout=2 + ).read() + ), + ) + + +def serve_infrastructure(root: Path, config: dict) -> None: + """Serve native witness tasks and packaged schema bytes until shutdown.""" + from contextlib import ExitStack + from importlib.resources import files + import falcon + from hio.base import doing + from hio.core import http + from keri.app import habbing, indirecting + + schemas = { + json.loads(p.read_bytes())["$id"]: p.read_bytes() + for p in files("eoa_verifier.verification").joinpath("schema_data").iterdir() + } + + class Schema: + """Expose only the already accepted packaged schemas for local issuers.""" + + def on_get(self, req, rep, said): + """Return exact schema bytes or 404; never fetch or synthesize a schema.""" + if said not in schemas: + raise falcon.HTTPNotFound() + rep.data = schemas[said] + rep.content_type = "application/schema+json" + + with ExitStack() as stack: + doers = [] + for index, w in enumerate(config["witnesses"]): + hby = stack.enter_context( + habbing.openHby( + name="witness", + headDirPath=str(root / f"witness-{index}"), + temp=False, + ) + ) + doers.extend( + indirecting.setupWitness( + hby=hby, alias="witness", tcpPort=None, httpPort=w["port"] + ) + ) + hab = hby.habByName("witness") + hby.psr.parse(ims=hab.makeEndRole(eid=hab.pre)) + hby.psr.parse(ims=hab.makeLocScheme(url=w["url"])) + app = falcon.App() + app.add_route("/oobi/{said}", Schema()) + server = http.Server(host="127.0.0.1", port=config["schemaPort"], app=app) + doers.append(http.ServerDoer(server=server)) + doing.Doist(real=True, tock=0.01).do(doers=doers) diff --git a/scripts/integration/issuers.py b/scripts/integration/issuers.py new file mode 100644 index 0000000..9355749 --- /dev/null +++ b/scripts/integration/issuers.py @@ -0,0 +1,297 @@ +"""Native witnessed issuer primitives shared by fixture commands and own tests. + +Callers own contexts, scheduling and transport. These helpers construct real +KERI/ACDC evidence and never write Verifier application acceptance records. +""" + +from hio.base import doing +from keri.app import habbing, signing +from keri.core import coring, eventing, parsing, serdering +from keri.db import dbing +from keri.kering import Protocols, versify +from keri.vc import protocoling +from keri.vdr import credentialing, verifying, viring + +from eoa_verifier.verification.constants import ( + ASSOCIATION_SCHEMA, + LE_SCHEMA, +) +from eoa_verifier.verification.eoa import DOMAIN_TAG, PROOF_ALGORITHM, build_challenge + +KEY = "0x" + "0" * 63 + "1" + + +def anchor(hab, event) -> serdering.SerderKERI: + """Append a signed TEL seal to hab’s KEL and return its KERIpy interaction Serder.""" + message = hab.interact( + data=[eventing.SealEvent(event.pre, event.snh, event.said)._asdict()] + ) + return serdering.SerderKERI(raw=message) + + +def replay(hab, rgy, registry, creder) -> bytes: + """Return issuer KEL, registry/credential TEL and accepted ACDC bytes from KERIpy stores. + + The caller supplies an issued credential and its registry. Prepend upstream + streams when the receiver also needs LE/QVI evidence; this helper does no network I/O. + """ + return b"".join( + [ + *hab.db.clonePreIter(pre=hab.pre), + *rgy.reger.clonePreIter(pre=registry.regk), + *rgy.reger.clonePreIter(pre=creder.said), + signing.serialize(*rgy.reger.cloneCred(creder.said)), + ] + ) + + +def issue_credential(issuer, registry, creder): + """Schedule KERIpy TEL/KEL issuance for creder in registry using the supplied Credentialer. + + Yield 0.01 HIO seconds until completion, then return None. The caller must run + Registrar, Credentialer and escrow Doers and own their stores. + """ + issuance = registry.issue(said=creder.said, dt=creder.attrib.get("dt")) + anc = anchor(registry.hab, issuance) + issuer.issue(creder, issuance) + issuer.registrar.issue(creder, issuance, anc) + while not issuer.complete(creder.said): + yield 0.01 + + +def revoke_credential(issuer, registry, creder): + """Anchor verified revocation and schedule it on the supplied issuer's Registrar. + + Yield 0.01 HIO seconds until witnessed completion, then return None. The caller + owns scheduling and later transports the resulting TEL/KEL evidence. + """ + revocation = registry.revoke(said=creder.said) + issuer.registrar.revoke(creder, revocation, anchor(registry.hab, revocation)) + while not issuer.registrar.complete(creder.said, sn=revocation.sn): + yield 0.01 + + +def receive(hby, rgy, stream) -> None: + """Give an issuer supporting KERI evidence through the standard parser. + + QVI and LE use this local delivery before issuing their own credentials. + Verifier delivery is tested separately through HTTP. Acceptance is established + by KERIpy's verifier, including its normal escrow processing. + """ + verifier = verifying.Verifier(hby=hby, reger=rgy.reger) + parsing.Parser().parse( + ims=bytearray(stream), + kvy=eventing.Kevery(db=hby.db, lax=False, local=False), + tvy=verifier.tvy, + vry=verifier, + ) + verifier.processEscrows() + + +def rules(schema) -> dict: + """Return a SAID-bearing rules dict with the exact disclaimers required by the supplied credential schema.""" + fields = schema.sed["properties"]["r"]["oneOf"][1]["properties"] + return coring.Saider.saidify( + sad={ + "d": "", + **{ + name: {"l": fields[name]["properties"]["l"]["const"]} + for name in ("usageDisclaimer", "issuanceDisclaimer") + }, + } + )[1] + + +def grant( + hab, + rgy, + creder, + recipient, + *, + acdc=None, +) -> bytes: + """Return IPEX Grant bytes addressed to recipient from the supplied issuer stores. + + Use the issued creder plus KERIpy issuance/anchor embeds; acdc can override + serialized credential bytes. Source + credentials travel separately so tests can withhold them. This builds, not sends. + """ + acdc = ( + signing.serialize(*rgy.reger.cloneCred(creder.said)) if acdc is None else acdc + ) + iss = rgy.reger.cloneTvtAt(creder.said) + issuance = serdering.SerderKERI(raw=iss) + sealing_event = hab.db.fetchLastSealingEventByEventSeal( + hab.pre, + seal={"i": issuance.pre, "s": issuance.snh, "d": issuance.said}, + ) + anc = hab.db.cloneEvtMsg(pre=hab.pre, fn=0, dig=sealing_event.said) + exn, attachments = protocoling.ipexGrantExn( + hab=hab, + recp=recipient, + message="External association", + acdc=acdc, + iss=iss, + anc=anc, + ) + return exn.raw + attachments + + +class IssuerEscrows(doing.Doer): + """Process each issuer's registry and credential escrows on the HIO clock. + + The KLI normally performs this alongside its mailbox processing. Local + issuer-to-holder delivery here has no mailbox; Registrar and Credentialer + still run as their own HIO doers. + """ + + def __init__(self, issuers): + """Borrow issuer runtimes in issuers and recur every 0.03125 HIO seconds; do not own their stores.""" + self.issuers = issuers + super().__init__(tock=0.03125) + + def recur(self, tyme): + """Process borrowed registry/verifier escrows once and return False to remain scheduled.""" + for issuer in self.issuers: + issuer.rgy.processEscrows() + issuer.verifier.processEscrows() + return False + + +def issuer_for(hby, rgy): + """Return a KERIpy Credentialer with Registrar and Verifier borrowing the supplied Habery/Regery.""" + registrar = credentialing.Registrar(hby=hby, rgy=rgy, counselor=None) + return credentialing.Credentialer( + hby=hby, + rgy=rgy, + registrar=registrar, + verifier=verifying.Verifier(hby=hby, reger=rgy.reger), + ) + + +def open_issuers(stack, schemas, *, base, temp, witness, head_dir=None): + """Return actor and issuer dictionaries for isolated witnessed GEDA/QVI/LE controllers. + + Pin supplied credential schemas and configure QVI delegation to GEDA. stack owns store closure; + temp selects disposable stores, base selects their namespace, witness supplies + the witness AID. head_dir selects an explicit persistent storage root when + temp is false; existing actors and registries reopen there. The caller must schedule the returned KERIpy issuance tasks. + """ + actors, issuers = {}, {} + for name in ("geda", "qvi", "le"): + hby = stack.enter_context( + habbing.openHby(name=name, base=base, temp=temp, headDirPath=head_dir) + ) + for schema in schemas: + hby.db.schema.pin(keys=(schema.said,), val=schema) + hab = hby.habByName(name) or hby.makeHab( + name=name, + icount=1, + isith="1", + ncount=1, + nsith="1", + wits=[witness.pre], + toad=1, + **({"delpre": actors["geda"][1].pre} if name == "qvi" else {}), + ) + reger = stack.enter_context( + viring.openReger( + name=name, base=base, temp=temp, db=hby.db, headDirPath=head_dir + ) + ) + rgy = credentialing.Regery( + hby=hby, name=name, base=base, temp=temp, reger=reger + ) + actors[name] = (hby, hab, rgy) + # Single-sig needs no multisig Counselor; retain the KLI lifecycle doers. + issuers[name] = issuer_for(hby, rgy) + return actors, issuers + + +def collect_receipts(issuer, hab, sn): + """Queue hab/sn on the issuer’s KERIpy receipt worker; yield until its completion cue, then return None.""" + receiptor = issuer.registrar.receiptor + receiptor.msgs.append({"pre": hab.pre, "sn": sn}) + while not any(cue["pre"] == hab.pre and cue["sn"] == sn for cue in receiptor.cues): + yield 0.01 + + +def approve_qvi(actors, issuers): + """Yield through real witnessed QVI delegation approval among the supplied actors. + + Use the KLI authorizer seal and replay accepted evidence to issuer stores. + Return None after GEDA accepts the delegation; the caller owns actor scheduling. + """ + geda_hby, geda, _geda_rgy = actors["geda"] + qvi_hby, qvi, qvi_rgy = actors["qvi"] + _le_hby, le, _le_rgy = actors["le"] + # Introduce the non-delegated inception events before GEDA's approval. + yield from collect_receipts(issuers["geda"], geda, 0) + yield from collect_receipts(issuers["le"], le, 0) + inception = serdering.SerderKERI(raw=qvi.makeOwnEvent(sn=0)) + geda.interact(data=[eventing.SealEvent(qvi.pre, "0", inception.said)._asdict()]) + couple = coring.Seqner(sn=geda.kever.sn).qb64b + geda.kever.serder.saidb + for hby in (geda_hby, qvi_hby): + hby.db.setAes(dbing.dgKey(qvi.pre, inception.said), couple) + yield from collect_receipts(issuers["geda"], geda, geda.kever.sn) + receive(qvi_hby, qvi_rgy, b"".join(geda.db.clonePreIter(pre=geda.pre))) + # The receipt worker sends cloneDelegation context before the delegated event. + yield from collect_receipts(issuers["qvi"], qvi, 0) + geda_hby.psr.parse(ims=bytearray(b"".join(qvi.db.clonePreIter(pre=qvi.pre)))) + geda_hby.kvy.processEscrowDelegables() + receive(qvi_hby, qvi_rgy, b"".join(le.db.clonePreIter(pre=le.pre))) + assert qvi.pre in geda_hby.kevers, "GEDA has not accepted QVI delegation" + + +def association_from_challenge(challenge, signature, registry): + """Return a SAID-bearing association ACDC for typed challenge, signature and registry. + + Require the exact EOA challenge shape and canonical registry SAID, raising + ValueError on mismatch. Build nested proof/attribute/LE-edge SAIDs but do not + verify the wallet signature, issue the credential or establish KERIpy credential acceptance. + """ + fields = challenge["message"] + expected = build_challenge( + issuer_aid=fields["issuerAid"], + le_vlei_said=fields["leVleiSaid"], + ext_id=fields["extId"], + nonce=fields["nonce"], + ) + if challenge != expected: + raise ValueError("challenge does not match the EOA profile") + if coring.Saider(qb64=registry).qb64 != registry: + raise ValueError("registry must be a canonical KERI SAID") + proof = coring.Saider.saidify( + sad={ + "d": "", + "alg": PROOF_ALGORITHM, + "tag": DOMAIN_TAG, + "sig": signature, + } + )[1] + attributes = coring.Saider.saidify( + sad={ + "d": "", + "extId": fields["extId"], + "proof": proof, + } + )[1] + edge = coring.Saider.saidify( + sad={ + "d": "", + "le": {"n": fields["leVleiSaid"], "s": LE_SCHEMA, "o": "I2I"}, + } + )[1] + return serdering.SerderACDC( + sad={ + "v": versify(protocol=Protocols.acdc, size=0), + "d": "", + "u": fields["nonce"], + "i": fields["issuerAid"], + "ri": registry, + "s": ASSOCIATION_SCHEMA, + "a": attributes, + "e": edge, + }, + makify=True, + ) diff --git a/scripts/integration/processes.py b/scripts/integration/processes.py new file mode 100644 index 0000000..294183b --- /dev/null +++ b/scripts/integration/processes.py @@ -0,0 +1,161 @@ +"""Start, inspect and stop only processes owned by one local integration run. + +All children start in their own session. A saved PID alone is insufficient: +shutdown checks the recorded start time, executable command and process group. +One controller operates a run at a time; separate runs use separate ports/state. +""" + +import os +from pathlib import Path +import signal +import socket +import subprocess +import time +from typing import Callable + +from .artifacts import load_json, save_json + + +def free_port() -> int: + """Probe a free loopback port; launch still rejects a later foreign occupant.""" + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def process_identity(pid: int) -> str: + """Read the POSIX process generation and command, or an empty value if gone.""" + result = subprocess.run( + ["ps", "-p", str(pid), "-o", "lstart=", "-o", "command="], + capture_output=True, + text=True, + ) + return result.stdout.strip() if result.returncode == 0 else "" + + +def is_running(record: dict | None) -> bool: + """Return whether this PID still identifies the recorded owned child.""" + return bool(record) and process_identity(record["pid"]) == record["identity"] + + +def process_records(root: Path) -> dict: + """Read a run's process inventory; a fresh run has no processes yet.""" + path = root / "processes.json" + return load_json(path) if path.exists() else {} + + +def launch( + root: Path, + role: str, + command: list[str], + *, + port: int, + env=None, + cwd: Path | None = None, +) -> None: + """Start one concrete service and retain its generation and combined log. + + Reusing our identical running role is idempotent. A different command or a + foreign listener fails. If process registration fails, stop the new child + instead of leaving an untracked daemon behind. Readiness is checked separately. + """ + records = process_records(root) + existing = records.get(role) + if is_running(existing): + if existing["command"] != command: + raise ValueError(f"{role} already runs with different arguments") + return + # Permit restart after our closed TCP connections enter TIME_WAIT. A live + # listener still makes this exclusive bind fail. + with socket.socket() as probe: + probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + probe.bind(("127.0.0.1", port)) + log_path = root / "logs" / f"{role}.log" + with log_path.open("ab") as log: + child = subprocess.Popen( + command, + stdout=log, + stderr=subprocess.STDOUT, + env=env, + cwd=cwd, + start_new_session=True, + ) + try: + identity = process_identity(child.pid) + if not identity or child.poll() is not None: + raise RuntimeError(f"{role} exited; inspect {log_path}") + records[role] = { + "pid": child.pid, + "identity": identity, + "command": command, + "port": port, + } + save_json(root / "processes.json", records) + except BaseException: + if child.poll() is None: + child.terminate() + child.wait(timeout=10) + raise + + +def stop(root: Path, role: str | None = None) -> None: + """Stop selected owned sessions in reverse launch order, preserving all data. + + Check identity again before escalation. Do not signal a recycled PID or a + process that is no longer its own group leader. A vanished child is harmless. + """ + records = process_records(root) + for name in reversed(list(records)): + if role is not None and name != role: + continue + record = records[name] + if is_running(record): + _signal_owned(record, signal.SIGTERM) + deadline = time.monotonic() + 12 + while is_running(record) and time.monotonic() < deadline: + time.sleep(0.05) + if is_running(record): + _signal_owned(record, signal.SIGKILL) + deadline = time.monotonic() + 3 + while is_running(record) and time.monotonic() < deadline: + time.sleep(0.05) + if is_running(record): + raise RuntimeError(f"Could not stop owned service {name}") + try: + os.waitpid(record["pid"], os.WNOHANG) + except ChildProcessError: + pass # A later controller is not the parent of the stopped child. + records.pop(name) + save_json(root / "processes.json", records) + + +def _signal_owned(record: dict, signum: int) -> None: + """Signal a verified owned session; tolerate an exit during the check.""" + try: + if is_running(record) and os.getpgid(record["pid"]) == record["pid"]: + os.killpg(record["pid"], signum) + except ProcessLookupError: + pass + + +def wait_ready(root: Path, role: str, probe: Callable, timeout: float = 20): + """Poll a bounded public readiness probe while checking the owned child's life. + + Network/decoding failures remain retryable until the deadline. Return the + successful probe value; include the service log path on failure. + """ + deadline = time.monotonic() + timeout + last_error = None + while time.monotonic() < deadline: + if not is_running(process_records(root).get(role)): + raise RuntimeError(f"{role} stopped; inspect {root}/logs/{role}.log") + try: + value = probe() + if value is not None and value is not False: + return value + except (OSError, ValueError) as error: + last_error = error + time.sleep(0.05) + raise TimeoutError( + f"{role} readiness timed out ({last_error}); inspect {root}/logs/{role}.log" + ) diff --git a/scripts/integration/receiver.py b/scripts/integration/receiver.py new file mode 100644 index 0000000..83ec40d --- /dev/null +++ b/scripts/integration/receiver.py @@ -0,0 +1,133 @@ +"""Focused durable webhook receiver. No association selection or contract effects.""" + +import argparse +import json +import signal +from urllib.parse import urlsplit +from pathlib import Path +import falcon +from hio.base import doing +from hio.core import http +from keri.app import habbing +from keri.db import subing +from eoa_verifier.delivery.authing import ServiceAuthenticator, AuthenticationError + + +class ReceiptStore: + """Borrow a native database for durable fixture receipts and replay claims.""" + + def __init__(self, db): + """Bind disjoint non-duplicate receipt, attempt and control subdatabases.""" + self.events = subing.Suber(db=db, subkey="fixture.events.") + self.replays = subing.Suber(db=db, subkey="fixture.replays.") + self.attempts = subing.Suber(db=db, subkey="fixture.attempts.") + self.control = subing.Suber(db=db, subkey="fixture.control.") + + def claim_nonce(self, peer, nonce, expires_at): + """Use native no-overwrite insertion for one authentication replay claim.""" + return self.replays.put(keys=(peer, nonce), val=str(expires_at)) + + +class Receiver: + """Authenticate exact producer bytes and acknowledge only a durable receipt.""" + + def __init__(self, auth, store, target, drop): + """Borrow auth/store; target is the signed URL, drop loses the first ACK.""" + self.auth, self.store, self.target, self.drop = auth, store, target, drop + + def on_post(self, req, rep): + """Commit immutable event bytes before signing an attempt-bound ACK.""" + parsed = urlsplit(self.target) + relative = parsed.path + ("?" + parsed.query if parsed.query else "") + if req.relative_uri != relative: + raise falcon.HTTPBadRequest(description="unexpected signed target") + body = req.bounded_stream.read() + try: + received = self.auth.verify( + method="POST", + target=self.target, + action="status", + body=body, + headers=req.headers, + ) + except AuthenticationError as exc: + raise falcon.HTTPUnauthorized(description=str(exc)) from exc + try: + payload = json.loads(body) + key = payload["eventId"] + if not isinstance(key, str) or not key: + raise ValueError("missing event ID") + except (ValueError, KeyError, TypeError) as exc: + raise falcon.HTTPBadRequest(description="invalid fixture event") from exc + text = body.decode() + previous = self.store.events.get(keys=(key,)) + if previous is not None and previous != text: + raise falcon.HTTPConflict(description="conflicting event bytes") + self.store.events.put( + keys=(key,), val=text + ) # Native synchronous commit precedes ACK. + count = int(self.store.attempts.get(keys=(key,)) or "0") + 1 + self.store.attempts.pin(keys=(key,), val=str(count)) + if self.drop and self.store.control.put(keys=("dropped",), val="true"): + raise falcon.HTTPServiceUnavailable( + description="fixture dropped post-commit ACK" + ) + ack = json.dumps({"eventId": key, "stored": True}).encode() + headers, _ = self.auth.sign( + method="POST", + target=self.target, + action="ack", + body=ack, + request=received.reference, + status=200, + ) + rep.data = ack + rep.set_headers(headers) + + def on_get(self, req, rep): + """Expose retained receipt bytes and attempt counts for qualification.""" + rep.media = [ + { + "eventId": keys[0], + "body": value, + "attempts": int(self.store.attempts.get(keys=keys)), + } + for keys, value in self.store.events.getItemIter() + ] + + +def main(): + """Own receiver Habery and HIO listener for one explicitly prepared run.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", required=True) + args = parser.parse_args() + root = Path(args.root) + config = json.loads((root / "run.json").read_text()) + with habbing.openHby( + name="receiver", headDirPath=str(root / "receiver"), temp=False + ) as hby: + hab = hby.habByName("receiver") + hby.psr.parse(ims=bytearray((root / "verifier.cesr").read_bytes())) + store = ReceiptStore(hby.db) + auth = ServiceAuthenticator( + hab=hab, baser=store, peer_aid=config["verifierAid"] + ) + app = falcon.App() + app.add_route( + "/hook", Receiver(auth, store, config["webhookUrl"], config["dropAck"]) + ) + server = http.Server(host="127.0.0.1", port=config["receiverPort"], app=app) + doing.Doist(real=True, tock=0.01).do(doers=[http.ServerDoer(server=server)]) + + +def shutdown(signum, frame): + """Unwind the receiver context and scheduler on owned termination.""" + raise KeyboardInterrupt + + +if __name__ == "__main__": + signal.signal(signal.SIGTERM, shutdown) + try: + main() + except KeyboardInterrupt: + pass diff --git a/scripts/integration/scenario.py b/scripts/integration/scenario.py new file mode 100644 index 0000000..e8b6b59 --- /dev/null +++ b/scripts/integration/scenario.py @@ -0,0 +1,126 @@ +"""Standalone witnessed Verifier acceptance/delivery scenario, with no Oracle.""" + +import json +from pathlib import Path +from importlib.resources import files +from urllib.request import urlopen +from uuid import uuid4 + +from .artifacts import save_json +from .ceremony import complete_ceremony, open_ceremony +from .environment import ( + present_credential, + request_json, + restart_verifier, + wait_for_status, +) +from .processes import stop + +TEST_KEYS = {1: "0x" + "0" * 63 + "1", 2: "0x" + "0" * 63 + "2"} + + +def run_flow(root: Path, configuration: dict) -> None: + """Qualify acceptance, nonce rejection, receipt durability and exact retirement. + + Require a fresh scenario but preserve its stores/evidence after completion. + Each ceremony closes issuer stores before service restart or public reads. + """ + if (root / "flow-started").exists(): + raise ValueError( + "Full flow requires a fresh run; use status for this completed scenario" + ) + (root / "flow-started").write_text("Full flow requires fresh scenario state.\n") + # Exercise the same exact installed resources served to manual clients. + for schema in files("eoa_verifier.verification").joinpath("schema_data").iterdir(): + raw = schema.read_bytes() + said = json.loads(raw)["$id"] + with urlopen( + f"http://127.0.0.1:{configuration['schemaPort']}/oobi/{said}", timeout=2 + ) as response: + assert response.read() == raw + first = _issue(root, TEST_KEYS[1], str(uuid4())) + present_credential(root, configuration, first["said"]) + accepted = wait_for_status(configuration, first["said"], "accepted") + _assert_delivery_mode(configuration, accepted) + duplicate = _reject_reused_nonce(root, configuration, first["nonce"]) + receipts = ( + request_json(configuration["webhookUrl"]) + if not configuration["localOnly"] + else None + ) + if receipts is not None: + stop(root, "receiver") + restart_verifier(root, configuration) + reopened = wait_for_status(configuration, first["said"], "accepted") + assert reopened["accountObservation"] == accepted["accountObservation"] + if receipts is not None: + assert request_json(configuration["webhookUrl"]) == receipts + + second = _issue(root, TEST_KEYS[1], str(uuid4())) + present_credential(root, configuration, second["said"]) + wait_for_status(configuration, second["said"], "accepted") + # Downstream replacement does not revoke the first credential's acceptance. + assert ( + wait_for_status(configuration, first["said"], "accepted")["eventId"] + == accepted["eventId"] + ) + for descriptor in (first, second): + with open_ceremony(root) as ceremony: + complete_ceremony(ceremony, ceremony.revoke_association(descriptor["said"])) + present_credential(root, configuration, descriptor["said"]) + wait_for_status(configuration, descriptor["said"], "revoked") + if receipts is not None: + _assert_receipts(configuration, first, second, duplicate) + save_json( + root / "flow.json", + { + "first": first, + "second": second, + "rejected": duplicate, + "accountObservation": accepted["accountObservation"], + }, + ) + + +def _issue(root: Path, wallet_key: str, nonce: str) -> dict: + """Open one native issuer session and return its exported association descriptor.""" + with open_ceremony(root) as ceremony: + return complete_ceremony( + ceremony, ceremony.issue_association(wallet_key, nonce) + ) + + +def _reject_reused_nonce(root: Path, configuration: dict, nonce: str) -> dict: + """Prove a valid different-wallet credential cannot reuse an accepted pair.""" + duplicate = _issue(root, TEST_KEYS[2], nonce) + present_credential(root, configuration, duplicate["said"]) + rejected = wait_for_status(configuration, duplicate["said"], "rejected") + assert rejected["reason"] == "NONCE_REUSED" and rejected["delivery"] is None + return duplicate + + +def _assert_delivery_mode(configuration: dict, accepted: dict) -> None: + """Distinguish target-free acceptance from retried authenticated delivery.""" + if configuration["localOnly"]: + assert accepted["delivery"] is None + else: + assert accepted["delivery"]["acknowledged"] + assert ( + accepted["delivery"]["attempts"] >= 2 + ) # Receiver deliberately drops its first ACK. + + +def _assert_receipts( + configuration: dict, first: dict, second: dict, duplicate: dict +) -> None: + """Require separate accepted/revoked receipts and no event for nonce rejection.""" + events = request_json(configuration["webhookUrl"]) + assert not any( + json.loads(event["body"])["associationSaid"] == duplicate["said"] + for event in events + ) + assert {event["eventId"] for event in events} == { + f"{descriptor['said']}:{revision}" + for descriptor in (first, second) + for revision in (1, 2) + } diff --git a/tests/delivery/test_completion_gaps.py b/tests/delivery/test_completion_gaps.py new file mode 100644 index 0000000..be8ba8b --- /dev/null +++ b/tests/delivery/test_completion_gaps.py @@ -0,0 +1,110 @@ +"""Producer recovery at durable receiver and sender completion boundaries.""" + +import falcon +import pytest +from hio.base import doing +from hio.core import http +from keri.app import habbing + +from eoa_verifier.delivery.authing import ServiceAuthenticator +from eoa_verifier.delivery.delivering import WebhookSender +from scripts.integration.receiver import ReceiptStore, Receiver +from tests.support.network import free_port + + +@pytest.mark.parametrize("gap", ["none", "before-ack", "before-sender-completion"]) +def test_real_sender_recovers_commit_ack_gaps( + verified_store, tmp_path, monkeypatch, gap +): + """Reopen durable stores and retry identical bytes after either commit gap.""" + with ( + habbing.openHby(name="producer", temp=True) as producer, + habbing.openHby( + name="receiver", headDirPath=str(tmp_path / "receiver"), temp=False + ) as receiver, + ): + sender_hab = producer.makeHab(name="producer") + receiver_hab = receiver.makeHab(name="receiver") + producer.psr.parse(ims=bytearray(receiver_hab.makeOwnEvent(sn=0))) + receiver.psr.parse(ims=bytearray(sender_hab.makeOwnEvent(sn=0))) + port = free_port() + target = f"http://127.0.0.1:{port}/hook" + store = ReceiptStore(receiver.db) + auth = ServiceAuthenticator( + hab=receiver_hab, baser=store, peer_aid=sender_hab.pre + ) + app = falcon.App() + app.add_route("/hook", Receiver(auth, store, target, False)) + server = http.ServerDoer( + server=http.Server(host="127.0.0.1", port=port, app=app) + ) + baser = verified_store + accepted = baser.accept( + "association", + association={"issuerAid": sender_hab.pre}, + nonce="gap-fixture", + destination=target, + peer_aid=receiver_hab.pre, + ) + + def fail(*args, **kwargs): + """Model loss at a precise durable/network boundary.""" + raise RuntimeError("simulated process loss") + + def attempt(*, expect_failure=False): + """Own native HTTP tasks until exactly one durable sender attempt settles.""" + sender = WebhookSender(baser=baser, hab=sender_hab, timeout=1) + starting = baser.outbox.get(keys=(accepted.eventId,)).attempts + + def settled(tymth, tock=0.0, **kwargs): + yield tock + while True: + event = baser.outbox.get(keys=(accepted.eventId,)) + if event.acknowledged or ( + event.attempts > starting + and event.error + and event.error + != "attempt started; authenticated ACK not recorded" + ): + parent.remove([server, sender]) + return + yield 0.01 + + parent = doing.DoDoer(doers=[server, sender, doing.doify(settled)]) + scheduler = doing.Doist(real=True, tock=0.01, limit=3) + if expect_failure: + with pytest.raises(RuntimeError, match="simulated process loss"): + scheduler.do(doers=[parent]) + else: + scheduler.do(doers=[parent]) + assert parent.done + assert not server.server.servant.opened + + with monkeypatch.context() as patch: + if gap == "before-ack": + patch.setattr(auth, "sign", fail) + elif gap == "before-sender-completion": + patch.setattr(baser, "delivery_result", fail) + attempt(expect_failure=(gap == "before-sender-completion")) + + committed = store.events.get(keys=(accepted.eventId,)) + assert committed == baser.outbox.get(keys=(accepted.eventId,)).body + if gap != "none": + assert not baser.outbox.get(keys=(accepted.eventId,)).acknowledged + baser.close() + baser.reopen() + # Rebind receipt subdatabases after a native persistent reopen. + receiver.db.close(clear=False) + receiver.db.reopen() + store = ReceiptStore(receiver.db) + auth.baser = store + app = falcon.App() + app.add_route("/hook", Receiver(auth, store, target, False)) + server = http.ServerDoer( + server=http.Server(host="127.0.0.1", port=port, app=app) + ) + attempt() + acknowledged = baser.outbox.get(keys=(accepted.eventId,)) + assert acknowledged.acknowledged + assert acknowledged.attempts == (1 if gap == "none" else 2) + assert list(store.events.getItemIter()) == [((accepted.eventId,), committed)] diff --git a/tests/integration/test_environment.py b/tests/integration/test_environment.py new file mode 100644 index 0000000..83c9c28 --- /dev/null +++ b/tests/integration/test_environment.py @@ -0,0 +1,118 @@ +"""Functional lifecycle failures must preserve foreign processes and data.""" + +import socket +import subprocess +import sys + +import pytest + +from scripts.integration.artifacts import load_json, save_json, snapshot_source +from scripts.integration.processes import ( + free_port, + is_running, + launch, + process_records, + stop, + wait_ready, +) + + +def test_foreign_listener_survives_refused_launch(tmp_path): + """A listening port never authorizes adopting or terminating its owner.""" + (tmp_path / "logs").mkdir() + with socket.socket() as foreign: + foreign.bind(("127.0.0.1", 0)) + foreign.listen() + with pytest.raises(OSError): + launch( + tmp_path, + "foreign", + [sys.executable, "-c", "raise AssertionError"], + port=foreign.getsockname()[1], + ) + stop(tmp_path) + with socket.create_connection(foreign.getsockname(), timeout=1): + pass + assert not process_records(tmp_path) + + +def test_owned_process_restart_and_stop_preserve_artifacts(tmp_path): + """Use literal shell-sensitive paths; restart promptly and keep stopped state.""" + root = tmp_path / "a space's $literal; run" + (root / "logs").mkdir(parents=True) + artifact = root / "sentinel.json" + save_json(artifact, {"preserve": True}) + port = free_port() + command = [ + sys.executable, + "-m", + "http.server", + str(port), + "--bind", + "127.0.0.1", + "--directory", + str(root), + ] + + def ready(): + with socket.create_connection(("127.0.0.1", port), timeout=0.1): + return True + + try: + launch(root, "server", command, port=port) + wait_ready(root, "server", ready) + first = process_records(root)["server"] + launch(root, "server", command, port=port) + assert process_records(root)["server"] == first + stop(root) + assert not is_running(first) + launch(root, "server", command, port=port) + wait_ready(root, "server", ready) + assert process_records(root)["server"]["pid"] != first["pid"] + finally: + stop(root) + assert load_json(artifact) == {"preserve": True} + assert not process_records(root) + + +def test_candidate_snapshot_preserves_work_and_excludes_ignored_stores(tmp_path): + """Build actual Git inputs while leaving operator state and stale builds alone.""" + source = tmp_path / "source" + source.mkdir() + subprocess.run(["git", "init", "--quiet", str(source)], check=True) + + def git(*args): + subprocess.run( + ["git", "-C", str(source), *args], check=True, capture_output=True + ) + + git("config", "user.name", "Disposable fixture") + git("config", "user.email", "fixture@example.invalid") + (source / ".gitignore").write_text("state/\nbuild/\n*.egg-info/\n") + (source / "current.py").write_text("original = True\n") + git("add", ".") + git("commit", "--quiet", "-m", "Create disposable source") + (source / "current.py").write_text("candidate = True\n") + for directory in ("state", "build", "old.egg-info"): + (source / directory).mkdir() + (source / directory / "sentinel").write_bytes(b"operator data") + destination = tmp_path / "build candidate" + provenance = snapshot_source(source, destination) + assert len(provenance["revision"]) == 40 and len(provenance["sha256"]) == 64 + assert sorted(p.name for p in destination.iterdir()) == [".gitignore", "current.py"] + assert (destination / "current.py").read_text() == "candidate = True\n" + assert (source / "state/sentinel").read_bytes() == b"operator data" + + +@pytest.mark.parametrize("wheel_inputs", [False, True]) +def test_snapshot_refuses_source_overlap_before_writing(tmp_path, wheel_inputs): + """A nested run must never recursively copy its own stores or build output.""" + from scripts.integration.artifacts import copy_tool_inputs + + source = tmp_path / "source" + source.mkdir() + destination = source / "run/tools" + copy = copy_tool_inputs if wheel_inputs else snapshot_source + with pytest.raises(ValueError, match="outside its source"): + copy(source, destination) + assert not (source / "run").exists() diff --git a/tests/integration/test_ipex_verification.py b/tests/integration/test_ipex_verification.py index 2d4f9c0..5e4090e 100644 --- a/tests/integration/test_ipex_verification.py +++ b/tests/integration/test_ipex_verification.py @@ -20,7 +20,7 @@ from eoa_verifier.runtime.config import ServiceConfig from eoa_verifier.verification.constants import LE_SCHEMA, QVI_SCHEMA from eoa_verifier.verification.eoa import build_challenge -from tests.support.issuers import ( +from scripts.integration.issuers import ( KEY, IssuerEscrows, anchor, @@ -358,9 +358,9 @@ def run(tymth, tock=0.0, **kwa): yield from send(revocation) deadline = workflow.tyme + 5 while runtime.rgy.reger.getTae(dbing.snKey(creder.said, 1)) is None: - assert ( - workflow.tyme < deadline - ), "revocation did not enter KERIpy anchor escrow" + assert workflow.tyme < deadline, ( + "revocation did not enter KERIpy anchor escrow" + ) yield 0.01 retirement = next(d for d in runtime.doers if isinstance(d, RetirementDoer)) retirement.recur(workflow.tyme) @@ -377,9 +377,9 @@ def run(tymth, tock=0.0, **kwa): while ( runtime.rgy.reger.tevers[creder.regi].vcState(creder.said).et != "rev" ): - assert ( - workflow.tyme < deadline - ), "verified revocation escrow did not resolve" + assert workflow.tyme < deadline, ( + "verified revocation escrow did not resolve" + ) yield 0.01 assert runtime.baser.associations.get(keys=(creder.said,)) == accepted workflow.remove([runtime, client_doer]) diff --git a/tests/qualification/__init__.py b/tests/qualification/__init__.py new file mode 100644 index 0000000..0539736 --- /dev/null +++ b/tests/qualification/__init__.py @@ -0,0 +1 @@ +"""Installed CLI qualification without Oracle or contracts.""" diff --git a/tests/qualification/test_verifier_service.py b/tests/qualification/test_verifier_service.py new file mode 100644 index 0000000..dd2d018 --- /dev/null +++ b/tests/qualification/test_verifier_service.py @@ -0,0 +1,64 @@ +"""The same standalone commands used by operators, against an installed wheel.""" + +import os +from pathlib import Path +import subprocess +import sys +import pytest + +from scripts.integration.artifacts import source_revision + + +@pytest.mark.parametrize("local_only", [False, True]) +def test_installed_verifier_qualifies_without_oracle_or_comply(tmp_path, local_only): + root = Path(__file__).resolve().parents[2] + wheel = os.environ.get("EOA_VERIFIER_WHEEL") + assert wheel and Path(wheel).is_file(), ( + "Set EOA_VERIFIER_WHEEL to the fresh qualified wheel" + ) + run = tmp_path / "standalone" + base = [sys.executable, "-m", "scripts.integration.env"] + prepare = [ + *base, + "prepare", + "--run-dir", + str(run), + "--witness-count", + "1", + "--verifier-wheel", + wheel, + "--tool-revision", + os.getenv("GITHUB_SHA") or source_revision(root), + ] + subprocess.run( + prepare, check=True, timeout=180, capture_output=True, text=True, cwd=root + ) + try: + subprocess.run( + [ + str(run / "venv/bin/python"), + "-c", + "from importlib.util import find_spec; assert find_spec('vlei_oracle') is None", + ], + check=True, + ) + completed = subprocess.run( + [ + *base, + "qualify", + "--run-dir", + str(run), + *(["--local-only"] if local_only else []), + ], + check=False, + timeout=180, + capture_output=True, + text=True, + cwd=root, + ) + assert completed.returncode == 0, (completed.stdout, completed.stderr, str(run)) + assert (run / "flow.json").is_file() + finally: + subprocess.run( + [*base, "stop", "--run-dir", str(run)], check=True, timeout=30, cwd=root + ) diff --git a/tests/support/issuers.py b/tests/support/issuers.py index 1f49320..902f3d9 100644 --- a/tests/support/issuers.py +++ b/tests/support/issuers.py @@ -2,17 +2,12 @@ from eth_account import Account from eth_account.messages import encode_typed_data -from hio.base import doing from keri import core -from keri.app import habbing, signing -from keri.core import coring, eventing, parsing, serdering -from keri.db import dbing -from keri.kering import Protocols, versify -from keri.vc import protocoling -from keri.vdr import credentialing, verifying +from keri.core import coring -from eoa_verifier.verification.constants import ASSOCIATION_SCHEMA, LE_SCHEMA -from eoa_verifier.verification.eoa import DOMAIN_TAG, PROOF_ALGORITHM, build_challenge +from eoa_verifier.verification.eoa import build_challenge + +from scripts.integration.issuers import association_from_challenge KEY = "0x" + "0" * 63 + "1" @@ -30,273 +25,6 @@ def candidate(): return association_from_challenge(challenge, "0x" + sig.hex(), said).sad -def anchor(hab, event) -> serdering.SerderKERI: - """Append a signed TEL seal to hab’s KEL and return its KERIpy interaction Serder.""" - message = hab.interact( - data=[eventing.SealEvent(event.pre, event.snh, event.said)._asdict()] - ) - return serdering.SerderKERI(raw=message) - - -def replay(hab, rgy, registry, creder) -> bytes: - """Return issuer KEL, registry/credential TEL and accepted ACDC bytes from KERIpy stores. - - The caller supplies an issued credential and its registry. Prepend upstream - streams when the receiver also needs LE/QVI evidence; this helper does no network I/O. - """ - return b"".join( - [ - *hab.db.clonePreIter(pre=hab.pre), - *rgy.reger.clonePreIter(pre=registry.regk), - *rgy.reger.clonePreIter(pre=creder.said), - signing.serialize(*rgy.reger.cloneCred(creder.said)), - ] - ) - - -def issue_credential(issuer, registry, creder): - """Schedule KERIpy TEL/KEL issuance for creder in registry using the supplied Credentialer. - - Yield 0.01 HIO seconds until completion, then return None. The caller must run - Registrar, Credentialer and escrow Doers and own their stores. - """ - issuance = registry.issue(said=creder.said, dt=creder.attrib.get("dt")) - anc = anchor(registry.hab, issuance) - issuer.issue(creder, issuance) - issuer.registrar.issue(creder, issuance, anc) - while not issuer.complete(creder.said): - yield 0.01 - - -def revoke_credential(issuer, registry, creder): - """Anchor verified revocation and schedule it on the supplied issuer's Registrar. - - Yield 0.01 HIO seconds until witnessed completion, then return None. The caller - owns scheduling and later transports the resulting TEL/KEL evidence. - """ - revocation = registry.revoke(said=creder.said) - issuer.registrar.revoke(creder, revocation, anchor(registry.hab, revocation)) - while not issuer.registrar.complete(creder.said, sn=revocation.sn): - yield 0.01 - - -def receive(hby, rgy, stream) -> None: - """Give an issuer supporting KERI evidence through the standard parser. - - QVI and LE use this local delivery before issuing their own credentials. - Verifier delivery is tested separately through HTTP. Acceptance is established - by KERIpy's verifier, including its normal escrow processing. - """ - verifier = verifying.Verifier(hby=hby, reger=rgy.reger) - parsing.Parser().parse( - ims=bytearray(stream), - kvy=eventing.Kevery(db=hby.db, lax=False, local=False), - tvy=verifier.tvy, - vry=verifier, - ) - verifier.processEscrows() - - -def rules(schema) -> dict: - """Return a SAID-bearing rules dict with the exact disclaimers required by the supplied credential schema.""" - fields = schema.sed["properties"]["r"]["oneOf"][1]["properties"] - return coring.Saider.saidify( - sad={ - "d": "", - **{ - name: {"l": fields[name]["properties"]["l"]["const"]} - for name in ("usageDisclaimer", "issuanceDisclaimer") - }, - } - )[1] - - -def grant( - hab, - rgy, - creder, - recipient, - *, - acdc=None, -) -> bytes: - """Return IPEX Grant bytes addressed to recipient from the supplied issuer stores. - - Use the issued creder plus KERIpy issuance/anchor embeds; acdc can override - serialized credential bytes. Source - credentials travel separately so tests can withhold them. This builds, not sends. - """ - acdc = ( - signing.serialize(*rgy.reger.cloneCred(creder.said)) if acdc is None else acdc - ) - iss = rgy.reger.cloneTvtAt(creder.said) - issuance = serdering.SerderKERI(raw=iss) - sealing_event = hab.db.fetchLastSealingEventByEventSeal( - hab.pre, - seal={"i": issuance.pre, "s": issuance.snh, "d": issuance.said}, - ) - anc = hab.db.cloneEvtMsg(pre=hab.pre, fn=0, dig=sealing_event.said) - exn, attachments = protocoling.ipexGrantExn( - hab=hab, - recp=recipient, - message="External association", - acdc=acdc, - iss=iss, - anc=anc, - ) - return exn.raw + attachments - - -class IssuerEscrows(doing.Doer): - """Process each issuer's registry and credential escrows on the HIO clock. - - The KLI normally performs this alongside its mailbox processing. Local - issuer-to-holder delivery here has no mailbox; Registrar and Credentialer - still run as their own HIO doers. - """ - - def __init__(self, issuers): - """Borrow issuer runtimes in issuers and recur every 0.03125 HIO seconds; do not own their stores.""" - self.issuers = issuers - super().__init__(tock=0.03125) - - def recur(self, tyme): - """Process borrowed registry/verifier escrows once and return False to remain scheduled.""" - for issuer in self.issuers: - issuer.rgy.processEscrows() - issuer.verifier.processEscrows() - return False - - -def issuer_for(hby, rgy): - """Return a KERIpy Credentialer with Registrar and Verifier borrowing the supplied Habery/Regery.""" - registrar = credentialing.Registrar(hby=hby, rgy=rgy, counselor=None) - return credentialing.Credentialer( - hby=hby, - rgy=rgy, - registrar=registrar, - verifier=verifying.Verifier(hby=hby, reger=rgy.reger), - ) - - -def open_issuers(stack, schemas, *, base, temp, witness): - """Return actor and issuer dictionaries for isolated witnessed GEDA/QVI/LE controllers. - - Pin supplied credential schemas and configure QVI delegation to GEDA. stack owns store closure; - temp selects disposable stores, base selects their namespace, witness supplies - the witness AID. The caller must schedule the returned KERIpy issuance tasks. - """ - actors, issuers = {}, {} - for name in ("geda", "qvi", "le"): - hby = stack.enter_context(habbing.openHby(name=name, base=base, temp=temp)) - for schema in schemas: - hby.db.schema.pin(keys=(schema.said,), val=schema) - hab = hby.makeHab( - name=name, - icount=1, - isith="1", - ncount=1, - nsith="1", - wits=[witness.pre], - toad=1, - **({"delpre": actors["geda"][1].pre} if name == "qvi" else {}), - ) - rgy = credentialing.Regery(hby=hby, name=name, base=base, temp=temp) - stack.callback(rgy.reger.close, clear=temp) - actors[name] = (hby, hab, rgy) - # Single-sig needs no multisig Counselor; retain the KLI lifecycle doers. - issuers[name] = issuer_for(hby, rgy) - return actors, issuers - - -def collect_receipts(issuer, hab, sn): - """Queue hab/sn on the issuer’s KERIpy receipt worker; yield until its completion cue, then return None.""" - receiptor = issuer.registrar.receiptor - receiptor.msgs.append({"pre": hab.pre, "sn": sn}) - while not any(cue["pre"] == hab.pre and cue["sn"] == sn for cue in receiptor.cues): - yield 0.01 - - -def approve_qvi(actors, issuers): - """Yield through real witnessed QVI delegation approval among the supplied actors. - - Use the KLI authorizer seal and replay accepted evidence to issuer stores. - Return None after GEDA accepts the delegation; the caller owns actor scheduling. - """ - geda_hby, geda, _geda_rgy = actors["geda"] - qvi_hby, qvi, qvi_rgy = actors["qvi"] - _le_hby, le, _le_rgy = actors["le"] - # Introduce the non-delegated inception events before GEDA's approval. - yield from collect_receipts(issuers["geda"], geda, 0) - yield from collect_receipts(issuers["le"], le, 0) - inception = serdering.SerderKERI(raw=qvi.makeOwnEvent(sn=0)) - geda.interact(data=[eventing.SealEvent(qvi.pre, "0", inception.said)._asdict()]) - couple = coring.Seqner(sn=geda.kever.sn).qb64b + geda.kever.serder.saidb - for hby in (geda_hby, qvi_hby): - hby.db.setAes(dbing.dgKey(qvi.pre, inception.said), couple) - yield from collect_receipts(issuers["geda"], geda, geda.kever.sn) - receive(qvi_hby, qvi_rgy, b"".join(geda.db.clonePreIter(pre=geda.pre))) - # The receipt worker sends cloneDelegation context before the delegated event. - yield from collect_receipts(issuers["qvi"], qvi, 0) - geda_hby.psr.parse(ims=bytearray(b"".join(qvi.db.clonePreIter(pre=qvi.pre)))) - geda_hby.kvy.processEscrowDelegables() - receive(qvi_hby, qvi_rgy, b"".join(le.db.clonePreIter(pre=le.pre))) - assert qvi.pre in geda_hby.kevers, "GEDA has not accepted QVI delegation" - - -def association_from_challenge(challenge, signature, registry): - """Return a SAID-bearing association ACDC for typed challenge, signature and registry. - - Require the exact EOA challenge shape and canonical registry SAID, raising - ValueError on mismatch. Build nested proof/attribute/LE-edge SAIDs but do not - verify the wallet signature, issue the credential or establish KERIpy credential acceptance. - """ - fields = challenge["message"] - expected = build_challenge( - issuer_aid=fields["issuerAid"], - le_vlei_said=fields["leVleiSaid"], - ext_id=fields["extId"], - nonce=fields["nonce"], - ) - if challenge != expected: - raise ValueError("challenge does not match the EOA profile") - if coring.Saider(qb64=registry).qb64 != registry: - raise ValueError("registry must be a canonical KERI SAID") - proof = coring.Saider.saidify( - sad={ - "d": "", - "alg": PROOF_ALGORITHM, - "tag": DOMAIN_TAG, - "sig": signature, - } - )[1] - attributes = coring.Saider.saidify( - sad={ - "d": "", - "extId": fields["extId"], - "proof": proof, - } - )[1] - edge = coring.Saider.saidify( - sad={ - "d": "", - "le": {"n": fields["leVleiSaid"], "s": LE_SCHEMA, "o": "I2I"}, - } - )[1] - return serdering.SerderACDC( - sad={ - "v": versify(protocol=Protocols.acdc, size=0), - "d": "", - "u": fields["nonce"], - "i": fields["issuerAid"], - "ri": registry, - "s": ASSOCIATION_SCHEMA, - "a": attributes, - "e": edge, - }, - makify=True, - ) - - def signed_notice(runtime, grants, sender, embedded, attachments=b""): """Deliver an actual signed opening Grant through KERIpy EXN authentication.""" from keri.core import coring, parsing, serdering