Skip to content

feat(mcp): reference remote spending authority over HTTP (stacked on #514) - #525

Closed
eddyflores100-lang wants to merge 9 commits into
solana-foundation:mainfrom
eddyflores100-lang:external-authority-remote-http
Closed

eddyflores100-lang wants to merge 9 commits into
solana-foundation:mainfrom
eddyflores100-lang:external-authority-remote-http

Conversation

@eddyflores100-lang

Copy link
Copy Markdown

Summary

Stacked on #514 — this adds the production-shaped reference implementation of SpendingAuthority that #514's trait leaves to hosts, following the Universal Trust Adapter (UTA) pattern discussed in #505. It is deliberately minimal: one new module, one line in lib.rs, one integration test file, and no new dependencies (reqwest/tokio/serde_json are already in the mcp crate).

While #514 ships the trait, the binding timeout and the replay-fenced call path (plus an inline Deny test stub), a host adopting the hook still has to write its own provider. This PR provides that provider so hosts can adopt external trust verification with ~10 lines of wiring:

let authority = Arc::new(RemoteHttpAuthority::new("http://127.0.0.1:8642/v1/authority/authorize")?);
let binding = AuthorityBinding::new("trusted-agent-42", authority);

Contract (fail-closed by construction)

Single round trip: POST {endpoint} with serde_json::to_vec(&SpendRequest) (content-type: application/json), then:

Verdict over 2xx Result
{"decision":"allow","unavailable":false} Ok(Allow)
{"decision":"deny","unavailable":false} Ok(Deny)
{"unavailable":true, ...} (any decision) Err(AuthorityUnavailable)
non-2xx / malformed / unknown verdict / transport error / timeout Err(AuthorityUnavailable)

The only path to Allow is an unambiguous, available allow verdict. The unavailable flag takes precedence over decision, mirroring the tested Node bridge semantics (universal-trust-adapter/pay-mcp-bridge/src/spend514.mjs, 9 tests) so a provider failure is never silently reinterpreted as a policy denial — and never as an implicit allow.

Security posture

  • endpoint is trusted host configuration, never a tool argument.
  • No credentials are attached to the consultation; redirects are not followed (Policy::none()), so the frozen request/offer snapshot cannot leak to a second origin mid-flight.
  • Verdict responses stay opaque to the agent (Allow/Deny/UNAVAILABLE via the existing AuthorityAttempt mapping). Hosts wanting receipts (verdict ids, bands, Ed25519 attestations) can wrap this authority and capture them into their own audit sink.
  • The optional inner request_timeout can only narrow the AuthorityBinding deadline (5s default, 60s max); it can never extend it.

Tests

tests/remote_authority.rs — 9 loopback tests over real HTTP on 127.0.0.1:0, no new dev-dependencies:

  1. allow verdict → Allow, and the frozen facts (operation/attempt/caller ids, amount, asset, networks, recipient, immutable request) arrive byte-faithful
  2. deny verdict → Deny
  3. unavailable:true wins over any decision → AuthorityUnavailable
  4. HTTP 500 → AuthorityUnavailable (fail-closed)
  5. malformed verdict body → AuthorityUnavailable
  6. unknown/missing decision → AuthorityUnavailable
  7. unreachable endpoint → AuthorityUnavailable
  8. 302 redirect is not followed (and the facts are not replayed elsewhere)
  9. inner request timeout → AuthorityUnavailable

Notes for reviewers

Closes nothing; complements #514. Related: #505.


Verification: cargo check -p pay-mcp --tests clean (0 warnings) and cargo test -p pay-mcp --test remote_authority → 9 passed, 0 failed (cargo 1.99.1, stable) on this exact commit.

Niri7981 and others added 5 commits October 18, 2026 13:50
Consult a trusted caller-scoped provider after SDK quote selection and YAML permissions, before the existing wallet signing path. Fail closed on deny, provider error, timeout, unsupported modes and prefilled credentials.

Preserve default behavior and add a bounded connection-local operation replay guard. This is a policy hook, not credential custody, durable recovery or final-egress Pause control.
Exercise real MCP initialization and tools/call with loopback merchants and offline fixture signing. Cover quote facts, allow/deny, failures, timeouts, replay conflicts, concurrent claims, independent YAML checks and disabled-mode compatibility.

Preserve the existing canonical Mainnet CAIP-2/YAML rejection explicitly; do not bypass permissions or fold its correction into this feature.
Describe trusted context activation, the public policy contract and conservative connection-local replay handling. Document existing YAML compatibility limits and the separate requirements for durable recovery and controlled final egress.
Implements SpendingAuthority by consulting a trusted external trust
service (UTA pattern, solana-foundation#505): POSTs the frozen SpendRequest JSON and maps
the verdict fail-closed. Complements solana-foundation#514 with the production-shaped
external provider the trait leaves to hosts.

- 2xx + {"decision":"allow","unavailable":false} -> Allow
- 2xx + {"decision":"deny", "unavailable":false} -> Deny
- {"unavailable":true} / non-2xx / malformed / unknown verdict /
  transport error / timeout -> AuthorityUnavailable (fail-closed)
- redirects are not followed; no credentials are attached
- optional inner request timeout can only narrow the binding deadline
- 9 loopback tests; no new dependencies
@vercel

vercel Bot commented Oct 21, 2026

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the Solana Foundation Team on Vercel.

A member of the Team first needs to authorize it.

@greptile-apps

greptile-apps Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Critical impact] No outstanding findings block merging. The changes since the previous review only explain the existing verdict-size limit and do not change runtime behavior.

Summary

Adds RemoteHttpAuthority, an HTTP provider for the optional spending check.

  • Pay MCP can check a host-provided spending policy before signing a payment.
  • A host can ask a remote HTTP policy service to approve each spend.

Reviews (5) · Last reviewed commit: "docs(mcp): explain why the verdict cap i..." · Reviewed by Greptile

Comment thread rust/crates/mcp/src/authority_remote.rs Outdated
Comment on lines +106 to +109
if verdict
.get("unavailable")
.and_then(Value::as_bool)
.unwrap_or(false)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Malformed verdicts approve spending

A response such as {"decision":"allow","unavailable":"true"} passes the external spending check because a present, non-boolean unavailable value becomes false. The same happens with null, numbers, objects, and arrays. Real HTTP and MCP payment tests confirmed that these malformed verdicts reach wallet approval and a signed merchant retry instead of returning AuthorityUnavailable. Wallet approval remains a separate gate.

Reject present unavailable values that are not booleans, and add regression tests for these cases. This fail-open path must be fixed before merging.

How this was verified: Malformed availability flags returned Allow over real HTTP and led to payment-signature-bearing merchant retries through the MCP spending check.

Artifacts

Runner for the focused authority response validation

  • The executed Python runner creates a uniquely named Rust test, runs it using existing offline Cargo caches, and captures both response phases without modifying product code.

Executed Rust test for malformed authority availability flags

  • The exact executed Rust source exercises real loopback authority requests and MCP payment calls, demonstrating that malformed flags reach signed retries.

HTTP and MCP results with valid availability flags

  • Captured the valid boolean and absent-field controls at HEAD, showing that true blocks spending while false and absence allow it.

HTTP and MCP results with malformed availability flags

  • Captured five malformed response types at the same HEAD, showing that each incorrectly authorizes a signed merchant retry.

Product code and shared test integrity check

  • Ran git diff against HEAD for product source, shared tests, and dependency files after cleanup, confirming no tracked changes.

View artifacts

TREX Ran code and verified through TREX

Comment thread rust/crates/mcp/src/authority_remote.rs Outdated
if !response.status().is_success() {
return Err(AuthorityUnavailable);
}
let bytes = response.bytes().await.map_err(|_| AuthorityUnavailable)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Verdicts have no size limit

response.bytes() buffers the entire successful response before parsing it, without a byte limit. A bounded test with a 32 MiB chunked response increased process memory by about 33 MiB in 256 ms, well within the five-second timeout. Even though its first byte was invalid JSON, the response was not rejected until the body ended.

This is a non-blocking resource-usage concern: a faulty policy service can consume excessive memory or stop the MCP process. Enforce a small verdict-size limit while reading chunks and return AuthorityUnavailable when it is exceeded; checking only Content-Length would miss streamed responses.

Artifacts

Executed Rust test for bounded authority response buffering

  • The unique Rust integration test sends small and 32 MiB chunked responses through the real authority implementation and measures live process memory, demonstrating full-body buffering safely.

Runner used to execute the probe once and capture evidence

  • The runner copies the exact test source, invokes Cargo once, and saves captured output with command metadata, preserving a reproducible execution record.

Small-response control on unchanged PR code

  • The captured 1 KiB control received HTTP/1.1 200 OK and remained pending until the chunked terminator, with no observed RSS increase.

Large-response probe on unchanged PR code

  • The captured 32 MiB response received HTTP/1.1 200 OK and increased RSS by 33,512 KiB before termination, confirming substantial buffering within the deadline.

Complete execution record and unchanged product source

  • The full capture records the command, working directory, exit code, executed-source hash, passing test output, and product-source inspection, tying the observations to unchanged PR HEAD.

View artifacts

TREX Ran code and verified through TREX

Comment thread docs/external-spending-authority.md Outdated
Comment on lines +16 to +18
The first extension is programmatic. This PR adds no command runner, HTTP client,
CLI flag or new YAML field. A host can implement a provider using its existing
local IPC or authenticated policy client. Provider failures must remain errors;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Guide hides the supplied provider

The setup guide says this PR adds no HTTP client and suggests implementing a provider with an existing policy client. This PR now publicly exports RemoteHttpAuthority, whose constructor creates an HTTP client and whose implementation sends the authorization request.

This is a non-blocking documentation concern: hosts following the guide may write a provider that is already supplied. Update the paragraph and show how to bind RemoteHttpAuthority, while keeping custom providers as an option.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Artifacts

Executed documentation and provider consistency check

  • This Python script was executed against the parent and PR revisions to compare the quoted guidance with the public HTTP provider source, reproducing the documentation mismatch.

Parent revision output without the HTTP provider

  • The focused check ran against the parent revision and captured the guidance, absent provider, and exit code 0, showing no contradiction at that revision.

PR revision output with the exported HTTP provider

  • The same check ran against PR525 and captured the unchanged guidance alongside the exported provider and HTTP implementation with exit code 1, confirming the stale claim.

View artifacts

TREX Ran code and verified through TREX

This was referenced Oct 21, 2026
…t body

- Treat a present `unavailable` value that is not a JSON boolean as a
  malformed verdict and return AuthorityUnavailable instead of coercing
  it to false. Found by review: a verdict such as
  {"decision":"allow","unavailable":"true"} previously reached wallet
  approval because as_bool() -> None fell through unwrap_or(false).
- Stream the verdict body under a 64 KiB cap (MAX_VERDICT_BYTES) instead
  of buffering an unbounded 2xx response from the consulted authority.
- Regression tests in tests/remote_authority.rs: seven malformed
  `unavailable` shapes fail closed; well-formed flags keep their
  semantics (allow/deny/precedence); 100 KiB verdict rejected; 32 KiB
  verdict still parsed. Validated with cargo test (stable 1.99).

Addresses the review findings on solana-foundation#525 (P1 malformed availability flags,
P2 unbounded verdict buffering).
@eddyflores100-lang

