diff --git a/api/scripts/e2e_paid_path.py b/api/scripts/e2e_paid_path.py index 90652af..9d18154 100644 --- a/api/scripts/e2e_paid_path.py +++ b/api/scripts/e2e_paid_path.py @@ -20,6 +20,9 @@ has to take the payer from the facilitator's verify. Its USDC balance drops by exactly the price and `has_license` becomes true on chain. 4. The bytes served hash to the on-chain content_hash. +4b. STE-48: the holder's address alone, a proof signed by another key, a replayed proof, + a stranger's proof presented for the holder, and a proof for another version are all + 401 with no artifact and no payment challenge (and, with --expiry-wait, an expired one). 5. The same agent signs a SECOND payment for the licence it now holds; the API must serve it as held and its USDC balance must not move. @@ -117,6 +120,30 @@ def field(name: str) -> str | None: } +def sep53_sign(keypair: Keypair, message: str) -> str: + """SEP-53, as a wallet's signMessage and `stellar message sign` produce it.""" + import base64 + import hashlib + + digest = hashlib.sha256(b"Stellar Signed Message:\n" + message.encode("utf-8")).digest() + return base64.b64encode(keypair.sign(digest)).decode() + + +def proof_headers( + http: httpx.Client, api: str, skill: str, version: str, agent: str, signer: Keypair +) -> tuple[dict, dict]: + challenge = http.get(f"{api}/use/{skill}/{version}/challenge", params={"agent": agent}) + if challenge.status_code != 200: + raise E2EFailure(f"challenge endpoint answered {challenge.status_code}: {challenge.text}") + body = challenge.json() + headers = { + "X-AGENT-ADDRESS": agent, + "X-STERISH-PROOF-NONCE": body["nonce"], + "X-STERISH-PROOF-SIGNATURE": sep53_sign(signer, body["message"]), + } + return headers, body + + def content_hash_of_served(body: bytes) -> str: sys.path.insert(0, str(REPO / "pipeline" / "src")) from sterish_pipeline.content_hash import content_hash @@ -133,6 +160,11 @@ def main() -> int: parser.add_argument("--dangerous", default="com.fixtures.poisoned.token-drainer@1.0.0") parser.add_argument("--funder-env", default="AUDITOR_SECRET") parser.add_argument("--out", default=None) + parser.add_argument( + "--expiry-wait", action="store_true", + help="also wait out one challenge and prove an expired proof is refused " + "(takes STERISH_PROOF_TTL_SECONDS of the target API)", + ) args = parser.parse_args() api = args.api.rstrip("/") @@ -224,12 +256,12 @@ def main() -> int: # --- 4. the bytes ------------------------------------------------------------------- print("\n4. the bytes served are the bytes the registry pinned") - served = http.get( - f"{api}/use/{args.skill}/{args.version}", headers={"X-AGENT-ADDRESS": agent.public_key} - ) + use_url = f"{api}/use/{args.skill}/{args.version}" + proven, _ = proof_headers(http, api, args.skill, args.version, agent.public_key, agent) + served = http.get(use_url, headers=proven) check( served.status_code == 200 and served.headers["X-STERISH-LICENSE"] == "held", - "licence holder served without payment", + "licence holder served without payment, with a SEP-53 ownership proof", ) onchain = http.get(f"{api}/check/{args.skill}/{args.version}").json()["content_hash"] check( @@ -238,6 +270,60 @@ def main() -> int: ) evidence["content_hash"] = onchain + # --- 4b. the licence cannot be borrowed (STE-48) ------------------------------------ + print("\n4b. naming the holder is not enough: every forged or reused proof is refused") + stranger = Keypair.random() + evidence["stranger"] = stranger.public_key + + def refused(response: httpx.Response, code: str, what: str) -> None: + body = response.json() if response.headers.get("content-type", "").startswith( + "application/json" + ) else {} + check( + response.status_code == 401 + and body.get("error") == code + and "PAYMENT-REQUIRED" not in response.headers + and "X-STERISH-LICENSE" not in response.headers, + f"{what} -> 401 {code}, no artifact, no payment challenge", + ) + + refused( + http.get(use_url, headers={"X-AGENT-ADDRESS": agent.public_key}), + "OWNERSHIP_PROOF_REQUIRED", "holder's address only", + ) + refused( + http.get(use_url, params={"agent": agent.public_key}), + "OWNERSHIP_PROOF_REQUIRED", "holder's address as ?agent=", + ) + forged, _ = proof_headers(http, api, args.skill, args.version, agent.public_key, stranger) + refused(http.get(use_url, headers=forged), "INVALID_OWNERSHIP_PROOF", + "holder's challenge signed by another key") + refused(http.get(use_url, headers=proven), "INVALID_OWNERSHIP_PROOF", + "the proof that was already used, replayed") + own, _ = proof_headers(http, api, args.skill, args.version, stranger.public_key, stranger) + refused(http.get(use_url, headers=dict(own, **{"X-AGENT-ADDRESS": agent.public_key})), + "INVALID_OWNERSHIP_PROOF", "a stranger's valid proof presented for the holder") + other_version, _ = proof_headers( + http, api, args.skill, args.version + ".other", agent.public_key, agent + ) + refused(http.get(use_url, headers=other_version), "INVALID_OWNERSHIP_PROOF", + "a proof for another version") + stranger_paying = http.get(use_url, headers=own) + check(stranger_paying.status_code == 402 and "PAYMENT-REQUIRED" in stranger_paying.headers, + "a stranger proving its OWN address, with no licence, is asked to pay (402)") + + if args.expiry_wait: + pending, challenge = proof_headers( + http, api, args.skill, args.version, agent.public_key, agent + ) + wait = max(0, challenge["expires_at"] - int(time.time())) + 3 + print(f" waiting {wait}s for the challenge to expire") + time.sleep(wait) + refused(http.get(use_url, headers=pending), "INVALID_OWNERSHIP_PROOF", + "a correctly signed proof after its challenge expired") + evidence["ownership_proof"] = "held with proof 200; address-only, forged, replayed, " \ + "borrowed, wrong-version" + (", expired" if args.expiry_wait else "") + " all 401" + # --- 5. a second payment for a held licence is not charged --------------------------- print("\n5. a second signed payment for a licence already held is not charged") second = run_buyer( diff --git a/api/src/sterish_api/config.py b/api/src/sterish_api/config.py index 5013510..5944622 100644 --- a/api/src/sterish_api/config.py +++ b/api/src/sterish_api/config.py @@ -60,6 +60,10 @@ class Settings: # (STE-33). Not a thread pool size for the app — FastAPI already has one; this # bounds the fan-out *inside* one handler. See fanout.py. chain_concurrency: int + # Lifetime of a licence ownership challenge (STE-48), seconds. Long enough for a + # human to approve a wallet prompt, short enough that a captured signature is + # worthless soon after. Clamped to [30, 900]. + proof_ttl_seconds: int @property def network(self) -> str: @@ -127,6 +131,7 @@ def load_settings() -> Settings: indexer_poll_seconds=_env_int("INDEXER_POLL_SECONDS", 8), indexer_chunk_ledgers=_env_int("INDEXER_CHUNK_LEDGERS", 4000), report_base_url=os.getenv("REPORT_BASE_URL", "").rstrip("/"), + proof_ttl_seconds=min(900, max(30, _env_int("STERISH_PROOF_TTL_SECONDS", 300))), ) diff --git a/api/src/sterish_api/main.py b/api/src/sterish_api/main.py index dd2de43..f28c12b 100644 --- a/api/src/sterish_api/main.py +++ b/api/src/sterish_api/main.py @@ -12,7 +12,7 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse -from . import chain, indexer, payments, x402 +from . import chain, indexer, payments, proofs, x402 from .chain import ChainError, ContractError, NotConfiguredError from .config import settings from .errors import ( @@ -55,6 +55,7 @@ async def lifespan(app: FastAPI): indexer.init_db() # The payments ledger is not a cache (STE-42): created here, never rebuilt. payments.init_db() + proofs.init_db() task = None if settings.indexer_enabled: diff --git a/api/src/sterish_api/proofs.py b/api/src/sterish_api/proofs.py new file mode 100644 index 0000000..66074c3 --- /dev/null +++ b/api/src/sterish_api/proofs.py @@ -0,0 +1,218 @@ +"""Proof that the caller controls the address it claims (STE-48). + +`GET /use` serves an already-licensed artifact for free. Before STE-48 "already +licensed" was decided by `X-AGENT-ADDRESS` alone, and licence holders are public on +chain, so anyone could name a holder's address and receive what that holder paid +for. A soulbound licence that anyone can borrow is not soulbound. + +The free path now needs a signature from the address's own key over a short-lived, +single-use challenge the API issued: + +1. `GET /use/{skill_id}/{version}/challenge?agent=G...` issues a nonce and returns the + exact message to sign. +2. The caller signs it with **SEP-53** — ed25519 over + `SHA-256("Stellar Signed Message:\\n" + message)` — which is what a wallet's SEP-43 + `signMessage` produces and what `stellar message sign` produces. +3. The caller repeats `GET /use/...` with `X-AGENT-ADDRESS`, `X-STERISH-PROOF-NONCE` and + `X-STERISH-PROOF-SIGNATURE` (base64). + +The message is rebuilt here from the stored row, never taken from the request, so a +client cannot get a different text accepted. A nonce is bound to one agent, one skill +and one version, expires, and is consumed by the first request that proves with it. +A failed signature does not consume it: otherwise anyone who guessed a nonce could +burn another caller's challenge, and a nonce is 128 random bits, so guessing is not a +path to anything else. + +Stored in the payments database file (its own table): the rows must survive a +restart, or a nonce used just before one could be replayed just after. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import secrets +import sqlite3 +import threading +import time +from dataclasses import dataclass +from typing import Any + +from stellar_sdk import Keypair +from stellar_sdk.exceptions import BadSignatureError + +from .config import settings + +SEP53_PREFIX = b"Stellar Signed Message:\n" +MESSAGE_TITLE = "Sterish licence ownership proof" + +NONCE_HEADER = "X-STERISH-PROOF-NONCE" +SIGNATURE_HEADER = "X-STERISH-PROOF-SIGNATURE" + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS proof_challenges ( + nonce TEXT PRIMARY KEY, + agent TEXT NOT NULL, + skill_id TEXT NOT NULL, + version TEXT NOT NULL, + issued_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + used_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_proof_expiry ON proof_challenges (expires_at); +""" + +# Rows past expiry are kept this long before being purged, so a replay of a recently +# used nonce is still reported as "already used" rather than "unknown". +_PURGE_GRACE_SECONDS = 3600 + +_lock = threading.Lock() + + +class ProofInvalid(Exception): + """The proof was supplied and is wrong. `reason` is safe to return to the caller.""" + + def __init__(self, reason: str): + super().__init__(reason) + self.reason = reason + + +@dataclass(frozen=True) +class Challenge: + agent: str + skill_id: str + version: str + nonce: str + issued_at: int + expires_at: int + + @property + def message(self) -> str: + return build_message( + self.agent, self.skill_id, self.version, self.nonce, self.expires_at + ) + + +def build_message(agent: str, skill_id: str, version: str, nonce: str, expires_at: int) -> str: + """The exact text a caller signs. Frozen: changing it invalidates every client. + + The network passphrase is in the text so a proof made for testnet can never be + mistaken for one made against a mainnet deployment of the same API. + """ + return "\n".join( + [ + MESSAGE_TITLE, + f"agent: {agent}", + f"skill: {skill_id}", + f"version: {version}", + f"nonce: {nonce}", + f"expires: {expires_at}", + f"network: {settings.network_passphrase}", + ] + ) + + +def sep53_digest(message: str) -> bytes: + return hashlib.sha256(SEP53_PREFIX + message.encode("utf-8")).digest() + + +def _connect() -> sqlite3.Connection: + conn = sqlite3.connect(settings.payments_db_path, check_same_thread=False) + conn.row_factory = sqlite3.Row + conn.executescript(_SCHEMA) + return conn + + +def init_db() -> None: + with _lock, _connect(): + pass + + +def issue(agent: str, skill_id: str, version: str, *, now: int | None = None) -> Challenge: + now = int(time.time()) if now is None else now + challenge = Challenge( + agent=agent, + skill_id=skill_id, + version=version, + nonce=secrets.token_hex(16), + issued_at=now, + expires_at=now + settings.proof_ttl_seconds, + ) + with _lock, _connect() as conn: + conn.execute( + "DELETE FROM proof_challenges WHERE expires_at < ?", (now - _PURGE_GRACE_SECONDS,) + ) + conn.execute( + "INSERT INTO proof_challenges " + "(nonce, agent, skill_id, version, issued_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)", + ( + challenge.nonce, agent, skill_id, version, + challenge.issued_at, challenge.expires_at, + ), + ) + return challenge + + +def _get(nonce: str) -> dict[str, Any] | None: + with _lock, _connect() as conn: + row = conn.execute("SELECT * FROM proof_challenges WHERE nonce = ?", (nonce,)).fetchone() + return dict(row) if row else None + + +def _decode_signature(raw: str) -> bytes: + value = raw.strip() + try: + # Accept both base64 alphabets; wallets differ. Padding is restored first. + padded = value + "=" * (-len(value) % 4) + decoded = base64.b64decode(padded.replace("-", "+").replace("_", "/"), validate=True) + except (binascii.Error, ValueError) as exc: + raise ProofInvalid("signature is not base64") from exc + if len(decoded) != 64: + raise ProofInvalid(f"signature must be 64 bytes (ed25519), got {len(decoded)}") + return decoded + + +def verify_and_consume( + agent: str, + skill_id: str, + version: str, + nonce: str, + signature: str, + *, + now: int | None = None, +) -> None: + """Accept the proof exactly once, or raise ProofInvalid naming why.""" + now = int(time.time()) if now is None else now + nonce = nonce.strip() + row = _get(nonce) + if row is None: + raise ProofInvalid("unknown nonce; request a new challenge") + if row["agent"] != agent: + raise ProofInvalid("this challenge was issued for a different agent") + if row["skill_id"] != skill_id or row["version"] != version: + raise ProofInvalid("this challenge was issued for a different skill or version") + if row["used_at"] is not None: + raise ProofInvalid("this challenge has already been used; request a new one") + if now > row["expires_at"]: + raise ProofInvalid("this challenge has expired; request a new one") + + sig = _decode_signature(signature) + message = build_message(agent, skill_id, version, nonce, row["expires_at"]) + try: + Keypair.from_public_key(agent).verify(sep53_digest(message), sig) + except BadSignatureError as exc: + raise ProofInvalid( + "signature does not verify against the agent's key " + "(expected SEP-53 over the challenge message)" + ) from exc + + # Conditional update: of two requests racing with the same valid proof, one wins. + with _lock, _connect() as conn: + consumed = conn.execute( + "UPDATE proof_challenges SET used_at = ? " + "WHERE nonce = ? AND used_at IS NULL AND expires_at >= ?", + (now, nonce, now), + ).rowcount + if consumed != 1: + raise ProofInvalid("this challenge has already been used; request a new one") diff --git a/api/src/sterish_api/routes/use.py b/api/src/sterish_api/routes/use.py index e17a0eb..6710349 100644 --- a/api/src/sterish_api/routes/use.py +++ b/api/src/sterish_api/routes/use.py @@ -8,8 +8,10 @@ 1. the version is SAFE on chain, else 403 — never offered for sale; 2. the artifact is on disk and hashes to the on-chain `content_hash`, else 404/500 — checked *before* the 402, so nothing undeliverable is ever priced; -3. the caller already holds a licence -> 200, no payment; -4. the caller has a settled payment still owed a licence -> finish the mint, 200; +3. the caller already holds a licence -> 200, no payment — **only with a proof that it + controls that address** (STE-48), else 401; +4. the caller has a settled payment still owed a licence -> finish the mint, 200 — + same proof required; 5. no payment attached -> 402 with x402 requirements; 6. payment attached -> verify (which names the payer) -> held or owed? serve without settling -> settle -> record the settlement -> mint -> 200. @@ -36,7 +38,7 @@ from fastapi import APIRouter, Request, Response from stellar_sdk.strkey import StrKey -from .. import chain, payments, x402 +from .. import chain, payments, proofs, x402 from ..config import settings from ..errors import ApiError @@ -92,6 +94,37 @@ def _agent_hint(request: Request) -> str | None: return value +def _require_ownership_proof( + request: Request, agent: str, skill_id: str, version: str, why: str +) -> None: + """The free paths serve bytes to an address. Make the caller prove it is that address. + + Anyone can read who holds a licence (it is on chain), so an address alone proves + nothing. Missing or wrong proof is 401 — never 402: this caller may well have paid, + and a 402 would invite them to pay again. + """ + nonce = request.headers.get(proofs.NONCE_HEADER) + signature = request.headers.get(proofs.SIGNATURE_HEADER) + challenge_url = str(request.url_for("use_challenge", skill_id=skill_id, version=version)) + details = { + "challenge_url": f"{challenge_url}?agent={agent}", + "signature_scheme": "SEP-53", + "headers": [AGENT_HEADER, proofs.NONCE_HEADER, proofs.SIGNATURE_HEADER], + } + if not nonce or not signature: + raise ApiError( + 401, "OWNERSHIP_PROOF_REQUIRED", + f"{agent} {why}; prove you control it: GET the challenge_url, sign its message " + f"(SEP-53) with that account's key, and repeat this request with " + f"{proofs.NONCE_HEADER} and {proofs.SIGNATURE_HEADER}", + details, + ) + try: + proofs.verify_and_consume(agent, skill_id, version, nonce, signature) + except proofs.ProofInvalid as exc: + raise ApiError(401, "INVALID_OWNERSHIP_PROOF", exc.reason, details) from exc + + def _skill_bytes(skill_id: str, version: str, expected_hash: str) -> bytes: """Read the pinned artifact and refuse to serve anything that is not it.""" if not settings.skills_dir: @@ -212,8 +245,9 @@ def _fulfil(owed_row: dict, skill_id: str, version: str) -> str | None: def _mint_pending(settle_tx: str, reason: str) -> ApiError: return ApiError( 502, "LICENSE_MINT_PENDING", - "your payment settled but the licence could not be minted yet; retry the same " - "request (with X-AGENT-ADDRESS) and it will be finished without charging again. " + "your payment settled but the licence could not be minted yet; retry with " + "X-AGENT-ADDRESS and an ownership proof (see the challenge endpoint) and it will be " + "finished without charging again. " f"Cause: {reason}", { "settlement_tx": settle_tx, @@ -235,6 +269,48 @@ def _serve_fulfilled(body: bytes, owed_row: dict, mint_tx: str | None) -> Respon return _serve(body, "minted" if mint_tx else "held", headers) +@router.get("/use/{skill_id}/{version}/challenge", name="use_challenge") +def use_challenge(skill_id: str, version: str, request: Request): + """Issue a single-use ownership challenge for the free licence-holder path (STE-48). + + Issued for any valid account and any version: whether the address holds a licence + is public on chain anyway, and answering differently would only add a round trip. + Nothing is served here; the proof is spent on the next `GET /use`. + """ + agent = _agent_hint(request) + if not agent: + raise ApiError( + 400, "MISSING_AGENT", + f"agent is required: ?agent=G... or {AGENT_HEADER}", + ) + challenge = proofs.issue(agent, skill_id, version) + from datetime import UTC, datetime + + body = { + "agent": challenge.agent, + "skill_id": challenge.skill_id, + "version": challenge.version, + "nonce": challenge.nonce, + "expires_at": challenge.expires_at, + "expires_at_iso": datetime.fromtimestamp(challenge.expires_at, UTC) + .isoformat() + .replace("+00:00", "Z"), + "message": challenge.message, + "signature_scheme": "SEP-53", + "sign": 'ed25519 over SHA-256("Stellar Signed Message:\\n" + message), base64', + "send_headers": { + AGENT_HEADER: challenge.agent, + proofs.NONCE_HEADER: challenge.nonce, + proofs.SIGNATURE_HEADER: "", + }, + } + return Response( + content=json.dumps(body).encode("utf-8"), + media_type="application/json", + headers={"Cache-Control": "no-store"}, + ) + + @router.get("/use/{skill_id}/{version}") def use_skill(skill_id: str, version: str, request: Request): record = chain.get_version(skill_id, version) @@ -258,6 +334,9 @@ def use_skill(skill_id: str, version: str, request: Request): if not payment_header: if agent: if _has_license(agent, skill_id, version): + _require_ownership_proof( + request, agent, skill_id, version, "holds a licence for this version" + ) # A mint that landed although its confirmation never reached us leaves # its settlement looking owed; close it so it is never fulfilled twice. stale = payments.owed(agent, skill_id, version) @@ -266,6 +345,9 @@ def use_skill(skill_id: str, version: str, request: Request): return _serve(body, "held") owed_row = payments.owed(agent, skill_id, version) if owed_row: + _require_ownership_proof( + request, agent, skill_id, version, "is owed a licence for this version" + ) with _purchase_lock(agent, skill_id, version): owed_row = payments.owed(agent, skill_id, version) or owed_row mint_tx = _fulfil(owed_row, skill_id, version) diff --git a/api/tests/test_use_x402.py b/api/tests/test_use_x402.py index 1de8c4d..3c12347 100644 --- a/api/tests/test_use_x402.py +++ b/api/tests/test_use_x402.py @@ -11,6 +11,7 @@ import time import pytest +from stellar_sdk import Keypair from sterish_api import chain, payments, x402 from sterish_api.config import settings @@ -32,13 +33,35 @@ DANGEROUS = dict(SAFE, verdict="DANGEROUS", is_verified=False) URL = f"/use/{SAFE['skill_id']}/1.0.0" -# Two real ed25519 account addresses: the buyer, and someone else entirely. -PAYER = "GBFXMHA77OLBYF3JJB43O6CKZ4QR35AAQALJK72MUIHTZNBVAQGTTZWY" -OTHER = "GD73M4F7RN74KBLFGJP4WKBMCBJWBOA4SFNOP5HG4NBCDQUQCC2ARSZU" +# Two real ed25519 accounts: the buyer, and someone else entirely. Both have keys, so +# the ownership proofs STE-48 requires can be signed for real rather than stubbed. +PAYER_KP = Keypair.from_raw_ed25519_seed(bytes([1]) * 32) +OTHER_KP = Keypair.from_raw_ed25519_seed(bytes([2]) * 32) +PAYER = PAYER_KP.public_key +OTHER = OTHER_KP.public_key SETTLE_TX = "5" * 64 MINT_TX = "6" * 64 +def _sep53_sign(keypair: Keypair, message: str) -> str: + """What a wallet's signMessage and `stellar message sign` produce (SEP-53).""" + import hashlib + + digest = hashlib.sha256(b"Stellar Signed Message:\n" + message.encode()).digest() + return base64.b64encode(keypair.sign(digest)).decode() + + +def _proof(client, signer: Keypair = None, agent: str = PAYER, url: str = URL) -> dict: + """Ask for a challenge as `agent`, sign it with `signer`, return the request headers.""" + signer = signer or PAYER_KP + challenge = client.get(f"{url}/challenge", params={"agent": agent}).json() + return { + "X-AGENT-ADDRESS": agent, + "X-STERISH-PROOF-NONCE": challenge["nonce"], + "X-STERISH-PROOF-SIGNATURE": _sep53_sign(signer, challenge["message"]), + } + + def _payment_header(payload: dict | None = None) -> str: return base64.b64encode(json.dumps(payload or {"payload": {}}).encode()).decode() @@ -257,7 +280,7 @@ def test_a_contract_address_is_not_an_agent(client, monkeypatch, artifact): def test_an_existing_licence_is_served_without_payment(client, monkeypatch, artifact): ledger = Ledger(monkeypatch) ledger.licences.add((PAYER, SAFE["skill_id"], "1.0.0")) - r = client.get(URL, headers={"X-AGENT-ADDRESS": PAYER}) + r = client.get(URL, headers=_proof(client)) assert r.status_code == 200 assert r.headers["X-STERISH-LICENSE"] == "held" assert json.loads(r.content) == {"manifest.json": '{"skill_id":"com.acme.pdf-suite"}\n'} @@ -477,7 +500,7 @@ def test_the_next_request_finishes_the_mint_without_charging( self._pay_with_failing_mint(client, ledger, OnChainError("rpc timeout")) ledger.mint_error = None - r = client.get(URL, headers={"X-AGENT-ADDRESS": PAYER}) + r = client.get(URL, headers=_proof(client)) assert r.status_code == 200 assert r.headers["X-STERISH-LICENSE"] == "minted" assert r.headers["X-STERISH-SETTLEMENT-TX"] == SETTLE_TX @@ -506,7 +529,7 @@ def test_a_mint_that_actually_landed_is_not_minted_twice(self, client, monkeypat ledger.licences.add((PAYER, SAFE["skill_id"], "1.0.0")) # it landed after all ledger.mint_error = AssertionError("must not mint again") - r = client.get(URL, headers={"X-AGENT-ADDRESS": PAYER}) + r = client.get(URL, headers=_proof(client)) assert r.status_code == 200 assert r.headers["X-STERISH-LICENSE"] == "held" assert payments.owed(PAYER, SAFE["skill_id"], "1.0.0") is None @@ -518,7 +541,7 @@ def test_already_minted_from_the_contract_closes_the_debt(self, client, monkeypa self._pay_with_failing_mint(client, ledger, OnChainError("did not finalise")) ledger.mint_error = ContractCallError(3, "mint_license", contract="tokens") - r = client.get(URL, headers={"X-AGENT-ADDRESS": PAYER}) + r = client.get(URL, headers=_proof(client)) assert r.status_code == 200 assert r.headers["X-STERISH-SETTLEMENT-TX"] == SETTLE_TX assert payments.owed(PAYER, SAFE["skill_id"], "1.0.0") is None @@ -575,3 +598,221 @@ def test_settlement_header_is_readable_by_a_browser(client, artifact): exposed = r.headers.get("access-control-expose-headers", "") assert "X-STERISH-SETTLEMENT-TX" in exposed assert "PAYMENT-REQUIRED" in exposed + + +# --- STE-48: a licence cannot be borrowed by naming its holder ------------------------ + + +class TestOwnershipProof: + """Licence holders are public on chain, so an address alone must never be enough.""" + + @pytest.fixture + def held(self, monkeypatch, artifact): + ledger = Ledger(monkeypatch) + ledger.licences.add((PAYER, SAFE["skill_id"], "1.0.0")) + return ledger + + def test_naming_a_holder_without_proof_is_401_not_the_artifact(self, client, held): + """The finding: anyone sending the holder's address received the bytes.""" + r = client.get(URL, headers={"X-AGENT-ADDRESS": PAYER}) + assert r.status_code == 401 + body = r.json() + assert body["error"] == "OWNERSHIP_PROOF_REQUIRED" + assert body["challenge_url"].endswith(f"{URL}/challenge?agent={PAYER}") + assert body["signature_scheme"] == "SEP-53" + assert "manifest.json" not in r.text + assert "PAYMENT-REQUIRED" not in r.headers # never 402: this caller may have paid + assert held.verifies == held.settles == 0 + + def test_the_query_parameter_form_is_refused_the_same_way(self, client, held): + r = client.get(URL, params={"agent": PAYER}) + assert r.status_code == 401 + assert r.json()["error"] == "OWNERSHIP_PROOF_REQUIRED" + + def test_a_nonce_without_a_signature_is_still_proof_required(self, client, held): + headers = _proof(client) + del headers["X-STERISH-PROOF-SIGNATURE"] + assert client.get(URL, headers=headers).json()["error"] == "OWNERSHIP_PROOF_REQUIRED" + + def test_a_valid_proof_serves_the_artifact(self, client, held): + r = client.get(URL, headers=_proof(client)) + assert r.status_code == 200 + assert r.headers["X-STERISH-LICENSE"] == "held" + assert held.settles == 0 + + def test_a_signature_from_another_key_is_refused(self, client, held): + """The attacker controls a key, just not the holder's.""" + r = client.get(URL, headers=_proof(client, signer=OTHER_KP, agent=PAYER)) + assert r.status_code == 401 + assert r.json()["error"] == "INVALID_OWNERSHIP_PROOF" + assert "does not verify" in r.json()["detail"] + assert "manifest.json" not in r.text + + def test_a_proof_cannot_be_replayed(self, client, held): + headers = _proof(client) + assert client.get(URL, headers=headers).status_code == 200 + again = client.get(URL, headers=headers) + assert again.status_code == 401 + assert again.json()["error"] == "INVALID_OWNERSHIP_PROOF" + assert "already been used" in again.json()["detail"] + + def test_an_expired_challenge_is_refused(self, client, held, monkeypatch): + from sterish_api import proofs + + headers = _proof(client) + real_time = time.time + later = real_time() + settings.proof_ttl_seconds + 5 + monkeypatch.setattr(proofs.time, "time", lambda: later) + r = client.get(URL, headers=headers) + assert r.status_code == 401 + assert "expired" in r.json()["detail"] + + def test_a_failed_signature_does_not_burn_the_holders_nonce(self, client, held): + headers = _proof(client) + forged = dict(headers, **{"X-STERISH-PROOF-SIGNATURE": _sep53_sign(OTHER_KP, "anything")}) + assert client.get(URL, headers=forged).status_code == 401 + assert client.get(URL, headers=headers).status_code == 200 + + def test_a_challenge_for_another_agent_cannot_be_reused(self, client, held): + """OTHER asks for its own challenge and signs it correctly, then claims PAYER.""" + own = _proof(client, signer=OTHER_KP, agent=OTHER) + stolen = dict(own, **{"X-AGENT-ADDRESS": PAYER}) + r = client.get(URL, headers=stolen) + assert r.status_code == 401 + assert "different agent" in r.json()["detail"] + + def test_a_challenge_for_another_version_cannot_be_reused(self, client, held): + headers = _proof(client, url=f"/use/{SAFE['skill_id']}/2.0.0") + r = client.get(URL, headers=headers) + assert r.status_code == 401 + assert "different skill or version" in r.json()["detail"] + + def test_the_signed_message_is_rebuilt_server_side(self, client, held): + """Signing some other text containing the same nonce proves nothing.""" + challenge = client.get(f"{URL}/challenge", params={"agent": PAYER}).json() + tampered = challenge["message"].replace("version: 1.0.0", "version: 9.9.9") + headers = { + "X-AGENT-ADDRESS": PAYER, + "X-STERISH-PROOF-NONCE": challenge["nonce"], + "X-STERISH-PROOF-SIGNATURE": _sep53_sign(PAYER_KP, tampered), + } + assert client.get(URL, headers=headers).status_code == 401 + + def test_a_raw_ed25519_signature_without_the_sep53_prefix_is_refused(self, client, held): + """One format, locked: a signature over the bare message is not SEP-53.""" + challenge = client.get(f"{URL}/challenge", params={"agent": PAYER}).json() + raw = base64.b64encode(PAYER_KP.sign(challenge["message"].encode())).decode() + headers = { + "X-AGENT-ADDRESS": PAYER, + "X-STERISH-PROOF-NONCE": challenge["nonce"], + "X-STERISH-PROOF-SIGNATURE": raw, + } + assert client.get(URL, headers=headers).status_code == 401 + + @pytest.mark.parametrize("bad", ["not base64!!", base64.b64encode(b"short").decode()]) + def test_a_malformed_signature_is_401_not_500(self, client, held, bad): + headers = dict(_proof(client), **{"X-STERISH-PROOF-SIGNATURE": bad}) + r = client.get(URL, headers=headers) + assert r.status_code == 401 + assert r.json()["error"] == "INVALID_OWNERSHIP_PROOF" + + def test_an_unknown_nonce_is_refused(self, client, held): + headers = dict(_proof(client), **{"X-STERISH-PROOF-NONCE": "0" * 32}) + assert "unknown nonce" in client.get(URL, headers=headers).json()["detail"] + + def test_an_owed_settlement_also_needs_proof(self, client, monkeypatch, artifact): + """The owed path mints and serves bytes too; naming the payer must not do it.""" + ledger = Ledger(monkeypatch) + payments.record_settlement(PAYER, SAFE["skill_id"], "1.0.0", SETTLE_TX, "1000000") + r = client.get(URL, headers={"X-AGENT-ADDRESS": PAYER}) + assert r.status_code == 401 + assert ledger.mints == [] + assert payments.owed(PAYER, SAFE["skill_id"], "1.0.0") is not None + + def test_a_non_holder_still_gets_402_with_or_without_proof(self, client, monkeypatch, artifact): + """Proof only matters when there is something to prove; a buyer is asked to pay.""" + Ledger(monkeypatch) + assert client.get(URL, headers={"X-AGENT-ADDRESS": PAYER}).status_code == 402 + assert client.get(URL, headers=_proof(client)).status_code == 402 + + def test_the_paid_path_needs_no_proof(self, client, monkeypatch, artifact): + """The x402 payment is signed by the payer, and the payer comes from /verify.""" + ledger = Ledger(monkeypatch) + r = client.get(URL, headers={"X-PAYMENT": _payment_header()}) + assert r.status_code == 200 + assert r.headers["X-STERISH-LICENSE"] == "minted" + assert ledger.settles == 1 + + +class TestChallengeEndpoint: + def test_the_challenge_names_everything_it_binds(self, client): + body = client.get(f"{URL}/challenge", params={"agent": PAYER}).json() + assert body["agent"] == PAYER and body["skill_id"] == SAFE["skill_id"] + assert body["version"] == "1.0.0" + assert len(body["nonce"]) == 32 + assert body["signature_scheme"] == "SEP-53" + lines = body["message"].split("\n") + assert lines == [ + "Sterish licence ownership proof", + f"agent: {PAYER}", + f"skill: {SAFE['skill_id']}", + "version: 1.0.0", + f"nonce: {body['nonce']}", + f"expires: {body['expires_at']}", + "network: Test SDF Network ; September 2015", + ] + assert 0 < body["expires_at"] - time.time() <= settings.proof_ttl_seconds + + def test_every_challenge_is_a_fresh_nonce(self, client): + a = client.get(f"{URL}/challenge", params={"agent": PAYER}).json()["nonce"] + b = client.get(f"{URL}/challenge", params={"agent": PAYER}).json()["nonce"] + assert a != b + + def test_the_challenge_is_never_cached(self, client): + r = client.get(f"{URL}/challenge", params={"agent": PAYER}) + assert r.headers["Cache-Control"] == "no-store" + + def test_the_header_form_works(self, client): + r = client.get(f"{URL}/challenge", headers={"X-AGENT-ADDRESS": PAYER}) + assert r.status_code == 200 + + @pytest.mark.parametrize( + "agent, code", + [ + (None, "MISSING_AGENT"), + ("not-an-address", "INVALID_AGENT"), + ("CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T", "INVALID_AGENT"), + ( + "MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ", + "INVALID_AGENT", + ), + ], + ) + def test_the_agent_is_validated(self, client, agent, code): + params = {"agent": agent} if agent else {} + r = client.get(f"{URL}/challenge", params=params) + assert r.status_code == 400 + assert r.json()["error"] == code + + def test_a_proof_signed_with_the_stellar_cli_format_verifies(self): + """Pin the digest to SEP-53 independently of our own signing helper.""" + import hashlib + + from sterish_api import proofs + + message = "hello" + assert proofs.sep53_digest(message) == hashlib.sha256( + b"Stellar Signed Message:\nhello" + ).digest() + + +def test_a_signature_made_by_the_stellar_cli_verifies(): + """Known answer, captured from `stellar message sign "hello" --sign-with-key ` + (stellar-cli, 2026-09-17). The same bytes came out of demo/x402-buyer/prove.js. If this + ever fails, the server and every real signer disagree about SEP-53.""" + from sterish_api import proofs + + signature = base64.b64decode( + "u5X4XThfRD8os95F82YDnzd/ow2uGibbTlisjIHkxaoEfgI7K4QN/oz9K5Vm9dut9zcT8kUJydc2VqonO0cWAQ==" + ) + PAYER_KP.verify(proofs.sep53_digest("hello"), signature) diff --git a/demo/x402-buyer/buy.js b/demo/x402-buyer/buy.js index 2c82f46..604f2c7 100644 --- a/demo/x402-buyer/buy.js +++ b/demo/x402-buyer/buy.js @@ -17,6 +17,7 @@ import { x402Client, x402HTTPClient } from "@x402/fetch"; import { createEd25519Signer } from "@x402/stellar"; import { ExactStellarScheme } from "@x402/stellar/exact/client"; +import { proofHeaders } from "./prove.js"; const API = process.env.STERISH_API ?? "http://127.0.0.1:8000"; const NETWORK = "stellar:testnet"; @@ -76,9 +77,19 @@ if (licence !== EXPECT) { process.exit(1); } -// 3. The licence is on chain now, so the next call is free. -const again = await fetch(url, { headers: agentHeaders }); -console.log(`\n3. second request (free) -> ${again.status}`); +// 3. The licence is on chain now, so the next call is free — for the holder. Naming the +// address is not enough (STE-48): first show the API refuses it, then prove control. +const bare = await fetch(url, { headers: agentHeaders }); +console.log(`\n3. free request, address only -> ${bare.status}`); +if (bare.status !== 401) { + console.log(" expected 401 OWNERSHIP_PROOF_REQUIRED; body:", (await bare.text()).slice(0, 300)); + process.exit(1); +} +const proven = await proofHeaders({ + api: API, skillId: SKILL, version: VERSION, secret: process.env.AGENT_SECRET, +}); +const again = await fetch(url, { headers: proven }); +console.log(` free request, SEP-53 proof -> ${again.status}`); console.log(` licence ${again.headers.get("X-STERISH-LICENSE")}`); if (again.status !== 200 || again.headers.get("X-STERISH-LICENSE") !== "held") { console.log(" expected a held licence and no payment"); diff --git a/demo/x402-buyer/prove.js b/demo/x402-buyer/prove.js new file mode 100644 index 0000000..e809dd0 --- /dev/null +++ b/demo/x402-buyer/prove.js @@ -0,0 +1,63 @@ +// Prove to Sterish that this agent controls the address holding a licence (STE-48). +// +// A licence holder is served for free, but holders are public on chain, so the API +// asks for a signature over a single-use challenge before it hands the bytes over: +// +// 1. GET /use///challenge?agent=G... -> { nonce, message, ... } +// 2. sign `message` with SEP-53: ed25519 over SHA-256("Stellar Signed Message:\n" + message) +// (the same bytes `stellar message sign` and a wallet's SEP-43 signMessage sign) +// 3. repeat GET /use with X-AGENT-ADDRESS, X-STERISH-PROOF-NONCE, X-STERISH-PROOF-SIGNATURE +// +// As a module: `proofHeaders({ api, skillId, version, secret })` returns the headers. +// As a script, it fetches a skill you already hold: +// +// STERISH_API=https://api-sterish.jameshub.fun AGENT_SECRET=S... \ +// SKILL_ID=org.stellar.skills.dapp.react SKILL_VERSION=2026.8.31 node prove.js +// +// The secret is only ever read from the environment and never printed. +import { createHash } from "node:crypto"; +import { pathToFileURL } from "node:url"; +import { Keypair } from "@stellar/stellar-sdk"; + +const SEP53_PREFIX = "Stellar Signed Message:\n"; + +export function sep53Sign(keypair, message) { + const digest = createHash("sha256").update(SEP53_PREFIX + message, "utf8").digest(); + return keypair.sign(digest).toString("base64"); +} + +export async function proofHeaders({ api, skillId, version, secret }) { + const keypair = Keypair.fromSecret(secret); + const agent = keypair.publicKey(); + const url = `${api}/use/${skillId}/${version}/challenge?agent=${agent}`; + const response = await fetch(url); + if (response.status !== 200) { + throw new Error(`challenge request failed: ${response.status} ${await response.text()}`); + } + const challenge = await response.json(); + return { + "X-AGENT-ADDRESS": agent, + "X-STERISH-PROOF-NONCE": challenge.nonce, + "X-STERISH-PROOF-SIGNATURE": sep53Sign(keypair, challenge.message), + }; +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + const api = process.env.STERISH_API ?? "http://127.0.0.1:8000"; + const skillId = process.env.SKILL_ID; + const version = process.env.SKILL_VERSION ?? "1.0.0"; + if (!process.env.AGENT_SECRET) throw new Error("AGENT_SECRET is required"); + if (!skillId) throw new Error("SKILL_ID is required"); + + const headers = await proofHeaders({ api, skillId, version, secret: process.env.AGENT_SECRET }); + const response = await fetch(`${api}/use/${skillId}/${version}`, { headers }); + const body = await response.text(); + console.log(`agent ${headers["X-AGENT-ADDRESS"]}`); + console.log(`status ${response.status}`); + console.log(`licence ${response.headers.get("X-STERISH-LICENSE")}`); + if (response.status !== 200) { + console.log(body); + process.exit(1); + } + process.stdout.write(`${body}\n`); +} diff --git a/docs/api-spec.md b/docs/api-spec.md index 73c6ccf..0b185fc 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -374,8 +374,8 @@ it twice.** Checked in this order — each step runs only if every step above it | 1 | version is not `SAFE` on chain | `403 NOT_VERIFIED`, no challenge | | 2 | no artifact on disk for this version | `404 ARTIFACT_NOT_FOUND`, no challenge | | 2 | artifact bytes do not hash to the on-chain `content_hash` | `500 ARTIFACT_HASH_MISMATCH`, no challenge | -| 3 | `X-AGENT-ADDRESS` holds a licence for this exact version | `200` + artifact, `X-STERISH-LICENSE: held` | -| 4 | `X-AGENT-ADDRESS` has a settled payment still owed a licence | mint → `200`, `X-STERISH-LICENSE: minted` + `X-STERISH-SETTLEMENT-TX` | +| 3 | `X-AGENT-ADDRESS` holds a licence for this exact version | **with a valid ownership proof** (STE-48): `200` + artifact, `X-STERISH-LICENSE: held`; without one `401 OWNERSHIP_PROOF_REQUIRED`, with a bad one `401 INVALID_OWNERSHIP_PROOF` | +| 4 | `X-AGENT-ADDRESS` has a settled payment still owed a licence | same proof required; then mint → `200`, `X-STERISH-LICENSE: minted` + `X-STERISH-SETTLEMENT-TX` | | 5 | no `X-PAYMENT` | `402` + `PAYMENT-REQUIRED` header, empty body | | 6 | `X-PAYMENT` attached | verify → (payer holds or is owed? serve, **no settle**) → settle → record → mint → `200`, `X-STERISH-LICENSE: minted` | @@ -393,6 +393,52 @@ defence in depth and a clearer error than a contract revert. a client that wants the "already licensed" shortcut sends `X-AGENT-ADDRESS: G…` (or `?agent=`). A malformed value is `400 INVALID_AGENT`. +**Proving the caller is that address (STE-48).** Who holds a licence is public: `license_minted` +events, `get_token`, and the dashboard's `/licences/[address]` page. Until STE-48 the address alone +unlocked steps 3 and 4, so anyone could name a holder and receive the artifact without paying — a +soulbound licence that anyone could borrow. The free paths now require a signature from the +address's own key over a single-use challenge: + +1. `GET /use/{skill_id}/{version}/challenge?agent=G…` (or `X-AGENT-ADDRESS`) → + + ```json + {"agent": "G…", "skill_id": "…", "version": "…", + "nonce": "32 hex chars", "expires_at": 1789600000, "expires_at_iso": "…Z", + "message": "Sterish licence ownership proof\nagent: G…\nskill: …\nversion: …\nnonce: …\nexpires: 1789600000\nnetwork: Test SDF Network ; September 2015", + "signature_scheme": "SEP-53", "send_headers": {…}} + ``` + + `400 MISSING_AGENT` / `400 INVALID_AGENT` (a `C…` or `M…` address is refused). `Cache-Control: + no-store`. Issued for any valid account and version: whether an address holds a licence is public + anyway, so answering differently would reveal nothing and cost a round trip. +2. Sign `message` exactly as returned with **SEP-53**: ed25519 over + `SHA-256("Stellar Signed Message:\n" + message)`, base64. That is what a wallet's SEP-43 + `signMessage` returns and what `stellar message sign "" --sign-with-key …` prints. A + signature over the bare message, without the prefix, is refused — one format, locked. +3. Repeat `GET /use/{skill_id}/{version}` with `X-AGENT-ADDRESS`, `X-STERISH-PROOF-NONCE` and + `X-STERISH-PROOF-SIGNATURE`. + +The server rebuilds the message from its own record of the nonce; nothing the client sends is +trusted as the signed text. A nonce is bound to one agent, one skill and one version, lives +`STERISH_PROOF_TTL_SECONDS` (default 300, clamped to 30–900 — long enough to approve a wallet prompt), +and is consumed by the first request that proves with it. A **failed** signature does not consume it, +so nobody can burn another caller's challenge. Nonces are stored beside the payments ledger, so a +restart does not reopen a used one. + +| Proof | Response | +|---|---| +| none, or nonce without signature | `401 OWNERSHIP_PROOF_REQUIRED` + `challenge_url`, `signature_scheme`, `headers` | +| unknown nonce, other agent's / other version's nonce, used, expired, not base64 / not 64 bytes, signature does not verify | `401 INVALID_OWNERSHIP_PROOF`, `detail` names which | +| valid | step 3 or 4 proceeds | + +Always `401`, never `402`: this caller may already have paid, and a `402` would invite a second +payment. A caller that proves its address but holds no licence gets the ordinary `402`. **The paid +path (step 6) needs no separate proof**: the x402 payment is signed by the payer, and the payer is +taken from the facilitator's `/verify`. + +Reference clients: `demo/x402-buyer/prove.js` (terminal agent; `AGENT_SECRET` from the environment, +never printed) and `api/scripts/e2e_paid_path.py`. + **Identifying the payer.** After payment the payer is **the account the facilitator's `/verify` names** — the `from` of the signed SAC `transfer` — and nothing else. `X-AGENT-ADDRESS` is ignored for this. Before STE-42 the payer was read from the payment payload and then the header; the @@ -405,7 +451,7 @@ sent someone else's address had the licence minted to that address. A verify res first landed. The settlement is recorded first (payer, skill, version, settlement tx) in a ledger that is **not** the index cache (`STERISH_PAYMENTS_DB_PATH`). A failed mint answers `502 LICENSE_MINT_PENDING` carrying `settlement_tx` and `settlement_tx_url`. The payer's next -request — with `X-AGENT-ADDRESS`, or with a fresh payment — finishes the mint **without settling +request — with `X-AGENT-ADDRESS` plus an ownership proof, or with a fresh payment — finishes the mint **without settling again**. Before minting, the licence is read from chain: a mint whose confirmation timed out but landed is closed out rather than minted twice (the contract would refuse it with `AlreadyMinted` anyway, and that refusal is also treated as fulfilled). @@ -449,7 +495,13 @@ listed in CORS `expose_headers`, so a browser client can read them. **Errors:** `403 NOT_VERIFIED`, `404 ARTIFACT_NOT_FOUND`, `500 ARTIFACT_HASH_MISMATCH`, `400 INVALID_AGENT`, `400 INVALID_PAYMENT`, `402 PAYMENT_REJECTED` (carries the facilitator's own reason), `503 FACILITATOR_UNAVAILABLE`, `502 FACILITATOR_BAD_RESPONSE`, `502 LICENSE_READ_FAILED`, -`502 LICENSE_MINT_PENDING`. +`502 LICENSE_MINT_PENDING`, `401 OWNERSHIP_PROOF_REQUIRED`, `401 INVALID_OWNERSHIP_PROOF`; +on the challenge endpoint `400 MISSING_AGENT`, `400 INVALID_AGENT`. + +**Known limit (STE-48).** A signed x402 payment header is itself accepted as proof of the payer +when that payer already holds the licence (it is served `held` without settling). The header is a +bearer credential until its auth entry expires (`maxTimeoutSeconds`, 300 s), so a client must not +leak it — the same exposure any signed payment already has. **Known limit.** If the version is re-audited away from `SAFE` between settlement and mint, the mint is refused (`NotSafeVerdict`) and the version now answers `403`. The settlement stays recorded as diff --git a/docs/audit-evidence.md b/docs/audit-evidence.md index a54d4f6..d6b4c1a 100644 --- a/docs/audit-evidence.md +++ b/docs/audit-evidence.md @@ -465,6 +465,39 @@ The 47 `com.sterish.it-*` / `e2e-*` / `canon-*` test entries were **not** migrat skills and their 26 versions were, in the old registry's registration order, so `query_all_skills` pages identically. +## Licences could be borrowed: the soulbound claim the API did not enforce (STE-48) + +**Recorded 17 September 2026, before the fix is live, on purpose.** + +A licence is a soulbound token: minted to one account, with no transfer entrypoint. The *contract* +holds that promise. The *API* did not. Until STE-48, `GET /use/{skill_id}/{version}` served the +artifact for free to any request whose `X-AGENT-ADDRESS` (or `?agent=`) named a licence holder, +without asking for any proof that the caller controls that address. Holders are public on chain +(`license_minted` events, `get_token`, `owner_of`, and the dashboard's `/licences/[address]` +page), so **every licence sold so far could be used by anyone who read the ledger.** No funds could +be taken, but the word *soulbound* was false in practice: a licence could be borrowed at will. + +Found by Ancung while testing a terminal install on 16 September; checked from the code, not by +using anyone else's licence. + +**The fix** (merged 17 September, [STE-48](https://linear.app/sterish/issue/STE-48)): the free paths +require a SEP-53 signature from the address's own key over a single-use challenge the API issues +(`api-spec.md` §3.7). Missing or wrong proof is `401`, never `402`. Tested on testnet: the holder with +a proof is served; the address alone, a proof signed by another key, a replayed proof, a stranger's +valid proof presented for the holder, a proof for another version, and an expired proof are all +refused ([`evidence/ste-48-e2e-ownership-proof-local-2026-09-17.json`](evidence/ste-48-e2e-ownership-proof-local-2026-09-17.json)). + +**Deploy status.** Merged but **not yet deployed**: until the dashboard can sign a challenge, its +"Request again" would answer `401` instead of `200 held`. The agreed plan is to deploy as soon as +that signing UI lands, and **no later than 19 September 2026 either way** — a visible degradation +on the dashboard is better than an invisible false claim. Until the deploy is recorded in +`docs/deployments.md`, production still has the gap described above. Any redeploy of the API from +`main` also ships the fix. + +**Residual limit, stated rather than implied away.** A signed x402 payment header is still accepted +as proof of the payer when that payer already holds the licence. It is a bearer credential until +its auth entry expires (`maxTimeoutSeconds`, 300 s) — proof of payment, not proof of possession. + ## Limits worth stating * **Stage 2 did not run for the 25 entries above, and that is correct.** The seed run passed diff --git a/docs/evidence/ste-48-e2e-ownership-proof-local-2026-09-17.json b/docs/evidence/ste-48-e2e-ownership-proof-local-2026-09-17.json new file mode 100644 index 0000000..d261e09 --- /dev/null +++ b/docs/evidence/ste-48-e2e-ownership-proof-local-2026-09-17.json @@ -0,0 +1,37 @@ +{ + "api": "http://127.0.0.1:8793", + "started_at": 1789580096, + "skill": "org.stellar.skills.cross-chain.cctp", + "version": "2026.8.31", + "for_sale": [ + "org.stellar.skills.agentic-payments.mpp@2026.8.31", + "org.stellar.skills.agentic-payments.x402@2026.8.31", + "org.stellar.skills.cross-chain.axelar@2026.8.31", + "org.stellar.skills.dapp.data-fetching@2026.8.31", + "org.stellar.skills.dapp.react@2026.8.31", + "org.stellar.skills.dapp.smart-accounts@2026.8.31", + "org.stellar.skills.data.horizon@2026.8.31", + "org.stellar.skills.smart-contracts.development@2026.8.31", + "org.stellar.skills.smart-contracts.security@2026.8.31", + "org.stellar.skills.smart-contracts.testing@2026.8.31", + "org.stellar.skills.standards.ecosystem@2026.8.31", + "org.stellar.skills.standards.resources@2026.8.31", + "com.fixtures.safe.premium-pdf-suite@3.1.0", + "com.fixtures.safe.price-checker@0.9.0", + "com.fixtures.safe.weather-lookup@1.2.0", + "org.stellar.skills.cross-chain.cctp@2026.8.31", + "com.fixtures.demo.changelog-writer@1.0.0" + ], + "not_offered": [], + "agent": "GDH5RSHSA6QHHJEFP5XNFMKCRGOEAFCJCH2ZETTTSECFMYD7TJGUMJ2M", + "funding_tx": "4b544844c6d7ea7d7e9af7868a4e766e7ae815b23381d32f135647b22ea1bed6", + "price_usdc": "0.1", + "pay_to": "GD73M4F7RN74KBLFGJP4WKBMCBJWBOA4SFNOP5HG4NBCDQUQCC2ARSZU", + "settle_tx": "67ed9bdcf7485bf77c14bbee4d7344207dc3f83c8cf0ffd277e6b97f47459cb2", + "mint_tx": "e9ea2e196fe726cf7852214a18be9e05f8b6d48aebf9711d0afa348b7eb2dc10", + "content_hash": "f6fcdb2907ded30e75bcd61ac13263f41ad45f9921923784f77305734e69cf2b", + "stranger": "GDCJVHA4WNIQHBAQSUF5Q3JZQMCD7T7QBICGKL5K7VEMWAEYIGOL37MM", + "ownership_proof": "held with proof 200; address-only, forged, replayed, borrowed, wrong-version, expired all 401", + "finished_at": 1789580194, + "result": "pass" +} diff --git a/docs/rehearsal/run_rehearsal.py b/docs/rehearsal/run_rehearsal.py index e739ab7..6023f1e 100644 --- a/docs/rehearsal/run_rehearsal.py +++ b/docs/rehearsal/run_rehearsal.py @@ -599,10 +599,21 @@ def s5_second_call(self, n: int): before = usdc_balance(self.cfg, agent.public_key) out = x402_call(self.env, "held", agent.secret, skill_id, version) (self.run_dir / "x402-step5.json").write_text(self.ev.scrub(json.dumps(out, indent=2)) + "\n") - held = (out.get("requests") or [{}])[0] + by_label = {r.get("label"): r for r in out.get("requests") or []} + # STE-48: naming the holder's address is not proof of being the holder. The bare + # request must be refused (401, never 402), and the proven one served. + bare = by_label.get("held_address_only", {}) + bare_ok = bare.get("status") == 401 and not bare.get("payment_required") + self.ev.log(n, "GET /use with X-AGENT-ADDRESS only (no ownership proof)", + "ok" if bare_ok else "fail", url=out.get("url"), + detail=f"HTTP {bare.get('status')}, PAYMENT-REQUIRED={bare.get('payment_required')}, " + f"body: {str(bare.get('body_excerpt'))[:200]}") + held = by_label.get("held", {}) after = usdc_balance(self.cfg, agent.public_key) - good = held.get("status") == 200 and held.get("license") == "held" and after == before - self.ev.log(n, "GET /use with X-AGENT-ADDRESS only", "ok" if good else "fail", url=out.get("url"), + good = (bare_ok and held.get("status") == 200 and held.get("license") == "held" + and after == before) + self.ev.log(n, "GET /use with X-AGENT-ADDRESS + SEP-53 ownership proof", "ok" if good else "fail", + url=out.get("url"), detail=f"HTTP {held.get('status')}, X-STERISH-LICENSE={held.get('license')}, " f"PAYMENT-REQUIRED={held.get('payment_required')}, agent balance unchanged=" f"{after == before}, body: {str(held.get('body_excerpt'))[:200]}") diff --git a/docs/rehearsal/x402_pay.mjs b/docs/rehearsal/x402_pay.mjs index acf8859..353f2f4 100644 --- a/docs/rehearsal/x402_pay.mjs +++ b/docs/rehearsal/x402_pay.mjs @@ -12,10 +12,14 @@ // // STERISH_API, AGENT_SECRET, SKILL_ID, SKILL_VERSION, STELLAR_RPC_URL // MODE = "buy" -> unpaid request, then pay and retry (steps 4) -// MODE = "held" -> one request carrying only X-AGENT-ADDRESS (step 5) +// MODE = "held" -> the free licence-holder request (step 5). Since STE-48 an address +// alone is refused (401), so this records that refusal and then the +// same request with a SEP-53 ownership proof. import { x402Client, x402HTTPClient } from "@x402/fetch"; import { createEd25519Signer } from "@x402/stellar"; import { ExactStellarScheme } from "@x402/stellar/exact/client"; +import { createHash } from "node:crypto"; +import { Keypair } from "@stellar/stellar-sdk"; const API = process.env.STERISH_API; const RPC = process.env.STELLAR_RPC_URL ?? "https://soroban-testnet.stellar.org"; @@ -56,7 +60,20 @@ async function record(label, response) { try { if (MODE === "held") { - await record("held", await fetch(url, { headers: agentHeaders })); + await record("held_address_only", await fetch(url, { headers: agentHeaders })); + // Inlined rather than imported from demo/x402-buyer/prove.js: this file is piped to + // node on stdin, where a relative import has no file to resolve against. + const keypair = Keypair.fromSecret(process.env.AGENT_SECRET); + const challenge = await (await fetch(`${url}/challenge?agent=${signer.address}`)).json(); + const digest = createHash("sha256") + .update("Stellar Signed Message:\n" + challenge.message, "utf8").digest(); + await record("held", await fetch(url, { + headers: { + ...agentHeaders, + "X-STERISH-PROOF-NONCE": challenge.nonce, + "X-STERISH-PROOF-SIGNATURE": keypair.sign(digest).toString("base64"), + }, + })); } else { const first = await fetch(url, { headers: agentHeaders }); const firstHeaders = first.headers;