diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index 4e9b6d67da..a85d882f95 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -52,6 +52,7 @@ Anything after the `--` double dash (the "slop") is parsed as arguments to the c - `config` — Manage CLI configuration - `snapshot` — Download a snapshot of a ledger from an archive - `token` — Interact with SEP-41 tokens and Stellar Asset Contracts +- `checkout` — Pay for and fetch an x402-protected resource - `tx` — Sign, Simulate, and Send transactions - `xdr` — Decode and encode XDR - `strkey` — Decode and encode strkey @@ -2501,6 +2502,52 @@ Calls the token's Stellar Asset Contract `set_authorized` function. A non-SAC co - `--fee ` — ⚠️ Deprecated, use `--inclusion-fee`. Fee amount for transaction, in stroops. 1 stroop = 0.0000001 xlm - `--inclusion-fee ` — Maximum fee amount for transaction inclusion, in stroops. 1 stroop = 0.0000001 xlm. Defaults to 100 if no arg, env, or config value is provided +## `stellar checkout` + +Pay for and fetch an x402-protected resource + +**Usage:** `stellar checkout [OPTIONS] --source-account ` + +###### **Arguments:** + +- `` — The x402-protected resource to fetch and pay for + +###### **Global Options:** + +- `--config-dir ` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings + +###### **Options:** + +- `--source-account ` [alias: `source`] — Account that pays for the resource. Signs and authorizes the on-chain payment, so it must be an identity or key you control +- `--max-amount ` — Maximum amount to pay, in the asset's display units (e.g. `1` = 1.0 USDC, roughly $1). Aborts before signing if the challenge asks for more. Set to `none` to disable the cap + + Default value: `1` + +- `--build-only` — Build and authorization-sign the payment and print the proof, without fetching the paid resource +- `--output ` — Format of the output + + Default value: `text` + + Possible values: + - `text`: Human-readable text + - `json`: Compact, single-line JSON output + - `json-formatted`: Formatted (multiline) JSON output + +###### **RPC Options:** + +- `--rpc-url ` — RPC server endpoint +- `--rpc-header ` — RPC Header(s) to include in requests to the RPC provider, example: "X-API-Key: abc123". Multiple headers can be added by passing the option multiple times +- `--network-passphrase ` — Network passphrase to sign the transaction sent to the rpc server +- `-n`, `--network ` — Name of network to use from config + +###### **Signing Options:** + +- `--sign-with-key ` — Sign with a local key or key saved in OS secure storage. Can be an identity (--sign-with-key alice), a secret key (--sign-with-key SC36…), or a seed phrase (--sign-with-key "kite urban…"). If using seed phrase, `--hd-path` defaults to the `0` path +- `--hd-path ` — If using a seed phrase to sign, sets which hierarchical deterministic path to use, e.g. `m/44'/148'/{hd_path}`. Example: `--hd-path 1`. Default: `0` +- `--sign-with-lab` — Sign with https://lab.stellar.org +- `--sign-with-ledger` — Sign with a ledger wallet +- `--auto-sign` — Sign without prompting for approval. Only applies to signatures that require user approval, like non-root Soroban auth entries + ## `stellar tx` Sign, Simulate, and Send transactions diff --git a/cmd/crates/soroban-test/tests/it/integration.rs b/cmd/crates/soroban-test/tests/it/integration.rs index 033a9b704d..4ab6590532 100644 --- a/cmd/crates/soroban-test/tests/it/integration.rs +++ b/cmd/crates/soroban-test/tests/it/integration.rs @@ -1,6 +1,7 @@ mod auth; mod auto_build; mod bindings; +mod checkout; mod constructor; mod contract; mod cookbook; diff --git a/cmd/crates/soroban-test/tests/it/integration/checkout.rs b/cmd/crates/soroban-test/tests/it/integration/checkout.rs new file mode 100644 index 0000000000..b3117fdf2c --- /dev/null +++ b/cmd/crates/soroban-test/tests/it/integration/checkout.rs @@ -0,0 +1,198 @@ +use httpmock::prelude::*; +use serde_json::{json, Value}; +use soroban_cli::xdr::{ + HostFunction, Int128Parts, Limits, OperationBody, Preconditions, ReadXdr, ScVal, + SorobanCredentials, TransactionEnvelope, +}; +use soroban_test::{AssertExt, TestEnv}; + +use crate::integration::{ + token::{deploy_sac, sac_id}, + util::{new_account, test_address}, +}; + +/// Base64 JSON `PAYMENT-RESPONSE` for a settled payment with tx hash `abc123`. +const SETTLEMENT_HEADER: &str = + "eyJzdWNjZXNzIjp0cnVlLCJ0cmFuc2FjdGlvbiI6ImFiYzEyMyIsIm5ldHdvcmsiOiJzdGVsbGFyOmxvY2FsIn0="; + +/// An x402 challenge asking for `amount` stroops of `asset`, paid to `pay_to`. +fn challenge(asset: &str, pay_to: &str, amount: i128) -> Value { + json!({ + "x402Version": 2, + "accepts": [{ + "scheme": "exact", + "network": "stellar:local", + "asset": asset, + "payTo": pay_to, + "amount": amount.to_string(), + "maxTimeoutSeconds": 60, + "extra": { "areFeesSponsored": true } + }], + "resource": { "url": "/pay" } + }) +} + +/// Whether the request carries an x402 payment proof. +fn has_payment_signature(req: &HttpMockRequest) -> bool { + req.headers.as_ref().is_some_and(|headers| { + headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("payment-signature")) + }) +} + +/// Mock the first, unpaid request with a `402` carrying `challenge`. +fn mock_challenge<'a>(server: &'a MockServer, challenge: &Value) -> httpmock::Mock<'a> { + server.mock(|when, then| { + when.method(GET) + .path("/pay") + .matches(|req| !has_payment_signature(req)); + then.status(402).json_body(challenge.clone()); + }) +} + +/// Mock the paid retry: any request carrying a payment proof gets `body`. +fn mock_paid<'a>(server: &'a MockServer, body: &[u8]) -> httpmock::Mock<'a> { + server.mock(|when, then| { + when.method(GET).path("/pay").matches(has_payment_signature); + then.status(200) + .header("content-type", "application/octet-stream") + .header("payment-response", SETTLEMENT_HEADER) + .body(body); + }) +} + +/// Deploy the native asset contract and create the pay-to account, returning +/// `(asset contract id, pay-to address)`. +fn setup(sandbox: &TestEnv) -> (String, String) { + deploy_sac(sandbox, "native", "test"); + (sac_id(sandbox, "native"), new_account(sandbox, "merchant")) +} + +#[tokio::test] +async fn build_only_emits_a_proof_authorizing_only_the_transfer() { + let sandbox = &TestEnv::new(); + let (asset, pay_to) = setup(sandbox); + let payer = test_address(sandbox); + let amount: i128 = 1_000_000; + + let server = MockServer::start(); + let challenge_mock = mock_challenge(&server, &challenge(&asset, &pay_to, amount)); + let paid_mock = mock_paid(&server, b"paid"); + + let stdout = sandbox + .new_assert_cmd("checkout") + .args([&server.url("/pay"), "--build-only", "--output", "json"]) + .assert() + .success() + .stdout_as_str(); + challenge_mock.assert(); + paid_mock.assert_hits(0); + + let proof: Value = serde_json::from_str(&stdout).unwrap(); + assert!(proof["payment_signature"].as_str().is_some()); + assert_eq!(proof["payload"]["accepted"]["payTo"], json!(pay_to)); + + let transaction = proof["payload"]["payload"]["transaction"].as_str().unwrap(); + let TransactionEnvelope::Tx(envelope) = + TransactionEnvelope::from_xdr_base64(transaction, Limits::none()).unwrap() + else { + panic!("expected a v1 transaction envelope"); + }; + assert!(envelope.signatures.is_empty()); + let Preconditions::Time(time_bounds) = &envelope.tx.cond else { + panic!("expected time bounds, got {:?}", envelope.tx.cond); + }; + assert!(time_bounds.max_time.0 > 0); + + let [op] = envelope.tx.operations.as_slice() else { + panic!("expected a single operation"); + }; + let OperationBody::InvokeHostFunction(op) = &op.body else { + panic!("expected an invoke host function operation"); + }; + let HostFunction::InvokeContract(call) = &op.host_function else { + panic!("expected a contract call"); + }; + assert_eq!(call.contract_address.to_string(), asset); + assert_eq!(call.function_name.to_string(), "transfer"); + let [ScVal::Address(from), ScVal::Address(to), value] = call.args.as_slice() else { + panic!("expected transfer(from, to, amount), got {:?}", call.args); + }; + assert_eq!(from.to_string(), payer); + assert_eq!(to.to_string(), pay_to); + assert_eq!( + *value, + ScVal::I128(Int128Parts { + hi: 0, + lo: u64::try_from(amount).unwrap() + }) + ); + + let [auth] = op.auth.as_slice() else { + panic!("expected a single authorization entry"); + }; + let SorobanCredentials::Address(credentials) = &auth.credentials else { + panic!("expected address credentials"); + }; + assert_ne!(credentials.signature, ScVal::Void); + assert!(auth.root_invocation.sub_invocations.is_empty()); +} + +#[tokio::test] +async fn payment_over_the_cap_is_refused_before_signing() { + let sandbox = &TestEnv::new(); + let (asset, pay_to) = setup(sandbox); + + let server = MockServer::start(); + let challenge_mock = mock_challenge(&server, &challenge(&asset, &pay_to, 20_000_000)); + let paid_mock = mock_paid(&server, b"paid"); + + let stdout = sandbox + .new_assert_cmd("checkout") + .args([&server.url("/pay"), "--output", "json"]) + .assert() + .failure() + .stdout_as_str(); + challenge_mock.assert(); + paid_mock.assert_hits(0); + + let error: Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(error["error"]["type"], json!("max_amount_exceeded")); +} + +#[tokio::test] +async fn paid_retry_returns_the_resource_and_receipt() { + let sandbox = &TestEnv::new(); + let (asset, pay_to) = setup(sandbox); + let body = [0x89, b'P', b'N', b'G', 0xff, 0x00, b'\n', 0xfe]; + + let server = MockServer::start(); + let challenge_mock = mock_challenge(&server, &challenge(&asset, &pay_to, 1_000_000)); + let paid_mock = mock_paid(&server, &body); + + let output = sandbox + .new_assert_cmd("checkout") + .arg(server.url("/pay")) + .assert() + .success(); + assert_eq!(output.get_output().stdout, body); + + let stdout = sandbox + .new_assert_cmd("checkout") + .args([&server.url("/pay"), "--output", "json"]) + .assert() + .success() + .stdout_as_str(); + challenge_mock.assert_hits(2); + paid_mock.assert_hits(2); + + let receipt: Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(receipt["tx_hash"], json!("abc123")); + assert_eq!(receipt["network"], json!("stellar:local")); + assert_eq!(receipt["resource"]["status"], json!(200)); + assert_eq!( + receipt["resource"]["content_type"], + json!("application/octet-stream") + ); +} diff --git a/cmd/soroban-cli/src/cli.rs b/cmd/soroban-cli/src/cli.rs index 30171ee713..9c1afabd8a 100644 --- a/cmd/soroban-cli/src/cli.rs +++ b/cmd/soroban-cli/src/cli.rs @@ -156,6 +156,7 @@ fn json_error_format(cmd: &commands::Cmd) -> Option { commands::Cmd::Token(token::Cmd::Clawback(cmd)) => cmd.output.into(), commands::Cmd::Token(token::Cmd::SetAdmin(cmd)) => cmd.output.into(), commands::Cmd::Token(token::Cmd::SetAuthorized(cmd)) => cmd.output.into(), + commands::Cmd::Checkout(cmd) => cmd.output.into(), _ => return None, }; @@ -168,6 +169,7 @@ fn json_error_format(cmd: &commands::Cmd) -> Option { fn error_type(err: &commands::Error) -> &'static str { match err { commands::Error::Token(e) => e.error_type(), + commands::Error::Checkout(e) => e.error_type(), _ => "unknown", } } diff --git a/cmd/soroban-cli/src/commands/contract/invoke.rs b/cmd/soroban-cli/src/commands/contract/invoke.rs index 85763ef277..2fd1fdceba 100644 --- a/cmd/soroban-cli/src/commands/contract/invoke.rs +++ b/cmd/soroban-cli/src/commands/contract/invoke.rs @@ -144,6 +144,9 @@ pub enum Error { #[error(transparent)] Rpc(#[from] rpc::Error), + #[error("refusing to sign the payment: {0}")] + UnsafePaymentAuthorization(&'static str), + #[error("missing operation result")] MissingOperationResult, @@ -472,6 +475,133 @@ impl Cmd { .expect("output_to_string always returns a result"); Ok(TxnResult::Res(InvokeReceipt { tx_hash, output })) } + + /// Build, simulate, and authorization-sign this invocation into an off-chain + /// payment proof, without signing the transaction envelope or submitting it. + /// + /// The transaction is sourced by the null account, so the paying address + /// authorizes the call through an explicitly-signed authorization entry + /// (expiring at `auth_expiration_ledger`) rather than through the transaction + /// signature. This is what an x402 payment needs: the client proves the + /// transfer is authorized, and the facilitator re-sources the operation onto + /// its own account, signs the envelope, and submits it. Returns the + /// assembled, auth-signed transaction for the caller to serialize into the + /// payment header. + /// + /// Requires `self.invocation` to be set (the by-position call used by typed + /// clients like `stellar token` / `stellar checkout`). + pub async fn build_payment_authorization( + &self, + config: &config::Args, + auth_expiration_ledger: u32, + quiet: bool, + no_cache: bool, + ) -> Result { + self.auth_mode.validate_not_enforce()?; + + let print = print::Print::new(quiet); + let network = config.get_network()?; + let contract_id = self + .contract_id + .resolve_contract_id(&config.locator, &network.network_passphrase)?; + let client = network.rpc_client()?; + client + .verify_network_passphrase(Some(&network.network_passphrase)) + .await?; + + let global_args = global::Args { + locator: config.locator.clone(), + filter_logs: Vec::default(), + quiet, + verbose: false, + very_verbose: false, + no_cache, + }; + + let spec_entries = get_remote_contract_spec( + &contract_id.0, + &config.locator, + &config.network, + Some(&global_args), + Some(config), + ) + .await + .map_err(Error::from)?; + + let inv = self + .invocation + .as_ref() + .expect("build_payment_authorization requires a positional invocation"); + let (_function, _spec, host_function_params, signers) = + build_host_function_parameters_by_position( + &contract_id, + &inv.function, + &inv.args, + &spec_entries, + config, + &print, + )?; + + // Null source account: the paying address is then a non-invoker whose + // `require_auth` surfaces as a signable `Address` authorization entry, + // rather than being covered by the (absent) transaction signature. + let tx = build_invoke_contract_tx( + host_function_params, + 1, + config.get_inclusion_fee()?, + Uint256([0; 32]), + )?; + + let assembled = simulate_and_assemble_transaction( + &client, + &tx, + self.resources.resource_config(), + self.resources.resource_fee, + self.auth_mode.to_rpc(), + ) + .await?; + let assembled = self.resources.apply_to_assembled_txn(assembled); + let tx = assembled.transaction().clone(); + + let [Operation { + body: OperationBody::InvokeHostFunction(op), + .. + }] = tx.operations.as_slice() + else { + return Err(Error::UnsafePaymentAuthorization( + "it must be a single contract call", + )); + }; + if let Some(reason) = + crate::signer::validation::payment_authorization_violation(&op.host_function, &op.auth) + { + return Err(Error::UnsafePaymentAuthorization(reason)); + } + + // The payer is the source account, so honor the signing options for it; + // otherwise fall back to the signers resolved from the arguments. + let signers = match config + .sign_with + .auth_signer(&config.locator, &print) + .map_err(config::Error::from)? + { + Some(signer) => vec![signer], + None => signers, + }; + + let signed = crate::signer::sign_soroban_authorizations( + &tx, + &signers, + auth_expiration_ledger, + &network.network_passphrase, + config.sign_with.auto_sign, + &print, + ) + .await + .map_err(|e| Error::Config(config::Error::Signer(e)))?; + + Ok(signed.unwrap_or(tx)) + } } /// The outcome of a submitted contract invocation: the decoded return value diff --git a/cmd/soroban-cli/src/commands/mod.rs b/cmd/soroban-cli/src/commands/mod.rs index 106c054b3d..e14d0b52b3 100644 --- a/cmd/soroban-cli/src/commands/mod.rs +++ b/cmd/soroban-cli/src/commands/mod.rs @@ -19,6 +19,7 @@ pub mod keys; pub mod ledger; pub mod message; pub mod network; +pub mod pay; pub mod plugin; pub mod skill; pub mod snapshot; @@ -126,6 +127,7 @@ impl Root { Cmd::Skill(skill) => skill.run(), Cmd::Keys(id) => id.run(&self.global_args).await?, Cmd::Token(token) => token.run(&self.global_args).await?, + Cmd::Checkout(checkout) => checkout.run(&self.global_args).await?, Cmd::Tx(tx) => tx.run(&self.global_args).await?, Cmd::Ledger(ledger) => ledger.run(&self.global_args).await?, Cmd::Message(message) => message.run(&self.global_args).await?, @@ -196,6 +198,9 @@ pub enum Cmd { #[command(subcommand)] Token(token::Cmd), + /// Pay for and fetch an x402-protected resource + Checkout(pay::Cmd), + /// Sign, Simulate, and Send transactions #[command(subcommand)] Tx(tx::Cmd), @@ -287,6 +292,9 @@ pub enum Error { #[error(transparent)] Token(#[from] token::Error), + #[error(transparent)] + Checkout(#[from] pay::Error), + #[error(transparent)] Tx(#[from] tx::Error), diff --git a/cmd/soroban-cli/src/commands/pay/cap.rs b/cmd/soroban-cli/src/commands/pay/cap.rs new file mode 100644 index 0000000000..c0504af40f --- /dev/null +++ b/cmd/soroban-cli/src/commands/pay/cap.rs @@ -0,0 +1,221 @@ +//! The `--max-amount` spend cap. +//! +//! The cap is denominated in the asset's display units (so `1` means 1.0 of the +//! asset — roughly $1 for a 7-decimal USD stablecoin like USDC). It defaults to +//! `1` so an unconfigured `checkout` refuses to pay more than that, and can be +//! disabled with `none` / `off` / `unlimited`. + +use std::str::FromStr; + +use crate::commands::token::args::MAX_DECIMALS; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("invalid --max-amount `{0}`: expected a decimal amount or `none` to disable")] + Invalid(String), + + #[error( + "--max-amount `{amount}` has more fractional digits than the asset's {decimals} decimals" + )] + TooPrecise { amount: String, decimals: u32 }, + + #[error("--max-amount `{0}` is too large for this asset")] + Overflow(String), + + #[error( + "the payment requires {required} but the --max-amount cap is {cap} \ + (asset's smallest unit).\n\ + Raise it with `--max-amount ` / `STELLAR_CHECKOUT_MAX_AMOUNT`, \ + or disable it with `--max-amount none`." + )] + Exceeded { required: i128, cap: i128 }, + + #[error("the asset's {decimals} decimals exceed the supported maximum of {MAX_DECIMALS}")] + DecimalsTooLarge { decimals: u32 }, +} + +impl Error { + /// Machine-readable discriminator for the JSON error envelope's `type` field. + #[must_use] + pub fn error_type(&self) -> &'static str { + match self { + Error::Invalid(_) => "invalid_max_amount", + Error::TooPrecise { .. } => "max_amount_too_precise", + Error::Overflow(_) => "max_amount_overflow", + Error::Exceeded { .. } => "max_amount_exceeded", + Error::DecimalsTooLarge { .. } => "asset_decimals_too_large", + } + } +} + +/// The resolved spend cap: either a decimal limit (in the asset's display units) +/// or no limit at all. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MaxAmount { + /// No cap — pay whatever the challenge asks. + Unlimited, + /// A cap given as a decimal string in the asset's display units (e.g. `1`, + /// `0.5`). Converted to the asset's smallest unit at enforcement time, once + /// the asset's `decimals` are known. + Limit(String), +} + +impl FromStr for MaxAmount { + type Err = Error; + + fn from_str(s: &str) -> Result { + let trimmed = s.trim(); + match trimmed.to_ascii_lowercase().as_str() { + "none" | "off" | "unlimited" => Ok(MaxAmount::Unlimited), + _ => { + validate_decimal(trimmed)?; + Ok(MaxAmount::Limit(trimmed.to_string())) + } + } + } +} + +impl MaxAmount { + /// Enforce the cap against a `required` amount (in the asset's smallest unit), + /// given the asset's `decimals`. A no-op when the cap is [`MaxAmount::Unlimited`]. + pub fn enforce(&self, required: i128, decimals: u32) -> Result<(), Error> { + let MaxAmount::Limit(amount) = self else { + return Ok(()); + }; + let cap = decimal_to_raw(amount, decimals)?; + if required > cap { + return Err(Error::Exceeded { required, cap }); + } + Ok(()) + } +} + +/// Validate that `s` is a non-negative decimal number (no sign, no exponent), +/// without needing to know the asset's decimals yet. +fn validate_decimal(s: &str) -> Result<(), Error> { + if s.is_empty() { + return Err(Error::Invalid(s.to_string())); + } + let (int_part, frac_part) = match s.split_once('.') { + Some((i, f)) => (i, f), + None => (s, ""), + }; + // A bare "." , "1." , or ".5" are all rejected: require digits on both sides + // that are actually present (an empty fractional part from a trailing "." is + // invalid). + if int_part.is_empty() || !int_part.bytes().all(|b| b.is_ascii_digit()) { + return Err(Error::Invalid(s.to_string())); + } + if s.contains('.') && (frac_part.is_empty() || !frac_part.bytes().all(|b| b.is_ascii_digit())) { + return Err(Error::Invalid(s.to_string())); + } + Ok(()) +} + +/// Convert a non-negative decimal string in display units to the asset's +/// smallest unit, scaling by `10^decimals`. Rejects more fractional digits than +/// the asset supports rather than silently rounding. +fn decimal_to_raw(s: &str, decimals: u32) -> Result { + validate_decimal(s)?; + if decimals > MAX_DECIMALS { + return Err(Error::DecimalsTooLarge { decimals }); + } + let (int_part, frac_part) = s.split_once('.').unwrap_or((s, "")); + let scale = decimals as usize; + if frac_part.len() > scale { + return Err(Error::TooPrecise { + amount: s.to_string(), + decimals, + }); + } + // Right-pad the fractional digits to exactly `decimals`, then the whole + // string is the integer value in the smallest unit. + let mut digits = String::with_capacity(int_part.len() + scale); + digits.push_str(int_part); + digits.push_str(frac_part); + for _ in 0..(scale - frac_part.len()) { + digits.push('0'); + } + // Strip leading zeros so `parse` doesn't choke on e.g. "0010000000"; an + // all-zero string parses as 0. + let digits = digits.trim_start_matches('0'); + if digits.is_empty() { + return Ok(0); + } + digits + .parse::() + .map_err(|_| Error::Overflow(s.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn disable_keywords_parse_to_unlimited() { + for kw in ["none", "off", "unlimited", "NONE", "Off"] { + assert_eq!(kw.parse::().unwrap(), MaxAmount::Unlimited); + } + } + + #[test] + fn decimal_values_parse_to_limit() { + assert_eq!( + "1".parse::().unwrap(), + MaxAmount::Limit("1".into()) + ); + assert_eq!( + "0.5".parse::().unwrap(), + MaxAmount::Limit("0.5".into()) + ); + } + + #[test] + fn invalid_values_are_rejected() { + for bad in ["", "abc", "-1", "1.", ".5", "1.2.3", "1e3"] { + assert!( + bad.parse::().is_err(), + "expected `{bad}` to be rejected" + ); + } + } + + #[test] + fn one_dollar_at_seven_decimals_is_ten_million() { + assert_eq!(decimal_to_raw("1", 7).unwrap(), 10_000_000); + assert_eq!(decimal_to_raw("0.5", 7).unwrap(), 5_000_000); + assert_eq!(decimal_to_raw("1.2345", 7).unwrap(), 12_345_000); + assert_eq!(decimal_to_raw("0", 7).unwrap(), 0); + assert_eq!(decimal_to_raw("10", 0).unwrap(), 10); + } + + #[test] + fn excess_precision_is_rejected() { + let err = decimal_to_raw("1.12345678", 7).unwrap_err(); + assert_eq!(err.error_type(), "max_amount_too_precise"); + } + + #[test] + fn oversized_decimals_are_rejected_before_scaling() { + let err = decimal_to_raw("1", MAX_DECIMALS + 1).unwrap_err(); + assert_eq!(err.error_type(), "asset_decimals_too_large"); + let err = decimal_to_raw("1", u32::MAX).unwrap_err(); + assert_eq!(err.error_type(), "asset_decimals_too_large"); + assert!(decimal_to_raw("0", MAX_DECIMALS).is_ok()); + } + + #[test] + fn enforce_passes_under_cap_and_fails_over() { + let cap: MaxAmount = "1".parse().unwrap(); + // 1.0 USDC default cap, 7 decimals → 10_000_000 raw. + assert!(cap.enforce(10_000_000, 7).is_ok()); + assert!(cap.enforce(9_999_999, 7).is_ok()); + let err = cap.enforce(10_000_001, 7).unwrap_err(); + assert_eq!(err.error_type(), "max_amount_exceeded"); + } + + #[test] + fn unlimited_never_enforces() { + assert!(MaxAmount::Unlimited.enforce(i128::MAX, 7).is_ok()); + } +} diff --git a/cmd/soroban-cli/src/commands/pay/challenge.rs b/cmd/soroban-cli/src/commands/pay/challenge.rs new file mode 100644 index 0000000000..5684fb0d3e --- /dev/null +++ b/cmd/soroban-cli/src/commands/pay/challenge.rs @@ -0,0 +1,464 @@ +//! x402 (v2) payment-challenge wire types and the base64-JSON header codec. +//! +//! These mirror the `@x402/core` / `@x402/stellar` TypeScript reference +//! implementation: a `402 Payment Required` response carries a `PAYMENT-REQUIRED` +//! declaration (as a base64-encoded JSON header, or the same JSON in the body), +//! the client replays the request with a base64-encoded JSON `PAYMENT-SIGNATURE` +//! proof, and a successful response carries a base64-encoded JSON +//! `PAYMENT-RESPONSE` settlement. + +use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; +use serde_json::Value; + +/// Header carrying the server's payment declaration on a `402` response. +pub const PAYMENT_REQUIRED_HEADER: &str = "PAYMENT-REQUIRED"; +/// Header carrying the client's signed payment proof on the replayed request. +pub const PAYMENT_SIGNATURE_HEADER: &str = "PAYMENT-SIGNATURE"; +/// Header carrying the facilitator's settlement result on a paid response. +pub const PAYMENT_RESPONSE_HEADER: &str = "PAYMENT-RESPONSE"; + +/// CAIP-2 network id for Stellar testnet, as used in `accepts[].network`. +const STELLAR_TESTNET_CAIP2: &str = "stellar:testnet"; +/// CAIP-2 network id for Stellar mainnet, as used in `accepts[].network`. +const STELLAR_PUBNET_CAIP2: &str = "stellar:pubnet"; +/// Network id for a local standalone network. Not part of the x402 spec; lets +/// checkout run against a local network. +const STELLAR_LOCAL_CAIP2: &str = "stellar:local"; + +const TESTNET_PASSPHRASE: &str = "Test SDF Network ; September 2015"; +const PUBNET_PASSPHRASE: &str = "Public Global Stellar Network ; September 2015"; +const LOCAL_PASSPHRASE: &str = "Standalone Network ; February 2017"; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("the server's {header} header is not valid base64-encoded JSON")] + MalformedHeader { header: &'static str }, + + #[error("the server's 402 response carried no payment declaration")] + MissingChallenge, + + #[error( + "the server offered no payment option for {network}.\n\ + Offered networks: {offered}" + )] + NoMatchingRequirement { network: String, offered: String }, + + #[error("the payment option uses an unsupported scheme `{0}`; only `exact` is supported")] + UnsupportedScheme(String), + + #[error("the payment option is missing an amount")] + MissingAmount, + + #[error("the payment option amount `{0}` is not a valid integer in the asset's smallest unit")] + InvalidAmount(String), + + #[error( + "the payment option does not sponsor fees (`extra.areFeesSponsored` is not true); \ + the exact scheme requires a fee-sponsoring facilitator" + )] + FeesNotSponsored, + + #[error(transparent)] + Serde(#[from] serde_json::Error), +} + +impl Error { + /// Machine-readable discriminator for the JSON error envelope's `type` field. + #[must_use] + pub fn error_type(&self) -> &'static str { + match self { + Error::MalformedHeader { .. } => "malformed_header", + Error::MissingChallenge => "missing_challenge", + Error::NoMatchingRequirement { .. } => "no_matching_requirement", + Error::UnsupportedScheme(_) => "unsupported_scheme", + Error::MissingAmount => "missing_amount", + Error::InvalidAmount(_) => "invalid_amount", + Error::FeesNotSponsored => "fees_not_sponsored", + Error::Serde(_) => "internal", + } + } +} + +/// The server's `402` payment declaration. +/// +/// The `accepts` options and `resource` are kept as raw JSON so the chosen +/// option can be echoed back verbatim in the payment proof's `accepted` field, +/// exactly as the server sent it. +#[derive(Debug, Clone)] +pub struct Challenge { + pub x402_version: u32, + pub accepts: Vec, + pub resource: Option, + /// Why the server rejected a payment, on a `402` returned for a replayed request. + pub error: Option, +} + +/// The typed subset of a payment requirement the client needs to build the +/// on-chain leg. Unknown fields are ignored here; the full option is preserved +/// as the raw [`Value`] alongside it (see [`Challenge::select_stellar`]). +#[derive(Debug, Clone, serde::Deserialize)] +pub struct Requirements { + pub scheme: String, + pub network: String, + pub asset: String, + #[serde(rename = "payTo")] + pub pay_to: String, + #[serde(default)] + pub amount: Option, + #[serde(rename = "maxAmountRequired", default)] + pub max_amount_required: Option, + #[serde(rename = "maxTimeoutSeconds", default)] + pub max_timeout_seconds: u64, + #[serde(default)] + pub extra: Option, +} + +#[derive(Debug, Clone, serde::Deserialize)] +pub struct Extra { + #[serde(rename = "areFeesSponsored", default)] + pub are_fees_sponsored: Option, +} + +impl Requirements { + /// The payment amount in the asset's smallest unit. The spec allows either + /// `amount` or the legacy `maxAmountRequired`; prefer the former. + pub fn amount_raw(&self) -> Result { + let raw = self + .amount + .as_deref() + .or(self.max_amount_required.as_deref()) + .ok_or(Error::MissingAmount)?; + raw.parse::() + .map_err(|_| Error::InvalidAmount(raw.to_string())) + } + + /// Whether the facilitator sponsors fees. The exact scheme requires this, + /// because the client signs only the authorization entry and never the + /// transaction envelope — the facilitator pays and submits. + #[must_use] + pub fn fees_sponsored(&self) -> bool { + self.extra + .as_ref() + .and_then(|e| e.are_fees_sponsored) + .unwrap_or(false) + } +} + +/// Map a Stellar network id (`stellar:testnet` / `stellar:pubnet` / `stellar:local`) to the +/// network passphrase used for signing. Returns `None` for ids this client +/// doesn't recognize. +#[must_use] +pub fn passphrase_for_caip2(network: &str) -> Option<&'static str> { + match network { + STELLAR_TESTNET_CAIP2 => Some(TESTNET_PASSPHRASE), + STELLAR_PUBNET_CAIP2 => Some(PUBNET_PASSPHRASE), + STELLAR_LOCAL_CAIP2 => Some(LOCAL_PASSPHRASE), + _ => None, + } +} + +impl Challenge { + /// Parse the challenge from a `402` response's `PAYMENT-REQUIRED` header + /// (base64-encoded JSON) when present, otherwise from the JSON body. + pub fn parse(header: Option<&str>, body: &[u8]) -> Result { + let value: Value = if let Some(header) = header.filter(|h| !h.is_empty()) { + let decoded = BASE64 + .decode(header.trim()) + .map_err(|_| Error::MalformedHeader { + header: PAYMENT_REQUIRED_HEADER, + })?; + serde_json::from_slice(&decoded).map_err(|_| Error::MalformedHeader { + header: PAYMENT_REQUIRED_HEADER, + })? + } else if !body.is_empty() { + serde_json::from_slice(body).map_err(|_| Error::MissingChallenge)? + } else { + return Err(Error::MissingChallenge); + }; + + Self::from_value(value) + } + + fn from_value(value: Value) -> Result { + let x402_version = value + .get("x402Version") + .and_then(Value::as_u64) + .and_then(|v| u32::try_from(v).ok()) + .ok_or(Error::MissingChallenge)?; + let accepts = value + .get("accepts") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let resource = value.get("resource").cloned(); + Ok(Self { + x402_version, + accepts, + resource, + error: value + .get("error") + .and_then(Value::as_str) + .map(str::to_string), + }) + } + + /// Select the `exact`-scheme option whose network matches `network_passphrase`, + /// returning both the raw option (to echo in the proof) and its typed view. + /// + /// Errors if no option targets the configured network, or none of the options + /// that do uses the `exact` scheme with sponsored fees. + pub fn select_stellar(&self, network_passphrase: &str) -> Result<(Value, Requirements), Error> { + let mut offered = Vec::new(); + let mut unsupported: Option = None; + + for raw in &self.accepts { + let Ok(req) = serde_json::from_value::(raw.clone()) else { + continue; + }; + offered.push(req.network.clone()); + if passphrase_for_caip2(&req.network) != Some(network_passphrase) { + continue; + } + if req.scheme != "exact" { + unsupported.get_or_insert(Error::UnsupportedScheme(req.scheme)); + } else if !req.fees_sponsored() { + unsupported.get_or_insert(Error::FeesNotSponsored); + } else { + return Ok((raw.clone(), req)); + } + } + + Err(unsupported.unwrap_or_else(|| Error::NoMatchingRequirement { + network: network_passphrase.to_string(), + offered: if offered.is_empty() { + "(none)".to_string() + } else { + offered.join(", ") + }, + })) + } +} + +/// The facilitator's settlement result, decoded from the `PAYMENT-RESPONSE` +/// header on a successful paid response. +#[derive(Debug, Clone, serde::Deserialize)] +pub struct Settlement { + #[serde(default)] + pub transaction: Option, + #[serde(default)] + pub network: Option, + #[serde(rename = "errorReason", default)] + pub error_reason: Option, + #[serde(rename = "errorMessage", default)] + pub error_message: Option, +} + +impl Settlement { + /// Decode the settlement from a base64-encoded JSON `PAYMENT-RESPONSE` header. + pub fn parse(header: &str) -> Result { + let decoded = BASE64 + .decode(header.trim()) + .map_err(|_| Error::MalformedHeader { + header: PAYMENT_RESPONSE_HEADER, + })?; + serde_json::from_slice(&decoded).map_err(|_| Error::MalformedHeader { + header: PAYMENT_RESPONSE_HEADER, + }) + } +} + +/// Why the server rejected a replayed payment: the facilitator's settlement +/// failure from `PAYMENT-RESPONSE`, else the verification failure carried in a +/// fresh `PAYMENT-REQUIRED` declaration. +#[must_use] +pub fn rejection_reason( + payment_response: Option<&str>, + payment_required: Option<&str>, +) -> Option { + let settlement = payment_response + .and_then(|header| Settlement::parse(header).ok()) + .and_then(|s| s.error_message.or(s.error_reason)); + settlement.or_else(|| { + payment_required + .filter(|header| !header.is_empty()) + .and_then(|header| Challenge::parse(Some(header), b"").ok()) + .and_then(|c| c.error) + }) +} + +/// Encode a payment proof payload as a base64-encoded JSON `PAYMENT-SIGNATURE` +/// header value. +pub fn encode_payment_signature(payload: &Value) -> Result { + Ok(BASE64.encode(serde_json::to_vec(payload)?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn sample_challenge() -> Value { + json!({ + "x402Version": 2, + "accepts": [{ + "scheme": "exact", + "network": "stellar:testnet", + "asset": "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + "payTo": "GAREAZZQWHOCBJS236KIE3AWYBVFLSBK7E5UW3ICI3TCRWQKT5LNLCEZ", + "amount": "10000000", + "maxTimeoutSeconds": 60, + "extra": { "areFeesSponsored": true } + }], + "resource": { "url": "https://example.test/weather" } + }) + } + + #[test] + fn parses_challenge_from_base64_header() { + let header = BASE64.encode(serde_json::to_vec(&sample_challenge()).unwrap()); + let challenge = Challenge::parse(Some(&header), b"").unwrap(); + assert_eq!(challenge.x402_version, 2); + assert_eq!(challenge.accepts.len(), 1); + assert!(challenge.resource.is_some()); + } + + #[test] + fn parses_challenge_from_body_when_no_header() { + let body = serde_json::to_vec(&sample_challenge()).unwrap(); + let challenge = Challenge::parse(None, &body).unwrap(); + assert_eq!(challenge.x402_version, 2); + } + + #[test] + fn malformed_header_is_rejected() { + let err = Challenge::parse(Some("not base64!!"), b"").unwrap_err(); + assert_eq!(err.error_type(), "malformed_header"); + } + + #[test] + fn selects_matching_network_and_reads_fields() { + let challenge = + Challenge::parse(None, &serde_json::to_vec(&sample_challenge()).unwrap()).unwrap(); + let (raw, req) = challenge.select_stellar(TESTNET_PASSPHRASE).unwrap(); + assert_eq!(req.scheme, "exact"); + assert_eq!(req.amount_raw().unwrap(), 10_000_000); + assert_eq!(req.max_timeout_seconds, 60); + assert!(req.fees_sponsored()); + // The raw option is preserved verbatim for echoing in the proof. + assert_eq!(raw["payTo"], req.pay_to); + } + + #[test] + fn local_network_is_recognized() { + assert_eq!( + passphrase_for_caip2("stellar:local"), + Some("Standalone Network ; February 2017") + ); + } + + #[test] + fn no_option_for_configured_network_errors() { + let challenge = + Challenge::parse(None, &serde_json::to_vec(&sample_challenge()).unwrap()).unwrap(); + let err = challenge.select_stellar(PUBNET_PASSPHRASE).unwrap_err(); + assert_eq!(err.error_type(), "no_matching_requirement"); + } + + #[test] + fn unsponsored_fees_are_rejected() { + let mut value = sample_challenge(); + value["accepts"][0]["extra"]["areFeesSponsored"] = json!(false); + let challenge = Challenge::parse(None, &serde_json::to_vec(&value).unwrap()).unwrap(); + let err = challenge.select_stellar(TESTNET_PASSPHRASE).unwrap_err(); + assert_eq!(err.error_type(), "fees_not_sponsored"); + } + + #[test] + fn later_supported_option_is_selected_over_earlier_unsupported_ones() { + let mut value = sample_challenge(); + let valid = value["accepts"][0].clone(); + let mut unsponsored = valid.clone(); + unsponsored["extra"]["areFeesSponsored"] = json!(false); + let mut other_scheme = valid.clone(); + other_scheme["scheme"] = json!("upto"); + value["accepts"] = json!([unsponsored, other_scheme, valid]); + let challenge = Challenge::parse(None, &serde_json::to_vec(&value).unwrap()).unwrap(); + let (raw, req) = challenge.select_stellar(TESTNET_PASSPHRASE).unwrap(); + assert_eq!(raw, valid); + assert!(req.fees_sponsored()); + } + + #[test] + fn legacy_max_amount_required_is_honored() { + let mut value = sample_challenge(); + let accept = &mut value["accepts"][0]; + accept["amount"] = Value::Null; + accept.as_object_mut().unwrap().remove("amount"); + accept["maxAmountRequired"] = json!("42"); + let challenge = Challenge::parse(None, &serde_json::to_vec(&value).unwrap()).unwrap(); + let (_, req) = challenge.select_stellar(TESTNET_PASSPHRASE).unwrap(); + assert_eq!(req.amount_raw().unwrap(), 42); + } + + #[test] + fn settlement_round_trips_through_header() { + let header = BASE64.encode( + serde_json::to_vec(&json!({ "transaction": "abc123", "network": "stellar:testnet" })) + .unwrap(), + ); + let settlement = Settlement::parse(&header).unwrap(); + assert_eq!(settlement.transaction.as_deref(), Some("abc123")); + } + + fn encode(value: &Value) -> String { + BASE64.encode(serde_json::to_vec(value).unwrap()) + } + + #[test] + fn rejection_reason_reads_verification_error_from_payment_required() { + let mut value = sample_challenge(); + value["error"] = json!("invalid_exact_stellar_payload_malformed"); + assert_eq!( + rejection_reason(None, Some(&encode(&value))).as_deref(), + Some("invalid_exact_stellar_payload_malformed") + ); + } + + #[test] + fn rejection_reason_prefers_settlement_failure_message() { + let settlement = json!({ + "success": false, + "errorReason": "transaction_failed", + "errorMessage": "transaction failed on-chain", + }); + let mut challenge = sample_challenge(); + challenge["error"] = json!("other"); + assert_eq!( + rejection_reason(Some(&encode(&settlement)), Some(&encode(&challenge))).as_deref(), + Some("transaction failed on-chain") + ); + } + + #[test] + fn rejection_reason_falls_back_to_settlement_reason() { + let settlement = json!({ "success": false, "errorReason": "transaction_failed" }); + assert_eq!( + rejection_reason(Some(&encode(&settlement)), None).as_deref(), + Some("transaction_failed") + ); + } + + #[test] + fn rejection_reason_is_none_without_headers() { + assert_eq!(rejection_reason(None, None), None); + assert_eq!(rejection_reason(Some("not base64!!"), Some("")), None); + } + + #[test] + fn payment_signature_encodes_to_decodable_base64_json() { + let payload = json!({ "x402Version": 2, "payload": { "transaction": "AAAA" } }); + let encoded = encode_payment_signature(&payload).unwrap(); + let decoded: Value = serde_json::from_slice(&BASE64.decode(&encoded).unwrap()).unwrap(); + assert_eq!(decoded, payload); + } +} diff --git a/cmd/soroban-cli/src/commands/pay/http.rs b/cmd/soroban-cli/src/commands/pay/http.rs new file mode 100644 index 0000000000..a90d83a2d4 --- /dev/null +++ b/cmd/soroban-cli/src/commands/pay/http.rs @@ -0,0 +1,91 @@ +//! Minimal HTTP client for the x402 request/replay loop. + +use reqwest::header::{HeaderMap, CONTENT_TYPE}; + +use super::challenge::PAYMENT_SIGNATURE_HEADER; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("could not reach `{url}`: {source}")] + Request { + url: String, + #[source] + source: reqwest::Error, + }, + + #[error("failed to build the HTTP client: {0}")] + Client(reqwest::Error), +} + +impl Error { + /// Machine-readable discriminator for the JSON error envelope's `type` field. + #[must_use] + pub fn error_type(&self) -> &'static str { + match self { + Error::Request { .. } => "request_failed", + Error::Client(_) => "http_client", + } + } +} + +/// A fetched HTTP response, with the body read into memory. +pub struct Response { + pub status: u16, + headers: HeaderMap, + pub body: Vec, +} + +impl Response { + /// Read a response header by (case-insensitive) name, if present and valid + /// UTF-8. + #[must_use] + pub fn header(&self, name: &str) -> Option { + self.headers + .get(name) + .and_then(|value| value.to_str().ok()) + .map(str::to_string) + } + + /// The response's `Content-Type`, if any. + #[must_use] + pub fn content_type(&self) -> Option { + self.headers + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(str::to_string) + } + + /// The response body as a lossy UTF-8 string. + #[must_use] + pub fn body_string(&self) -> String { + String::from_utf8_lossy(&self.body).to_string() + } +} + +/// `GET url`, optionally attaching the x402 `PAYMENT-SIGNATURE` proof header. +pub async fn get(url: &str, payment_signature: Option<&str>) -> Result { + let client = reqwest::Client::builder().build().map_err(Error::Client)?; + let mut request = client.get(url); + if let Some(signature) = payment_signature { + request = request.header(PAYMENT_SIGNATURE_HEADER, signature); + } + let response = request.send().await.map_err(|source| Error::Request { + url: url.to_string(), + source, + })?; + let status = response.status().as_u16(); + let headers = response.headers().clone(); + let body = response + .bytes() + .await + .map_err(|source| Error::Request { + url: url.to_string(), + source, + })? + .to_vec(); + Ok(Response { + status, + headers, + body, + }) +} diff --git a/cmd/soroban-cli/src/commands/pay/mod.rs b/cmd/soroban-cli/src/commands/pay/mod.rs new file mode 100644 index 0000000000..3a2bdbb655 --- /dev/null +++ b/cmd/soroban-cli/src/commands/pay/mod.rs @@ -0,0 +1,524 @@ +//! `stellar checkout ` — the x402 / MPP payment client. +//! +//! Fetches an x402-protected resource: on a `402 Payment Required` challenge it +//! builds and authorization-signs a SEP-41 token transfer through the +//! `contract invoke` pipeline (so the payment is previewable via simulation), +//! replays the signed proof to fetch the paid resource, and returns both the +//! settlement receipt and the service response. The client signs only the +//! authorization entry; the facilitator re-sources the transaction, signs the +//! envelope, pays the fees, and submits. + +pub mod cap; +pub mod challenge; +pub mod http; +pub mod payment; + +use clap::Parser; +use serde_json::Value; + +use crate::{ + commands::{global, token::args::OutputFormat}, + config::{self, locator, network, sign_with, UnresolvedMuxedAccount}, + output::Output, +}; + +use cap::MaxAmount; +use challenge::{Challenge, Settlement}; + +/// HTTP status returned by an x402 server to demand payment. +const PAYMENT_REQUIRED_STATUS: u16 = 402; + +#[derive(Debug, Parser, Clone)] +#[group(skip)] +pub struct Cmd { + /// The x402-protected resource to fetch and pay for. + pub url: String, + + /// Account that pays for the resource. Signs and authorizes the on-chain + /// payment, so it must be an identity or key you control. + #[arg( + long = "source-account", + visible_alias = "source", + env = "STELLAR_ACCOUNT", + hide_env_values = true + )] + pub source_account: UnresolvedMuxedAccount, + + /// Maximum amount to pay, in the asset's display units (e.g. `1` = 1.0 USDC, + /// roughly $1). Aborts before signing if the challenge asks for more. Set to + /// `none` to disable the cap. + #[arg( + long, + env = "STELLAR_CHECKOUT_MAX_AMOUNT", + default_value = "1", + value_parser = parse_max_amount + )] + pub max_amount: MaxAmount, + + /// Build and authorization-sign the payment and print the proof, without + /// fetching the paid resource. + #[arg(long)] + pub build_only: bool, + + /// Format of the output. + #[arg(long, default_value = "text")] + pub output: OutputFormat, + + #[command(flatten)] + pub network: network::Args, + + #[command(flatten)] + pub locator: locator::Args, + + #[command(flatten)] + pub sign_with: sign_with::Args, +} + +fn parse_max_amount(value: &str) -> Result { + value.parse() +} + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error(transparent)] + Config(#[from] config::Error), + + #[error(transparent)] + Network(#[from] network::Error), + + #[error(transparent)] + Http(#[from] http::Error), + + #[error(transparent)] + Challenge(#[from] challenge::Error), + + #[error(transparent)] + Cap(#[from] cap::Error), + + #[error(transparent)] + Payment(#[from] payment::Error), + + #[error(transparent)] + Serde(#[from] serde_json::Error), + + #[error("failed to write the resource to stdout: {0}")] + Io(#[from] std::io::Error), + + #[error("the server returned status {status} for `{url}`:\n{body}")] + UnexpectedStatus { + status: u16, + url: String, + body: String, + }, + + #[error("the payment was rejected (status {status}): {reason}")] + PaymentRejected { status: u16, reason: String }, +} + +impl Error { + /// Machine-readable discriminator for the JSON error envelope's `type` field. + #[must_use] + pub fn error_type(&self) -> &'static str { + match self { + Error::Config(_) => "config", + Error::Network(_) => "network", + Error::Http(e) => e.error_type(), + Error::Challenge(e) => e.error_type(), + Error::Cap(e) => e.error_type(), + Error::Payment(e) => e.error_type(), + Error::Serde(_) => "internal", + Error::Io(_) => "io", + Error::UnexpectedStatus { .. } => "unexpected_status", + Error::PaymentRejected { .. } => "payment_rejected", + } + } +} + +/// The machine-readable receipt of a checkout. +#[derive(Debug, serde::Serialize)] +struct Receipt { + /// Hash of the settled transaction, as reported by the facilitator. `None` + /// when the facilitator didn't report one. + tx_hash: Option, + /// Block-explorer link for `tx_hash`, when the network is a known public one. + #[serde(skip_serializing_if = "Option::is_none")] + explorer_url: Option, + /// The CAIP-2 network the payment settled on (e.g. `stellar:testnet`). + network: String, + /// The paid resource that was fetched after settlement. + resource: ResourceResponse, +} + +/// The service's response to the paid (replayed) request. +#[derive(Debug, serde::Serialize)] +struct ResourceResponse { + status: u16, + #[serde(skip_serializing_if = "Option::is_none")] + content_type: Option, + /// The body, parsed as JSON when possible, otherwise the raw text. + body: Value, +} + +/// The proof emitted by `--build-only`: the encoded header plus the decoded +/// payload it carries. +#[derive(Debug, serde::Serialize)] +struct Proof { + payment_signature: String, + payload: Value, +} + +impl Cmd { + fn config(&self) -> config::Args { + config::Args { + network: self.network.clone(), + source_account: self.source_account.clone(), + locator: self.locator.clone(), + sign_with: self.sign_with.clone(), + fee: None, + inclusion_fee: None, + } + } + + pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> { + let output = Output::new(self.output.into(), global_args.quiet); + // In JSON mode the underlying invoke pipeline's human-readable status + // logging (stderr) would still fire; run it quietly so machine consumers + // get clean output without needing `--quiet`. + let quiet = global_args.quiet || output.is_json(); + let no_cache = global_args.no_cache; + let config = self.config(); + let network = config.get_network()?; + + // 1. Initial request. A non-402 success means the resource is free. + let initial = http::get(&self.url, None).await?; + if initial.status != PAYMENT_REQUIRED_STATUS { + return self.handle_unpaid(&output, initial); + } + + output.readable(|print| print.infoln("Received 402 Payment Required; building payment…")); + + // 2. Parse the challenge and select the option for our network. + let challenge = Challenge::parse( + initial + .header(challenge::PAYMENT_REQUIRED_HEADER) + .as_deref(), + &initial.body, + )?; + let (accepted, req) = challenge.select_stellar(&network.network_passphrase)?; + let asset = payment::parse_asset(&req.asset)?; + let amount = req.amount_raw()?; + + // 3. Enforce the spend cap (default 1.0 of the asset ≈ $1) before signing. + if let MaxAmount::Limit(_) = self.max_amount { + let decimals = payment::read_decimals(&config, asset, quiet, no_cache).await?; + self.max_amount.enforce(amount, decimals)?; + } + + // 4. Build + simulate + authorization-sign the transfer into a proof. + let payload = payment::build_proof( + &config, + asset, + &req.pay_to, + amount, + req.max_timeout_seconds, + challenge.x402_version, + &accepted, + challenge.resource.as_ref(), + quiet, + no_cache, + ) + .await?; + let payment_signature = challenge::encode_payment_signature(&payload)?; + + // 5. `--build-only`: emit the proof and stop before paying. + if self.build_only { + return emit_proof(&output, payment_signature, payload); + } + + // 6. Replay the request with the proof to settle and fetch the resource. + output.readable(|print| print.globeln("Submitting payment…")); + let paid = http::get(&self.url, Some(&payment_signature)).await?; + if !(200..300).contains(&paid.status) { + let reason = challenge::rejection_reason( + paid.header(challenge::PAYMENT_RESPONSE_HEADER).as_deref(), + paid.header(challenge::PAYMENT_REQUIRED_HEADER).as_deref(), + ) + .unwrap_or_else(|| paid.body_string()); + return Err(Error::PaymentRejected { + status: paid.status, + reason, + }); + } + + // 7. Decode the settlement and build the receipt. + let settlement = paid + .header(challenge::PAYMENT_RESPONSE_HEADER) + .map(|header| Settlement::parse(&header)) + .transpose()?; + let tx_hash = settlement.and_then(|s| s.transaction); + let explorer_url = tx_hash + .as_deref() + .and_then(|hash| crate::utils::explorer_url_for_transaction(&network, hash)); + + let receipt = Receipt { + tx_hash, + explorer_url, + network: req.network, + resource: resource_response(&paid), + }; + + output.readable(|print| { + if let Some(hash) = &receipt.tx_hash { + print.checkln(format!("Payment settled: {hash}")); + } + if let Some(url) = &receipt.explorer_url { + print.linkln(url); + } + }); + + // Human-readable output writes the fetched resource body to stdout so it + // stays pipeable; JSON mode writes the full receipt. + if !output.is_json() { + write_body(&mut std::io::stdout().lock(), &paid.body)?; + } + output.json_value(&receipt)?; + + Ok(()) + } + + /// Handle a response that didn't demand payment: a success is the free + /// resource; anything else is an error. + fn handle_unpaid(&self, output: &Output, response: http::Response) -> Result<(), Error> { + if !(200..300).contains(&response.status) { + return Err(Error::UnexpectedStatus { + status: response.status, + url: self.url.clone(), + body: response.body_string(), + }); + } + output.readable(|print| print.infoln("No payment required.")); + if !output.is_json() { + write_body(&mut std::io::stdout().lock(), &response.body)?; + } + output.json_value(&resource_response(&response))?; + Ok(()) + } +} + +/// Emit the `--build-only` proof: the header value on stdout (text mode) or the +/// full proof object (JSON mode). +fn emit_proof(output: &Output, payment_signature: String, payload: Value) -> Result<(), Error> { + output.readable(|print| { + print.infoln("Built payment proof (not submitted):"); + }); + if !output.is_json() { + println!("{payment_signature}"); + } + output.json_value(&Proof { + payment_signature, + payload, + })?; + Ok(()) +} + +/// Write a fetched resource body to `out` byte-for-byte, so binary resources +/// survive redirection to a file. +fn write_body(out: &mut impl std::io::Write, body: &[u8]) -> std::io::Result<()> { + out.write_all(body)?; + out.flush() +} + +/// Decode an HTTP response body into the receipt's resource field, preferring a +/// parsed JSON value and falling back to the raw text. +fn resource_response(response: &http::Response) -> ResourceResponse { + let body = serde_json::from_slice::(&response.body) + .unwrap_or_else(|_| Value::String(response.body_string())); + ResourceResponse { + status: response.status, + content_type: response.content_type(), + body, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const TESTNET_PASSPHRASE: &str = "Test SDF Network ; September 2015"; + const PUBNET_PASSPHRASE: &str = "Public Global Stellar Network ; September 2015"; + + fn cmd(url: String, network_passphrase: &str, max_amount: MaxAmount) -> Cmd { + Cmd { + url, + source_account: UnresolvedMuxedAccount::default(), + max_amount, + build_only: false, + output: OutputFormat::Text, + network: network::Args { + // A reachable RPC URL isn't needed: these tests exercise the + // HTTP challenge loop only, which errors before the on-chain leg. + rpc_url: Some("http://127.0.0.1:1".to_string()), + rpc_headers: Vec::new(), + network_passphrase: Some(network_passphrase.to_string()), + network: None, + }, + locator: locator::Args::default(), + sign_with: sign_with::Args::default(), + } + } + + fn global() -> global::Args { + global::Args { + locator: locator::Args::default(), + filter_logs: Vec::new(), + quiet: true, + verbose: false, + very_verbose: false, + no_cache: true, + } + } + + fn testnet_challenge() -> Value { + json!({ + "x402Version": 2, + "accepts": [{ + "scheme": "exact", + "network": "stellar:testnet", + "asset": "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + "payTo": "GAREAZZQWHOCBJS236KIE3AWYBVFLSBK7E5UW3ICI3TCRWQKT5LNLCEZ", + "amount": "10000000", + "maxTimeoutSeconds": 60, + "extra": { "areFeesSponsored": true } + }] + }) + } + + #[test] + fn body_is_written_byte_for_byte() { + let body = [0x89, b'P', b'N', b'G', 0xff, 0x00, b'\n', 0xfe]; + let mut out = Vec::new(); + write_body(&mut out, &body).unwrap(); + assert_eq!(out, body); + } + + #[tokio::test] + async fn free_resource_is_returned_without_payment() { + let mut server = mockito::Server::new_async().await; + let mock = server + .mock("GET", "/free") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"weather":"sunny"}"#) + .create_async() + .await; + + let cmd = cmd( + format!("{}/free", server.url()), + TESTNET_PASSPHRASE, + MaxAmount::Unlimited, + ); + assert!(cmd.run(&global()).await.is_ok()); + mock.assert_async().await; + } + + #[tokio::test] + async fn non_payment_error_status_surfaces_unexpected_status() { + let mut server = mockito::Server::new_async().await; + let _mock = server + .mock("GET", "/boom") + .with_status(500) + .with_body("internal error") + .create_async() + .await; + + let cmd = cmd( + format!("{}/boom", server.url()), + TESTNET_PASSPHRASE, + MaxAmount::Unlimited, + ); + let err = cmd.run(&global()).await.unwrap_err(); + assert_eq!(err.error_type(), "unexpected_status"); + } + + #[tokio::test] + async fn challenge_for_a_different_network_is_rejected() { + let mut server = mockito::Server::new_async().await; + let _mock = server + .mock("GET", "/pay") + .with_status(402) + .with_body(serde_json::to_string(&testnet_challenge()).unwrap()) + .create_async() + .await; + + // The challenge only offers testnet, but we're configured for pubnet. + let cmd = cmd( + format!("{}/pay", server.url()), + PUBNET_PASSPHRASE, + MaxAmount::Unlimited, + ); + let err = cmd.run(&global()).await.unwrap_err(); + assert_eq!(err.error_type(), "no_matching_requirement"); + } + + #[tokio::test] + async fn rpc_on_a_different_network_is_rejected_before_signing() { + let mut server = mockito::Server::new_async().await; + let _challenge = server + .mock("GET", "/pay") + .with_status(402) + .with_body(serde_json::to_string(&testnet_challenge()).unwrap()) + .create_async() + .await; + let _latest_ledger = server + .mock("POST", "/rpc") + .match_body(mockito::Matcher::Regex("getLatestLedger".into())) + .with_body( + r#"{"jsonrpc":"2.0","id":0,"result":{"id":"x","protocolVersion":23,"sequence":10}}"#, + ) + .create_async() + .await; + let _network = server + .mock("POST", "/rpc") + .match_body(mockito::Matcher::Regex("getNetwork".into())) + .with_body(format!( + r#"{{"jsonrpc":"2.0","id":0,"result":{{"passphrase":"{PUBNET_PASSPHRASE}","protocolVersion":23}}}}"# + )) + .create_async() + .await; + + let mut cmd = cmd( + format!("{}/pay", server.url()), + TESTNET_PASSPHRASE, + MaxAmount::Unlimited, + ); + cmd.network.rpc_url = Some(format!("{}/rpc", server.url())); + cmd.source_account = "GAREAZZQWHOCBJS236KIE3AWYBVFLSBK7E5UW3ICI3TCRWQKT5LNLCEZ" + .parse() + .unwrap(); + let err = cmd.run(&global()).await.unwrap_err(); + assert!( + err.to_string().contains(PUBNET_PASSPHRASE), + "unexpected error: {err}" + ); + } + + #[tokio::test] + async fn malformed_challenge_is_rejected() { + let mut server = mockito::Server::new_async().await; + let _mock = server + .mock("GET", "/pay") + .with_status(402) + .with_body("this is not json") + .create_async() + .await; + + let cmd = cmd( + format!("{}/pay", server.url()), + TESTNET_PASSPHRASE, + MaxAmount::Unlimited, + ); + let err = cmd.run(&global()).await.unwrap_err(); + assert_eq!(err.error_type(), "missing_challenge"); + } +} diff --git a/cmd/soroban-cli/src/commands/pay/payment.rs b/cmd/soroban-cli/src/commands/pay/payment.rs new file mode 100644 index 0000000000..cc21a09602 --- /dev/null +++ b/cmd/soroban-cli/src/commands/pay/payment.rs @@ -0,0 +1,504 @@ +//! The on-chain leg of an x402 payment. +//! +//! Drives a SEP-41 `transfer(from, to, amount)` through the `contract invoke` +//! pipeline (build → simulate → authorization-sign) to produce the signed, +//! unsubmitted transaction the facilitator settles, then packages it into the +//! x402 payment proof. Reads the asset's `decimals` through the same pipeline so +//! the spend cap can be enforced in display units. + +use serde_json::{json, Value}; + +use crate::{ + commands::{contract::invoke, global, token::args::format_decimal}, + config::{self, UnresolvedMuxedAccount}, + utils::{contract_id_from_str, XDR_DEPTH_LIMIT}, + xdr::{ + Limits, MuxedAccount, Preconditions, TimeBounds, TimePoint, Transaction, + TransactionEnvelope, TransactionV1Envelope, VecM, WriteXdr, + }, +}; + +/// Estimated ledger close time in seconds, used to convert the challenge's +/// `maxTimeoutSeconds` into an authorization-signature expiration ledger. Matches +/// the x402 reference client's default when a live estimate isn't available. +const ESTIMATED_LEDGER_CLOSE_SECONDS: u64 = 5; + +/// Stellar Asset Contract error raised when a transfer would leave a balance +/// outside its allowed range (e.g. below zero). +const SAC_BALANCE_OUT_OF_RANGE: u32 = 10; +/// Stellar Asset Contract error raised when an account has no trustline for the +/// asset. +const SAC_TRUSTLINE_MISSING: u32 = 13; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error(transparent)] + Invoke(#[from] invoke::Error), + + #[error(transparent)] + Config(#[from] config::Error), + + #[error(transparent)] + Network(#[from] config::network::Error), + + #[error(transparent)] + Rpc(#[from] soroban_rpc::Error), + + #[error(transparent)] + Xdr(#[from] crate::xdr::Error), + + #[error("the asset at {asset} did not return a valid decimals value (`{value}`)")] + InvalidDecimals { asset: String, value: String }, + + #[error("the payment option's asset `{0}` is not a valid contract id")] + InvalidAsset(String), + + #[error("muxed (M…) accounts are not yet supported as the paying account")] + MuxedNotSupported, + + #[error( + "`{account}` has no trustline for `{asset}`; add one with \ + `stellar tx new change-trust --source {account} --line {asset}`" + )] + PayerMissingTrustline { account: String, asset: String }, + + #[error("`{account}` has {balance} `{asset}`, but the payment requires {required}")] + InsufficientBalance { + account: String, + asset: String, + balance: String, + required: String, + }, + + #[error( + "the server's pay-to account `{account}` has no trustline for `{asset}`, \ + so it can't receive the payment" + )] + RecipientMissingTrustline { account: String, asset: String }, +} + +impl Error { + /// Machine-readable discriminator for the JSON error envelope's `type` field. + #[must_use] + pub fn error_type(&self) -> &'static str { + match self { + Error::Invoke(_) => "invoke", + Error::Config(_) => "config", + Error::Network(_) => "network", + Error::Rpc(_) => "rpc", + Error::Xdr(_) => "internal", + Error::InvalidDecimals { .. } => "invalid_decimals", + Error::InvalidAsset(_) => "invalid_asset", + Error::MuxedNotSupported => "unsupported", + Error::PayerMissingTrustline { .. } => "payer_missing_trustline", + Error::InsufficientBalance { .. } => "insufficient_balance", + Error::RecipientMissingTrustline { .. } => "recipient_missing_trustline", + } + } +} + +/// The payer's balance of the asset, as probed after a failed transfer. +#[derive(Debug, Clone, Copy)] +enum PayerBalance { + MissingTrustline, + Amount(i128), + Unknown, +} + +/// A transfer failure that can be attributed to a specific account. +#[derive(Debug, PartialEq, Eq)] +enum TransferFailure { + PayerMissingTrustline, + InsufficientBalance(i128), + RecipientMissingTrustline, +} + +/// The Stellar Asset Contract error code carried by a failed simulation, if it's +/// one that points at a trustline or balance problem. +fn sac_error_code(message: &str) -> Option { + [SAC_BALANCE_OUT_OF_RANGE, SAC_TRUSTLINE_MISSING] + .into_iter() + .find(|code| message.contains(&format!("Error(Contract, #{code})"))) +} + +/// Attribute a failed transfer (SAC error `code`) using the payer's probed +/// balance. `None` when the cause can't be pinned on an account. +fn classify_transfer_failure( + code: u32, + payer: PayerBalance, + amount: i128, +) -> Option { + match payer { + PayerBalance::MissingTrustline => Some(TransferFailure::PayerMissingTrustline), + PayerBalance::Amount(balance) if balance < amount => { + Some(TransferFailure::InsufficientBalance(balance)) + } + PayerBalance::Amount(_) if code == SAC_TRUSTLINE_MISSING => { + Some(TransferFailure::RecipientMissingTrustline) + } + _ => None, + } +} + +/// Number of ledgers to add to the current ledger so the authorization signature +/// stays valid for at least `max_timeout_seconds`. +fn expiry_ledgers(max_timeout_seconds: u64) -> u32 { + // Round up so a short timeout still yields at least one ledger of validity. + let ledgers = max_timeout_seconds + .max(1) + .div_ceil(ESTIMATED_LEDGER_CLOSE_SECONDS) + .max(1); + u32::try_from(ledgers).unwrap_or(u32::MAX) +} + +/// Build the base `contract invoke` command for a SEP-41 call on `asset`, +/// supplying the arguments by position so the call works regardless of what the +/// deployed token names its parameters. +fn invoke_cmd( + config: &config::Args, + asset: stellar_strkey::Contract, + function: &str, + args: Vec, + send: invoke::Send, +) -> invoke::Cmd { + invoke::Cmd { + contract_id: config::UnresolvedContract::Resolved(asset), + invocation: Some(invoke::PositionalInvocation { + function: function.to_string(), + args, + }), + config: config.clone(), + send, + ..Default::default() + } +} + +/// The paying account as an argument string that resolves both to an on-chain +/// address and to a signing key: the original alias/secret when given that way, +/// otherwise the resolved `G…` address (matched to a stored identity by public +/// key). Rejects muxed accounts, which can't yet source or sign. +fn paying_account_arg(config: &config::Args) -> Result { + if matches!(config.source_account()?, MuxedAccount::MuxedEd25519(_)) { + return Err(Error::MuxedNotSupported); + } + Ok(match &config.source_account { + UnresolvedMuxedAccount::AliasOrSecret(s) => s.clone(), + UnresolvedMuxedAccount::Resolved(_) => config.source_account()?.to_string(), + }) +} + +/// Call a read-only token `function` and return its output with any JSON string +/// quoting removed. +async fn read( + config: &config::Args, + asset: stellar_strkey::Contract, + function: &str, + args: Vec, + quiet: bool, + no_cache: bool, +) -> Result { + let cmd = invoke_cmd(config, asset, function, args, invoke::Send::No); + let global_args = global::Args { + locator: config.locator.clone(), + filter_logs: Vec::default(), + quiet, + verbose: false, + very_verbose: false, + no_cache, + }; + let output = cmd + .invoke(&global_args) + .await? + .into_result() + .unwrap_or_default(); + Ok(output.trim().trim_matches('"').to_string()) +} + +/// Read the asset's `decimals` through a read-only invocation, for rendering the +/// spend cap in display units. +pub async fn read_decimals( + config: &config::Args, + asset: stellar_strkey::Contract, + quiet: bool, + no_cache: bool, +) -> Result { + let output = read(config, asset, "decimals", vec![], quiet, no_cache).await?; + output + .trim() + .parse::() + .map_err(|_| Error::InvalidDecimals { + asset: format!("{asset}"), + value: output, + }) +} + +/// Build, simulate, and authorization-sign the `transfer` and package it into the +/// x402 payment proof. The chosen requirement (`accepted`) and `resource` are +/// echoed back verbatim as the server sent them. +#[allow(clippy::too_many_arguments)] +pub async fn build_proof( + config: &config::Args, + asset: stellar_strkey::Contract, + pay_to: &str, + amount: i128, + max_timeout_seconds: u64, + x402_version: u32, + accepted: &Value, + resource: Option<&Value>, + quiet: bool, + no_cache: bool, +) -> Result { + let network = config.get_network()?; + let client = network.rpc_client()?; + let latest_ledger = client.get_latest_ledger().await?.sequence; + let expiration_ledger = latest_ledger.saturating_add(expiry_ledgers(max_timeout_seconds)); + + let from = paying_account_arg(config)?; + let payer = config.source_account()?.to_string(); + let cmd = invoke_cmd( + config, + asset, + "transfer", + vec![from, pay_to.to_string(), amount.to_string()], + invoke::Send::Yes, + ); + + let tx = match cmd + .build_payment_authorization(config, expiration_ledger, quiet, no_cache) + .await + { + Ok(tx) => tx, + Err(err) => { + return Err(explain_transfer_failure( + config, asset, &payer, pay_to, amount, err, no_cache, + ) + .await) + } + }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let transaction = encode_transaction(with_time_bounds(tx, now, max_timeout_seconds))?; + + let mut payload = json!({ + "x402Version": x402_version, + "payload": { "transaction": transaction }, + "accepted": accepted, + }); + if let Some(resource) = resource { + payload["resource"] = resource.clone(); + } + Ok(payload) +} + +/// Turn a failed transfer simulation into an error naming the account at fault +/// when it's a trustline or balance problem, by probing the payer's balance. +/// Anything else is returned unchanged. +async fn explain_transfer_failure( + config: &config::Args, + asset: stellar_strkey::Contract, + payer: &str, + pay_to: &str, + amount: i128, + err: invoke::Error, + no_cache: bool, +) -> Error { + let Some(code) = sac_error_code(&err.to_string()) else { + return err.into(); + }; + let balance = match read( + config, + asset, + "balance", + vec![payer.to_string()], + true, + no_cache, + ) + .await + { + Ok(output) => output + .parse() + .map_or(PayerBalance::Unknown, PayerBalance::Amount), + Err(e) if sac_error_code(&e.to_string()) == Some(SAC_TRUSTLINE_MISSING) => { + PayerBalance::MissingTrustline + } + Err(_) => PayerBalance::Unknown, + }; + let Some(failure) = classify_transfer_failure(code, balance, amount) else { + return err.into(); + }; + let asset_name = read(config, asset, "name", vec![], true, no_cache) + .await + .unwrap_or_else(|_| format!("{asset}")); + match failure { + TransferFailure::PayerMissingTrustline => Error::PayerMissingTrustline { + account: payer.to_string(), + asset: asset_name, + }, + TransferFailure::RecipientMissingTrustline => Error::RecipientMissingTrustline { + account: pay_to.to_string(), + asset: asset_name, + }, + TransferFailure::InsufficientBalance(balance) => { + let decimals = read_decimals(config, asset, true, no_cache).await.ok(); + Error::InsufficientBalance { + account: payer.to_string(), + asset: asset_name, + balance: display_amount(balance, decimals), + required: display_amount(amount, decimals), + } + } + } +} + +/// Render a raw token amount in display units, or as the raw integer when the +/// asset's decimals are unknown. +fn display_amount(value: i128, decimals: Option) -> String { + decimals + .and_then(|d| format_decimal(value, d).ok()) + .unwrap_or_else(|| value.to_string()) +} + +/// Bound the transaction to expire `max_timeout_seconds` after `now`. +fn with_time_bounds(tx: Transaction, now: u64, max_timeout_seconds: u64) -> Transaction { + Transaction { + cond: Preconditions::Time(TimeBounds { + min_time: TimePoint(0), + max_time: TimePoint(now.saturating_add(max_timeout_seconds)), + }), + ..tx + } +} + +/// Encode the auth-signed transaction as the base64 XDR of an unsigned v1 +/// `TransactionEnvelope`, the form the facilitator parses. +fn encode_transaction(tx: Transaction) -> Result { + let envelope = TransactionEnvelope::Tx(TransactionV1Envelope { + tx, + signatures: VecM::default(), + }); + Ok(envelope.to_xdr_base64(Limits::depth(XDR_DEPTH_LIMIT))?) +} + +/// Parse an `asset` contract id string (`C…`) from the challenge. +pub fn parse_asset(asset: &str) -> Result { + contract_id_from_str(asset).map_err(|_| Error::InvalidAsset(asset.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expiry_ledgers_rounds_up_from_seconds() { + // 60s / 5s per ledger = 12 ledgers. + assert_eq!(expiry_ledgers(60), 12); + // 61s rounds up to 13. + assert_eq!(expiry_ledgers(61), 13); + // A sub-ledger timeout still yields at least one ledger. + assert_eq!(expiry_ledgers(1), 1); + assert_eq!(expiry_ledgers(0), 1); + } + + const MISSING_TRUSTLINE: &str = "transaction simulation failed: HostError: \ + Error(Contract, #13)\n\nEvent log (newest first):\n 0: [Diagnostic Event] ..."; + + #[test] + fn sac_error_code_detects_trustline_and_balance_errors() { + assert_eq!( + sac_error_code(MISSING_TRUSTLINE), + Some(SAC_TRUSTLINE_MISSING) + ); + assert_eq!( + sac_error_code("HostError: Error(Contract, #10)"), + Some(SAC_BALANCE_OUT_OF_RANGE) + ); + assert_eq!(sac_error_code("HostError: Error(Contract, #1)"), None); + assert_eq!(sac_error_code("HostError: Error(Contract, #130)"), None); + assert_eq!(sac_error_code("could not reach the RPC server"), None); + } + + #[test] + fn payer_without_trustline_is_blamed_first() { + for code in [SAC_TRUSTLINE_MISSING, SAC_BALANCE_OUT_OF_RANGE] { + assert_eq!( + classify_transfer_failure(code, PayerBalance::MissingTrustline, 100), + Some(TransferFailure::PayerMissingTrustline) + ); + } + } + + #[test] + fn payer_short_of_funds_is_insufficient_balance() { + assert_eq!( + classify_transfer_failure(SAC_BALANCE_OUT_OF_RANGE, PayerBalance::Amount(40), 100), + Some(TransferFailure::InsufficientBalance(40)) + ); + } + + #[test] + fn funded_payer_with_missing_trustline_blames_recipient() { + assert_eq!( + classify_transfer_failure(SAC_TRUSTLINE_MISSING, PayerBalance::Amount(100), 100), + Some(TransferFailure::RecipientMissingTrustline) + ); + } + + #[test] + fn unattributable_failures_are_left_alone() { + assert_eq!( + classify_transfer_failure(SAC_BALANCE_OUT_OF_RANGE, PayerBalance::Amount(100), 100), + None + ); + assert_eq!( + classify_transfer_failure(SAC_TRUSTLINE_MISSING, PayerBalance::Unknown, 100), + None + ); + } + + #[test] + fn encoded_transaction_is_an_unsigned_v1_envelope() { + use crate::xdr::{Memo, Preconditions, ReadXdr, SequenceNumber, TransactionExt, Uint256}; + + let tx = Transaction { + source_account: MuxedAccount::Ed25519(Uint256([0; 32])), + fee: 100, + seq_num: SequenceNumber(1), + cond: Preconditions::None, + memo: Memo::None, + operations: VecM::default(), + ext: TransactionExt::V0, + }; + let encoded = encode_transaction(tx.clone()).unwrap(); + let envelope = + TransactionEnvelope::from_xdr_base64(&encoded, Limits::depth(XDR_DEPTH_LIMIT)).unwrap(); + let TransactionEnvelope::Tx(v1) = envelope else { + panic!("expected a v1 envelope"); + }; + assert_eq!(v1.tx, tx); + assert!(v1.signatures.is_empty()); + } + + #[test] + fn transaction_is_time_bounded_by_the_challenge_timeout() { + use crate::xdr::{Memo, SequenceNumber, TransactionExt, Uint256}; + + let tx = Transaction { + source_account: MuxedAccount::Ed25519(Uint256([0; 32])), + fee: 100, + seq_num: SequenceNumber(1), + cond: Preconditions::None, + memo: Memo::None, + operations: VecM::default(), + ext: TransactionExt::V0, + }; + let bounded = with_time_bounds(tx, 1_000, 300); + assert_eq!( + bounded.cond, + Preconditions::Time(TimeBounds { + min_time: TimePoint(0), + max_time: TimePoint(1_300), + }) + ); + } +} diff --git a/cmd/soroban-cli/src/config/sign_with.rs b/cmd/soroban-cli/src/config/sign_with.rs index 6ea1bb560c..92c0453deb 100644 --- a/cmd/soroban-cli/src/config/sign_with.rs +++ b/cmd/soroban-cli/src/config/sign_with.rs @@ -32,6 +32,8 @@ pub enum Error { Xdr(#[from] xdr::Error), #[error(transparent)] Ledger(#[from] signer::ledger::Error), + #[error("--sign-with-lab can't sign authorization entries; use --sign-with-key or --sign-with-ledger")] + LabCannotSignAuthorization, } #[derive(Debug, clap::Args, Clone, Default)] @@ -76,6 +78,32 @@ pub struct Args { } impl Args { + /// The signer requested through the signing options for authorization + /// entries, or `None` when no signing option was given. + pub fn auth_signer( + &self, + locator: &locator::Args, + print: &Print, + ) -> Result, Error> { + if self.sign_with_lab { + return Err(Error::LabCannotSignAuthorization); + } + if self.sign_with_ledger { + return Ok(Some(Signer { + kind: SignerKind::Ledger(LedgerEntry { + hd_path: self.hd_path.unwrap_or_default(), + public_key: None, + }), + print: print.clone(), + })); + } + let Some(key_or_name) = self.sign_with_key.as_deref() else { + return Ok(None); + }; + let secret = locator.get_secret_key_with_hd_path(key_or_name, self.hd_path)?; + Ok(Some(secret.signer(self.hd_path, print.clone())?)) + } + // when a default_signer_account is provided, it will be used as the tx signer if the user does not specify a signer. The default signer should be the tx's source_account. pub async fn sign_tx_env( &self, @@ -115,3 +143,64 @@ impl Args { Ok(signer.sign_tx_env(tx, network).await?) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn secret_key() -> String { + format!( + "{}", + stellar_strkey::ed25519::PrivateKey([7; 32]).as_unredacted() + ) + } + + #[test] + fn auth_signer_is_none_without_signing_options() { + let signer = Args::default() + .auth_signer(&locator::Args::default(), &Print::new(true)) + .unwrap(); + assert!(signer.is_none()); + } + + #[test] + fn auth_signer_uses_sign_with_key() { + let args = Args { + sign_with_key: Some(secret_key()), + ..Default::default() + }; + let signer = args + .auth_signer(&locator::Args::default(), &Print::new(true)) + .unwrap() + .unwrap(); + let expected = ed25519_dalek::SigningKey::from_bytes(&[7; 32]).verifying_key(); + assert_eq!(signer.get_public_key().unwrap().0, expected.to_bytes()); + } + + #[test] + fn auth_signer_uses_sign_with_ledger() { + let args = Args { + sign_with_ledger: true, + hd_path: Some(3), + ..Default::default() + }; + let signer = args + .auth_signer(&locator::Args::default(), &Print::new(true)) + .unwrap() + .unwrap(); + assert!(matches!( + signer.kind, + SignerKind::Ledger(LedgerEntry { hd_path: 3, .. }) + )); + } + + #[test] + fn auth_signer_rejects_sign_with_lab() { + let args = Args { + sign_with_lab: true, + ..Default::default() + }; + let result = args.auth_signer(&locator::Args::default(), &Print::new(true)); + assert!(matches!(result, Err(Error::LabCannotSignAuthorization))); + } +} diff --git a/cmd/soroban-cli/src/env_vars.rs b/cmd/soroban-cli/src/env_vars.rs index c7418e89da..e95391bb60 100644 --- a/cmd/soroban-cli/src/env_vars.rs +++ b/cmd/soroban-cli/src/env_vars.rs @@ -6,6 +6,7 @@ pub fn unprefixed() -> Vec<&'static str> { "ACCOUNT", "ARCHIVE_URL", "AUTH_MODE", + "CHECKOUT_MAX_AMOUNT", "CONFIG_HOME", "CONTAINER_ENGINE", "CONTRACT_ID", @@ -32,6 +33,7 @@ pub fn unprefixed() -> Vec<&'static str> { /// Unprefixed names of env vars that are safe to display in plain text. const VISIBLE: &[&str] = &[ "AUTH_MODE", + "CHECKOUT_MAX_AMOUNT", "CONFIG_HOME", "CONTAINER_ENGINE", "CONTRACT_ID", diff --git a/cmd/soroban-cli/src/signer/validation.rs b/cmd/soroban-cli/src/signer/validation.rs index 98e55a54a9..8c57dbe2c6 100644 --- a/cmd/soroban-cli/src/signer/validation.rs +++ b/cmd/soroban-cli/src/signer/validation.rs @@ -1,4 +1,7 @@ -use crate::xdr::{HostFunction, SorobanAuthorizedFunction, SorobanAuthorizedInvocation}; +use crate::xdr::{ + HostFunction, SorobanAuthorizationEntry, SorobanAuthorizedFunction, + SorobanAuthorizedInvocation, SorobanCredentials, +}; #[derive(thiserror::Error, Debug)] pub enum Error { @@ -97,6 +100,32 @@ pub fn classify_auth_invocation( } } +/// Why a payment's authorization can't be signed as-is: a payment must authorize +/// exactly the transaction's own call, by a single address, and nothing nested +/// beneath it. Returns `None` when the authorization is safe to sign. +#[must_use] +pub fn payment_authorization_violation( + host_fn: &HostFunction, + auth: &[SorobanAuthorizationEntry], +) -> Option<&'static str> { + let [entry] = auth else { + return Some("it must require exactly one authorization"); + }; + if !matches!( + entry.credentials, + SorobanCredentials::Address(_) | SorobanCredentials::AddressV2(_) + ) { + return Some("it must be authorized by the paying address"); + } + if classify_auth_invocation(host_fn, &entry.root_invocation) != AuthStyle::Strict { + return Some("it authorizes a call other than the transfer"); + } + if !entry.root_invocation.sub_invocations.is_empty() { + return Some("it authorizes calls beyond the transfer"); + } + None +} + #[cfg(test)] mod tests { use super::*; @@ -305,4 +334,64 @@ mod tests { let style = classify_auth_invocation(&host_fn, &invocation); assert_eq!(style, AuthStyle::Strict); } + + fn payment_entry(invocation: SorobanAuthorizedInvocation) -> SorobanAuthorizationEntry { + SorobanAuthorizationEntry { + credentials: SorobanCredentials::Address(crate::xdr::SorobanAddressCredentials { + address: ed25519_address(source_bytes()), + nonce: 0, + signature_expiration_ledger: 0, + signature: ScVal::Void, + }), + root_invocation: invocation, + } + } + + #[test] + fn payment_authorizing_only_the_transfer_is_accepted() { + let contract = [1u8; 32]; + let host_fn = host_fn_invoke(contract, "transfer", &[ScVal::U32(1)]); + let entry = payment_entry(invocation_contract(contract, "transfer", &[ScVal::U32(1)])); + assert_eq!(payment_authorization_violation(&host_fn, &[entry]), None); + } + + #[test] + fn payment_with_nested_calls_is_rejected() { + let contract = [1u8; 32]; + let other = [99u8; 32]; + let host_fn = host_fn_invoke(contract, "transfer", &[ScVal::U32(1)]); + let mut invocation = invocation_contract(contract, "transfer", &[ScVal::U32(1)]); + invocation.sub_invocations = [invocation_contract(other, "transfer", &[ScVal::U32(1_000)])] + .try_into() + .unwrap(); + assert!(payment_authorization_violation(&host_fn, &[payment_entry(invocation)]).is_some()); + } + + #[test] + fn payment_authorizing_a_different_call_is_rejected() { + let contract = [1u8; 32]; + let host_fn = host_fn_invoke(contract, "transfer", &[ScVal::U32(1)]); + let entry = payment_entry(invocation_contract(contract, "transfer", &[ScVal::U32(2)])); + assert!(payment_authorization_violation(&host_fn, &[entry]).is_some()); + } + + #[test] + fn payment_needing_several_authorizations_is_rejected() { + let contract = [1u8; 32]; + let host_fn = host_fn_invoke(contract, "transfer", &[ScVal::U32(1)]); + let entry = payment_entry(invocation_contract(contract, "transfer", &[ScVal::U32(1)])); + assert!(payment_authorization_violation(&host_fn, &[entry.clone(), entry]).is_some()); + assert!(payment_authorization_violation(&host_fn, &[]).is_some()); + } + + #[test] + fn payment_with_source_account_credentials_is_rejected() { + let contract = [1u8; 32]; + let host_fn = host_fn_invoke(contract, "transfer", &[ScVal::U32(1)]); + let entry = SorobanAuthorizationEntry { + credentials: SorobanCredentials::SourceAccount, + root_invocation: invocation_contract(contract, "transfer", &[ScVal::U32(1)]), + }; + assert!(payment_authorization_violation(&host_fn, &[entry]).is_some()); + } }