Copy link
Copy Markdown
Author

Fix pushed to the branch (commit 697f0cd):

  1. P1 — malformed verdicts approve spending: map_verdict now matches unavailable strictly. A present value that is not a JSON boolean (string, null, number, object, array) returns AuthorityUnavailable — nothing is coerced to false. The only path to Allow remains an explicit decision:"allow" with an explicit or absent boolean false.

  2. P2 — verdicts have no size limit: the body is now streamed under a hard 64 KiB cap (MAX_VERDICT_BYTES); a larger 2xx response fails closed instead of being buffered in full.

  3. P2 — guide wording: acknowledged — the wording that suggests the PR ships no HTTP client will be corrected; the constructor does create the client (that is the point of the reference provider).

Regression tests added to tests/remote_authority.rs: seven malformed unavailable shapes fail closed, well-formed flags keep their semantics (allow / deny / unavailable:true precedence), a 100 KiB verdict is rejected, a 32 KiB verdict still parses. All pass locally with cargo test (stable 1.99).

The fail-open path was exactly the failure mode this module claims to prevent, so it deserved the strict-typing fix rather than a deserializer tweak. Thanks for the review — the loopback + signed-retry reproduction made the case unambiguous.

…proval refactor

- Session cache reuse stays disabled when an external authority gates the
  flow (cached sessions must not shortcut the verdict).
- Hardware/account probing in the X402Challenge path stays after the
  authority verdict, with the wallet-switch identity check.
- Adopts upstream's payer-keyed session cache, cross-origin challenge
  rejection, and scope.with_approval payment building.
Comment thread rust/crates/mcp/src/tools/curl.rs Outdated
};
let cache = SessionCache::default();
cache.store(
session_cache_key("GET", &url).unwrap(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Cache test cannot compile

The new test calls session_cache_key with two arguments, but it requires three: payer, method, and resource_url. Running cargo check --locked --offline -p pay-mcp --tests fails here with E0061; the same check succeeds on the PR base. This prevents contributors from compiling the crate's full test suite. Pass the matching payer key as the first argument.

TREX Ran code and verified through TREX

assert!(text(&result).contains("DENIED"));
assert_eq!(m.probes.load(Ordering::SeqCst), 1);
assert_eq!(m.paid.load(Ordering::SeqCst), 0);
assert_eq!(c.store.reads.load(Ordering::SeqCst), 0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Account-read checks always fail

The denial test expects zero account reads, but do_paid_fetch calls session_payer before fetching the quote or consulting the authority. That calls store.load(), which increments reads. The denial test fails with one read instead of zero, and the integration run confirms the same mismatch at lines 379, 560, and 574. These failures prevent the integration suite from passing even when the authority correctly denies spending.

Skip the unused payer lookup when the authority disables session reuse, or revise the assertions if account reads are allowed.

TREX Ran code and verified through TREX

…nt RemoteHttpAuthority

- curl.rs cache test: session_payer() derives an empty payer with an empty
  MemoryAccountsStore, so the preloaded key must be session_cache_key("", "GET", url);
  fixes the E0061 two-vs-three argument compile error in the lib test target.
- external_authority.rs: account-read assertions now expect the one benign
  session_payer() store.load() that precedes the verdict (upstream payer-keyed
  session cache); denial/provider-error/unsupported paths still show exactly one
  read and zero after failure.
- canonical CAIP-2-only challenge under a USD cap now flows after upstream's
  CAIP-2 parser support; the test locks the new behavior (authority consulted,
  in-cap payment signed once) instead of the removed rejection.
- docs: setup guide now shows the shipped RemoteHttpAuthority reference provider
  (constructor builds the client) and keeps custom providers as an option.

Full suite: cargo test --locked -p pay-mcp --tests = 199 passed, 0 failed.
@eddyflores100-lang

Copy link
Copy Markdown
Author

Both new P1s are fixed on the branch (5df4aba), full suite green:

P1 — Cache test cannot compile: right. do_paid_fetch derives the payer via session_payer(), and with the empty MemoryAccountsStore in that test the payer is "". The cache test now preloads session_cache_key("", "GET", &url) with a comment explaining where the empty payer comes from. cargo check --locked -p pay-mcp --tests is clean.

P1 — Account-read checks always fail: I adopted the "revise the assertions" option (product code untouched — with an authority present the cached session is never consulted anyway, and minimizing divergence from upstream is the point of this stacked PR). The assertions now expect exactly the one benign session_payer() store.load() that precedes the verdict:

  • denial / provider-error / unsupported-version paths: exactly 1 read, still no account work after the failure;
  • cap-rejection iteration of the YAML-gate loop: 1 read (the lookup happens inside the paid flow, before the cap check);
  • the replay/conflict snapshot assertion is unchanged and still passing (guard-blocked calls never re-enter the fetch).

New behavior locked by a test: pre-merge, a canonical CAIP-2-only challenge under a USD max_payment cap failed YAML parsing (invalid Solana network). Upstream's parser now understands CAIP-2, so that assertion could not hold on the merged tree. Replaced it with caip2_only_challenge_with_yaml_cap_flows_after_upstream_caip2_support: the authority is consulted once, the in-cap payment is signed and retried, no error — the test now documents the interaction instead of a rejection path that no longer exists.

P2 — Guide hides the supplied provider: paragraph rewritten and a binding snippet for RemoteHttpAuthority::new(...).with_request_timeout(...) added; custom providers remain documented as the alternative.

cargo test --locked -p pay-mcp --tests = 199 passed, 0 failed (161 lib + 11 remote_authority + 14 external_authority + 13 curl_http_e2e; 4 ignored pre-existing).

@eddyflores100-lang

Copy link
Copy Markdown
Author

Ready for review — status and notes.

All greptile findings on this PR are addressed in commits 697f0cd and 5df4aba: malformed unavailable verdicts now fail closed, verdict bodies are capped, the cache-test compile issue is fixed, tests are adapted and the docs guide updated. The pay-mcp test suite is green on this branch.

One design note for review: verdict bodies are capped by MAX_VERDICT_BYTES (64 KiB) — deliberately much tighter than pay-core's MAX_PUBLIC_RESPONSE_BODY_BYTES (64 MiB). Authority verdicts are tens of bytes; the tight bound is what prevents a broken or hostile authority from forcing response-sized buffering. The latest commit (ba0451d) adds a doc comment spelling out that reasoning.

The only non-green status on the head commit is the Vercel – payment-debugger deploy preview, which looks like a fork-PR authorization issue on Vercel's side rather than anything in this PR's code path.

Overlap question for maintainers: this PR and #514 both land external spending-authority behavior. If you'd rather see #514 go first, happy to rebase this one on top of it — whichever order you prefer.

Thanks!

@eddyflores100-lang

Copy link
Copy Markdown
Author

Closing this PR — it has been open without activity for a while and I am cleaning up my queue. Happy to re-open or open a fresh PR if this is still relevant. Thanks for the review so far!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants