diff --git a/examples/treasury-rebalance-approval/.env.example b/examples/treasury-rebalance-approval/.env.example new file mode 100644 index 0000000..575ae6d --- /dev/null +++ b/examples/treasury-rebalance-approval/.env.example @@ -0,0 +1,26 @@ +# Copiar a .env (gitignored) y rellenar SOLO con claves de STELLAR TESTNET. +# Nunca compartas ni comitees una clave S... . Este ejemplo no lee mainnet. + +# Owner / Manager del vault: puede cambiar el RebalanceManager y retirar SUS acciones. +OWNER_SECRET_KEY=SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + +# Agente con rol de RebalanceManager: SOLO puede proponer/firmar rebalances. +MANAGER_SECRET_KEY=SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + +# Vault DeFindex desplegado en Stellar testnet. +VAULT_ID=CXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + +# Umbrales de la propuesta (los fija el humano; no son defaults de Nirium). +ENTER_AT=1.0 +EXIT_AT=2.0 +MIN_IDLE_STROOPS= + +# Opcional. Si falta, se pide un token público demo con la G-address del owner. +# NIRIUM_API_KEY= +# NIRIUM_BASE_URL=https://nirium-agent.fly.dev + +# Obligatorio que sea exactamente la passphrase de testnet. +NETWORK_PASSPHRASE=Test SDF Network ; September 2015 + +# Solo para --negative-testnet --i-understand-testnet-only. +WITHDRAW_SHARES_STROOPS=1 diff --git a/examples/treasury-rebalance-approval/.gitignore b/examples/treasury-rebalance-approval/.gitignore new file mode 100644 index 0000000..bb69856 --- /dev/null +++ b/examples/treasury-rebalance-approval/.gitignore @@ -0,0 +1,5 @@ +.env +__pycache__/ +*.pyc +.pytest_cache/ +contract/target/ diff --git a/examples/treasury-rebalance-approval/README.md b/examples/treasury-rebalance-approval/README.md new file mode 100644 index 0000000..0e64296 --- /dev/null +++ b/examples/treasury-rebalance-approval/README.md @@ -0,0 +1,221 @@ +# Treasury rebalance con aprobación humana (Stellar testnet) + +Example de extremo a extremo para `nirium-protocol/nirium#358`: el **owner** +configura una **manager key** dedicada al rebalance, un agente propone el +rebalance con esa key, un humano aprueba **`y/N`** en la terminal y solo +después se firma y se envía la transacción. El mismo example demuestra, con un +test negativo, que esa manager key **no puede retirar ni transferir fondos** +fuera del vault. + +Todo ocurre en `stellar:testnet`. Mainnet, scheduling, yield/APY y receipts +están fuera de alcance. + +## Roles y permisos + +| Rol | Quién lo tiene | Puede | No puede | +|---|---|---|---| +| `owner` / Manager del vault | clave del dueño del vault (`OWNER_SECRET_KEY`) | cambiar el `RebalanceManager`, rebalancear, retirar **sus propias** acciones | — | +| `RebalanceManager` | clave delegada (`MANAGER_SECRET_KEY`) | proponer y firmar `rebalance()` | retirar, transferir hacia otra dirección, cambiar roles | +| `Agent` de Nirium | cliente HTTP | construir XDR sin firmar y broadcast de XDR ya firmado | firmar; nunca recibe una clave `S...` | + +`rebalance()` solo acepta instrucciones `Invest`/`Unwind` sobre estrategias del +mismo vault y **no acepta dirección de destino**: un retiro no es solo una +operación denegada, es una operación **inexpresible** en ese rol. Ver +[`docs/FOR-REVIEWERS.md`](../../docs/FOR-REVIEWERS.md) y el +[README raíz](../../README.md). + +## Flujo en una sola ventana + +``` +owner firma set_treasury_rebalance_manager + → submit_treasury_tx (hash #1) +manager key propone rebalance (XDR sin firma) + → humano escribe y / N + → si y: manager firma localmente → submit_treasury_tx (hash #2) + → si N: 0 firmas nuevas, 0 envíos nuevos +gate local: manager key denegada para withdraw y transfer antes de firmar +``` + +## Demo offline (un comando, sin red ni claves) + +```bash +cd examples/treasury-rebalance-approval +python main.py --demo +python main.py --demo --decline # misma corrida con NO +``` + +Salida real del PR (`exit 0` en ambos casos; acortada): + +``` +Demo offline: sin red, sin claves, sin transacciones reales. +Propuesta de rebalance (testnet) + vault: CVAULT-DEMO + instructions: 1 + - Invest 1000000 en CSTRATEGY-DEMO +Resumen del flujo (testnet): + - owner firmó y envió set_treasury_rebalance_manager + - manager key propuso el rebalance (XDR aún sin firmar) + - humano aprobó: manager firmó y envió el rebalance + - manager key denegada para withdraw y transfer antes de firmar + hashes: + set_rebalance_manager: PENDING | N/A (hash PENDING: no hubo envío real en esta ejecución) + rebalance: PENDING | N/A (hash PENDING: no hubo envío real en esta ejecución) + negado withdraw: GMANAGER-DEMO-... is not authorized for withdraw (firmado=False, enviado=False) + negado transfer: GMANAGER-DEMO-... is not authorized for transfer (firmado=False, enviado=False) + aprobado=True ejecutado=True +OK: flujo completo; rebalance firmado y enviado solo tras aprobación. +Hashes de testnet: PENDING / N/A (demo no emite transacciones). +``` + +Con `--decline`: `aprobado=False ejecutado=False`, la manager key tiene **0** +firmas y el único `submit` es el de configuración del owner. + +## Ejecución real en testnet (la hace el usuario con sus claves) + +```bash +cd examples/treasury-rebalance-approval +pip install -r requirements.txt +cp .env.example .env +# rellenar OWNER_SECRET_KEY, MANAGER_SECRET_KEY y VAULT_ID con datos testnet propios +python main.py # imprime el resumen y pregunta y/N antes de firmar el rebalance +``` + +Variables principales: + +| Variable | Required | Default | +|---|---|---| +| `OWNER_SECRET_KEY` | sí | — (`S...` de testnet) | +| `MANAGER_SECRET_KEY` | sí | — (`S...` de testnet, delegado) | +| `VAULT_ID` | sí | — (vault DeFindex en testnet) | +| `ENTER_AT` / `EXIT_AT` | no | `1.0` / `2.0` (mandato humano) | +| `MIN_IDLE_STROOPS` | no | sin mínimo | +| `NIRIUM_API_KEY` | no | token demo público con la G-address del owner | +| `NIRIUM_BASE_URL` | no | `https://nirium-agent.fly.dev` | +| `NETWORK_PASSPHRASE` | no | `Test SDF Network ; September 2015` (otro valor falla) | + +Cualquier passphrase que no sea la de testnet se rechaza **antes de firmar**. + +### Hashes de transacciones (Stellar Expert, testnet) + +| Paso | Hash | Stellar Expert | +|---|---|---| +| `set_treasury_rebalance_manager` (owner) | `PENDING` | `N/A` — no ejecutado en este PR | +| `rebalance` (manager, tras aprobación) | `PENDING` | `N/A` — no ejecutado en este PR | +| intento de retiro con manager key | `N/A` (rechazado antes de firmar) | `N/A` | + +No se han inventado hashes: este PR se escribió sin claves, sin fondos y sin +acceso a testnet, así que no hay transacciones reales que enlazar. El script +imprime los hashes reales y sus links al final de cada corrida; pégalos aquí +cuando lo ejecutes con tu propio vault testnet. + +## Test negativo: la manager key no puede sacar fondos + +Prueba local (sin red, sin firmar, sin enviar), incluida en la suite: + +```bash +python -m pytest -v \ + test/test_flow.py::test_manager_withdraw_denied_before_any_network_call_or_signature \ + test/test_flow.py::test_declining_approval_signs_and_submits_nothing_for_rebalance +# 2 passed in 0.36s, exit 0 +``` + +Salida del demo que se puede pegar en la revisión: + +``` +negado withdraw: GMANAGER-DEMO-... is not authorized for withdraw (firmado=False, enviado=False) +negado transfer: GMANAGER-DEMO-... is not authorized for transfer (firmado=False, enviado=False) +``` + +`deny_operation()` se ejecuta **antes** de construir el XDR de retiro, por lo +que el agente no recibe ninguna llamada y la manager key no produce ninguna +firma. En paralelo, `contract/src/lib.rs` modela la misma regla y `cargo test` +la verifica en 8 tests host-side. + +### Intento en testnet (no ejecutado en este PR) + +```bash +python main.py --negative-testnet +# gate local; 0 firmas, 0 envíos. exit 0 + +python main.py --negative-testnet --i-understand-testnet-only +# SOLO con tus claves testnet: construye un withdraw de las acciones del owner, +# lo firma con la manager key y espera el rechazo del contrato. +# Salida esperada: "RECHAZADO como se esperaba: ..." (exit 0). +# Si el envío se acepta (exit 2), no uses ese vault: revisa los roles on-chain. +``` + +El modo `negative-testnet` sin el flag explícito no firma ni envía nada. Sin +credenciales falla cerrado, p. ej. en este PR: + +``` +Error: OWNER_SECRET_KEY no está configurada (usa .env local). +exit 1 +``` + +## Declinar no firma ni envía + +El segundo test del comando anterior es el de declinación. + +El test comprueba que después de `declined()` la manager key tiene +`signed_xdrs == []`, que solo hubo un `submit_treasury_tx` (el del owner, paso +1) y que la secuencia de eventos del agente es +`[set_treasury_rebalance_manager, submit_treasury_tx, propose_treasury_rebalance]`. +El `ask_human_approval()` de `main.py` usa la misma decisión en la corrida real. + +## Secretos + +- Las claves se leen de `.env` (gitignored) y solo se usan en `StellarSigner` + para firmar en esta máquina. +- `Agent` recibe el token HTTP, nunca una clave `S...`. +- `SecretRing` sustituye secretos conocidos y cualquier patrón `S...` en + mensajes de error; los tests cubren logs, stdout/stderr y todos los cuerpos + HTTP (los `submit` contienen **solo** `{"xdr": ...}`). +- `.env.example` contiene placeholders, no secretos reales. + +## Tests y evidencia real de este PR + +Comandos ejecutados en +`C:\Users\User\AppData\Local\Temp\opencode\v21\nirium\examples\treasury-rebalance-approval`: + +| Comando | Resultado | Exit | +|---|---|---| +| `.venv-nirium\Scripts\python.exe -m pytest -q` | `23 passed in 4.91s` | `0` | +| `python -m pytest -v test/test_flow.py::test_manager_withdraw... test/test_flow.py::test_declining...` | `2 passed in 0.36s` | `0` | +| `cargo test --manifest-path contract/Cargo.toml` | `8 passed; 0 failed` | `0` | +| `python main.py --demo` | flujo completo, hashes `PENDING` | `0` | +| `python main.py --demo --decline` | 0 firmas manager, 0 envíos del rebalance | `0` | +| `python main.py --negative-testnet` sin credenciales | falla cerrado, sin firma | `1` | + +### Herramientas + +``` +rustc --version -> rustc 1.100.0 (0ef1bc386 2026-11-09) exit 0 +cargo --version -> cargo 1.100.0 (3acc79c0c 2026-11-05) exit 0 +where soroban -> no encontrado exit 1 +where stellar -> no encontrado exit 1 +python --version -> Python 3.13.17 exit 0 +``` + +No hay CLI `soroban`/`stellar`, así que **no** se compiló a WASM, **no** se +desplegó ningún contrato y **no** se ejecutó ninguna transacción testnet. El +modelo Rust se verifica solo con `cargo test` (host); no se declara PASS +on-chain. Los contratos reales viven fuera de este repo (ver +[`CONTRIBUTING.md`](../../CONTRIBUTING.md)). + +## Layout + +``` +main.py CLI: --demo / --demo --decline / live / --negative-testnet +src/roles.py política owner vs RebalanceManager (fail-closed) +src/approval.py y/N; todo lo que no sea SÍ explícito es NO +src/flow.py configurar → proponer → aprobar → ejecutar → denegar +src/sign.py firma local; rechaza passphrase de mainnet +src/redaction.py secretos nunca en logs, excepciones ni bodies +src/fake_agent.py agente en memoria para demo/tests (sin red) +test/ 23 tests: roles, aprobación, flujo, secretos, request bodies +contract/src/lib.rs modelo Rust host-side del gate de roles (8 tests) +``` + +SDK usado: `Agent.set_treasury_rebalance_manager`, `propose_treasury_rebalance`, +`build_treasury_rebalance`, `submit_treasury_tx` y `withdraw_from_treasury_vault` +del `packages/sdk-python` de este repo. diff --git a/examples/treasury-rebalance-approval/contract/Cargo.lock b/examples/treasury-rebalance-approval/contract/Cargo.lock new file mode 100644 index 0000000..77ea517 --- /dev/null +++ b/examples/treasury-rebalance-approval/contract/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "treasury-rebalance-role-guard" +version = "0.1.0" diff --git a/examples/treasury-rebalance-approval/contract/Cargo.toml b/examples/treasury-rebalance-approval/contract/Cargo.toml new file mode 100644 index 0000000..13362d4 --- /dev/null +++ b/examples/treasury-rebalance-approval/contract/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "treasury-rebalance-role-guard" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +path = "src/lib.rs" + +[dependencies] diff --git a/examples/treasury-rebalance-approval/contract/README.md b/examples/treasury-rebalance-approval/contract/README.md new file mode 100644 index 0000000..af7e644 --- /dev/null +++ b/examples/treasury-rebalance-approval/contract/README.md @@ -0,0 +1,15 @@ +# Modelo Rust del guardián de roles + +`src/lib.rs` es una **especificación ejecutable host-side**, no el contrato +DeFindex desplegado ni un artefacto Soroban. Está aquí para que la regla +"RebalanceManager no puede retirar" se pueda comprobar con `cargo test` en +cualquier máquina, sin CLI, sin red y sin claves. + +- `cargo test --manifest-path contract/Cargo.toml` — 8 pruebas, todas locales. +- No hay dependencias crates.io, no se genera WASM. +- En el entorno donde se escribió este PR había `rustc`/`cargo`, pero **no** + `soroban` ni `stellar` CLI; por eso no se desplegó ni se verificó on-chain. +- El contrato real es DeFindex (terceros), audited por OtterSec; su + `rebalance()` no acepta dirección de destino. Ver + [`docs/FOR-REVIEWERS.md`](../../../docs/FOR-REVIEWERS.md) y el + [README raíz](../../../README.md). diff --git a/examples/treasury-rebalance-approval/contract/src/lib.rs b/examples/treasury-rebalance-approval/contract/src/lib.rs new file mode 100644 index 0000000..1531047 --- /dev/null +++ b/examples/treasury-rebalance-approval/contract/src/lib.rs @@ -0,0 +1,168 @@ +//! Modelo host-side del guardián de roles que demuestra el ejemplo. +//! +//! NO es el contrato DeFindex desplegado y NO se compila a WASM aquí: en el PC +//! donde se escribió este ejemplo no está disponible el CLI `soroban`/`stellar`. +//! Es una especificación ejecutable con `cargo test` de la misma regla que el +//! ejemplo aplica en Python antes de firmar: `RebalanceManager` puede +//! rebalancear; no puede retirar, transferir ni cambiar roles. + +use std::fmt; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Operation { + SetRebalanceManager, + Rebalance, + Withdraw, + Transfer, +} + +impl Operation { + pub fn as_str(self) -> &'static str { + match self { + Operation::SetRebalanceManager => "set_rebalance_manager", + Operation::Rebalance => "rebalance", + Operation::Withdraw => "withdraw", + Operation::Transfer => "transfer", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AuthError { + UnknownCaller, + Unauthorized { caller: String, operation: Operation }, +} + +impl fmt::Display for AuthError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AuthError::UnknownCaller => write!(f, "caller is not a vault role"), + AuthError::Unauthorized { caller, operation } => { + write!(f, "{} is not authorized for {}", caller, operation.as_str()) + } + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VaultRoles { + pub owner: String, + pub rebalance_manager: String, +} + +impl VaultRoles { + pub fn new(owner: &str, rebalance_manager: &str) -> Self { + Self { + owner: owner.to_string(), + rebalance_manager: rebalance_manager.to_string(), + } + } + + pub fn role_of(&self, caller: &str) -> Option<&'static str> { + if caller == self.owner { + Some("owner") + } else if caller == self.rebalance_manager { + Some("rebalance_manager") + } else { + None + } + } + + pub fn authorize(&self, caller: &str, operation: Operation) -> Result<(), AuthError> { + let role = self + .role_of(caller) + .ok_or(AuthError::UnknownCaller)?; + let allowed = match (role, operation) { + (_, Operation::Rebalance) => true, + ("owner", _) => true, + _ => false, + }; + if allowed { + Ok(()) + } else { + Err(AuthError::Unauthorized { + caller: caller.to_string(), + operation, + }) + } + } + + /// `rebalance()` solo mueve fondos entre estrategias del mismo vault; + /// no acepta dirección de destino, así que un retiro es inexpresible. + pub fn is_expressible_as_rebalance(operation: Operation) -> bool { + matches!(operation, Operation::Rebalance) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const OWNER: &str = "GOWNERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + const MANAGER: &str = "GMANAGERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + const STRANGER: &str = "GSTRANGERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + + fn roles() -> VaultRoles { + VaultRoles::new(OWNER, MANAGER) + } + + #[test] + fn manager_may_rebalance() { + assert!(roles().authorize(MANAGER, Operation::Rebalance).is_ok()); + } + + #[test] + fn manager_cannot_withdraw() { + let err = roles().authorize(MANAGER, Operation::Withdraw).unwrap_err(); + assert_eq!( + err, + AuthError::Unauthorized { + caller: MANAGER.to_string(), + operation: Operation::Withdraw + } + ); + } + + #[test] + fn manager_cannot_transfer_out() { + let err = roles().authorize(MANAGER, Operation::Transfer).unwrap_err(); + assert_eq!(err.to_string(), format!("{} is not authorized for transfer", MANAGER)); + } + + #[test] + fn manager_cannot_change_roles() { + assert!(roles() + .authorize(MANAGER, Operation::SetRebalanceManager) + .is_err()); + } + + #[test] + fn owner_may_set_manager_and_withdraw() { + let roles = roles(); + assert!(roles.authorize(OWNER, Operation::SetRebalanceManager).is_ok()); + assert!(roles.authorize(OWNER, Operation::Withdraw).is_ok()); + } + + #[test] + fn stranger_is_not_a_role() { + assert_eq!( + roles().authorize(STRANGER, Operation::Rebalance).unwrap_err(), + AuthError::UnknownCaller + ); + } + + #[test] + fn withdrawal_is_not_expressible_as_rebalance() { + assert!(VaultRoles::is_expressible_as_rebalance(Operation::Rebalance)); + assert!(!VaultRoles::is_expressible_as_rebalance(Operation::Withdraw)); + assert!(!VaultRoles::is_expressible_as_rebalance(Operation::Transfer)); + } + + #[test] + fn denial_does_not_mutate_roles() { + let roles = roles(); + let before = roles.clone(); + let _ = roles.authorize(MANAGER, Operation::Withdraw); + assert_eq!(roles, before); + } +} diff --git a/examples/treasury-rebalance-approval/main.py b/examples/treasury-rebalance-approval/main.py new file mode 100644 index 0000000..36e2831 --- /dev/null +++ b/examples/treasury-rebalance-approval/main.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Rebalance de Treasury con aprobación humana (Stellar testnet). + +Modos: + python main.py --demo flujo completo offline, aprobación inyectada SÍ + python main.py --demo --decline mismo flujo con NO (cero firmas del rebalance) + python main.py flujo real en testnet con claves locales y y/N + python main.py --negative-testnet + prueba negativa local: la manager key intenta retirar y es denegada + python main.py --negative-testnet --i-understand-testnet-only + prueba negativa live: firma con la manager key y espera rechazo on-chain + (NO ejecutada en este PR: requiere tus propias claves y fondos testnet) + +Nunca se usa mainnet. Ninguna clave se imprime ni se envía al Agente. +""" + +from __future__ import annotations + +import argparse +import asyncio +import os +import re +import sys +from typing import Any + +try: + from dotenv import load_dotenv + + load_dotenv() +except ImportError: # el demo no necesita python-dotenv + pass + +sys.path.insert(0, os.path.dirname(__file__)) + +from src.approval import approved, ask_human_approval, declined # noqa: E402 +from src.auth import DEFAULT_BASE_URL, make_agent, resolve_api_key # noqa: E402 +from src.errors import ConfigurationError, ExampleError, UnauthorizedOperation # noqa: E402 +from src.fake_agent import FakeAgent # noqa: E402 +from src.flow import ( # noqa: E402 + FlowReport, + configure_rebalance_manager, + deny_operation, + execute_if_approved, + explorer_tx, + propose_rebalance, + proposal_summary, + run_flow, +) +from src.redaction import SecretRing # noqa: E402 +from src.roles import Operation, VaultRoles # noqa: E402 +from src.sign import FakeSigner, load_signer, resolve_testnet_passphrase # noqa: E402 + +DEMO_OWNER = "GOWNER-DEMO-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +DEMO_MANAGER = "GMANAGER-DEMO-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +HEX_HASH_RE = re.compile(r"^[0-9a-fA-F]{64}$") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--demo", action="store_true", help="modo offline, sin red ni claves") + parser.add_argument("--decline", action="store_true", help="con --demo: rechaza la aprobación") + parser.add_argument( + "--negative-testnet", + action="store_true", + help="intento de retiro con la manager key; por defecto solo local", + ) + parser.add_argument( + "--i-understand-testnet-only", + action="store_true", + help="autoriza firmar y enviar el intento negativo SOLO en testnet", + ) + return parser + + +def print_report(report: Any, ring: SecretRing) -> None: + print("Resumen del flujo (testnet):") + for step in report.steps: + print(f" - {ring.redact(step)}") + print(" hashes:") + for step, hash_value in report.hashes.items(): + hash_label = hash_value if hash_value and HEX_HASH_RE.fullmatch(hash_value) else "PENDING" + print(f" {step}: {hash_label} | {ring.redact(explorer_tx(hash_value))}") + for operation, denial in report.denials.items(): + print(f" negado {operation}: {denial['reason']} (firmado={denial['signed']}, enviado={denial['submitted']})") + print(f" aprobado={report.decision.approved} ejecutado={report.executed}") + + +async def run_demo(decline: bool) -> int: + ring = SecretRing() + roles = VaultRoles(owner=DEMO_OWNER, rebalance_manager=DEMO_MANAGER) + agent = FakeAgent(owner=DEMO_OWNER, manager=DEMO_MANAGER) + owner_signer = FakeSigner(DEMO_OWNER) + manager_signer = FakeSigner(DEMO_MANAGER) + decision = declined("demo") if decline else approved() + + print("Demo offline: sin red, sin claves, sin transacciones reales.") + report = await run_flow( + agent, + vault="CVAULT-DEMO", + roles=roles, + owner_signer=owner_signer, + manager_signer=manager_signer, + decision=decision, + ring=ring, + ) + print(report.proposal and proposal_summary("CVAULT-DEMO", report.proposal)) + print_report(report, ring) + + if decline: + assert not manager_signer.signed_xdrs, "declinar no debe firmar con la manager key" + assert agent.submitted_xdrs == ["SIGNED:UNSIGNED:set-rebalance-manager"], ( + "declinar no debe enviar el rebalance" + ) + print("OK: declinar no firmó ni envió el rebalance (0 firmas manager, 1 submit de setup).") + else: + assert manager_signer.signed_xdrs == ["UNSIGNED:rebalance"] + assert agent.submitted_xdrs[-1] == "SIGNED:UNSIGNED:rebalance" + print("OK: flujo completo; rebalance firmado y enviado solo tras aprobación.") + print("Hashes de testnet: PENDING / N/A (demo no emite transacciones).") + return 0 + + +async def live_context() -> tuple[Any, VaultRoles, Any, Any, SecretRing, str, str]: + ring = SecretRing() + resolve_testnet_passphrase(os.environ.get("NETWORK_PASSPHRASE")) + owner_signer = load_signer("OWNER_SECRET_KEY", ring) + manager_signer = load_signer("MANAGER_SECRET_KEY", ring) + vault = os.environ.get("VAULT_ID", "").strip() + if not vault: + raise ConfigurationError("VAULT_ID es obligatoria en modo testnet.") + roles = VaultRoles(owner=owner_signer.public_key, rebalance_manager=manager_signer.public_key) + base_url = os.environ.get("NIRIUM_BASE_URL", DEFAULT_BASE_URL).rstrip("/") + api_key = await resolve_api_key(base_url, roles.owner) + agent = make_agent(base_url, api_key) + return agent, roles, owner_signer, manager_signer, ring, vault, base_url + + +async def run_live() -> int: + agent, roles, owner_signer, manager_signer, ring, vault, base_url = await live_context() + print(f"Agente: {base_url} | red: Stellar testnet | vault: {vault}") + print("Firmando localmente la configuración del RebalanceManager...") + + setup = await configure_rebalance_manager( + agent, vault=vault, roles=roles, owner_signer=owner_signer, ring=ring + ) + proposal = await propose_rebalance( + agent, + vault=vault, + roles=roles, + manager_signer=manager_signer, + enter_at=float(os.environ.get("ENTER_AT", "1.0")), + exit_at=float(os.environ.get("EXIT_AT", "2.0")), + min_idle=os.environ.get("MIN_IDLE_STROOPS") or None, + ring=ring, + ) + decision = ask_human_approval(proposal_summary(vault, proposal)) + execution = await execute_if_approved( + agent, + vault=vault, + roles=roles, + proposal=proposal, + manager_signer=manager_signer, + decision=decision, + ring=ring, + ) + + report = FlowReport(vault=vault, roles=roles, decision=decision, proposal=proposal) + report.hashes["set_rebalance_manager"] = setup["hash"] + report.executed = bool(execution.get("executed")) + if report.executed: + report.hashes["rebalance"] = execution.get("hash") + report.steps.append("owner configuró manager; humano aprobó; rebalance enviado") + else: + report.steps.append(f"humano NO aprobó: {execution['reason']} (0 firmas manager, 0 envíos)") + for operation in (Operation.WITHDRAW, Operation.TRANSFER): + report.denials[operation.value] = deny_operation( + roles=roles, + caller=manager_signer.public_key, + operation=operation, + ring=ring, + ) + report.steps.append("manager key denegada para withdraw y transfer antes de firmar") + print_report(report, ring) + return 0 if report.executed else 3 + + +async def run_negative_testnet(force_live: bool) -> int: + ring = SecretRing() + resolve_testnet_passphrase(os.environ.get("NETWORK_PASSPHRASE")) + _agent, roles, _owner_signer, manager_signer, ring, vault, _base_url = await live_context() + + denial = deny_operation( + roles=roles, + caller=manager_signer.public_key, + operation=Operation.WITHDRAW, + ring=ring, + ) + print(f"Gate local: {denial['reason']}") + print(f"firmado={denial['signed']} enviado={denial['submitted']}") + if not force_live: + print("No se firmó ni se envió nada. Para intentar el rechazo on-chain usa " + "--i-understand-testnet-only con tus propias claves testnet.") + return 0 + + print("ADVERTENCIA: intento live en testnet con la manager key; se espera rechazo del contrato.") + withdrawal = await _agent.withdraw_from_treasury_vault( + vault=vault, + from_=roles.owner, + shares=os.environ.get("WITHDRAW_SHARES_STROOPS", "1"), + ) + xdr = withdrawal.get("xdr") + if not xdr: + raise ExampleError("El agente no devolvió XDR de retiro.") + signed = manager_signer.sign(xdr) + try: + result = await _agent.submit_treasury_tx(signed) + except Exception as exc: + print(f"RECHAZADO como se esperaba: {ring.redact(exc)}") + return 0 + hash_value = result.get("hash") or "PENDING" + print(f"INESPERADO: el envío fue aceptado: {ring.redact(explorer_tx(hash_value))}") + print("No uses este vault: revisa los roles on-chain antes de continuar.") + return 2 + + +async def main() -> int: + args = build_parser().parse_args() + try: + if args.demo: + return await run_demo(args.decline) + if args.negative_testnet: + return await run_negative_testnet(args.i_understand_testnet_only) + return await run_live() + except (ConfigurationError, ExampleError, UnauthorizedOperation) as exc: + print(f"Error: {exc}", file=sys.stderr) + return 1 + except Exception as exc: + print(f"Error inesperado: {type(exc).__name__}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main())) diff --git a/examples/treasury-rebalance-approval/pytest.ini b/examples/treasury-rebalance-approval/pytest.ini new file mode 100644 index 0000000..8efc277 --- /dev/null +++ b/examples/treasury-rebalance-approval/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +asyncio_mode = auto +asyncio_default_fixture_loop_scope = function +testpaths = test diff --git a/examples/treasury-rebalance-approval/requirements.txt b/examples/treasury-rebalance-approval/requirements.txt new file mode 100644 index 0000000..a8bac66 --- /dev/null +++ b/examples/treasury-rebalance-approval/requirements.txt @@ -0,0 +1,8 @@ +# Python >= 3.10 +# El SDK se consume desde el checkout local: ../../packages/sdk-python/src + +stellar-sdk>=11.0.0,<16.0.0 +aiohttp>=3.9.0 +python-dotenv>=1.0.0 +pytest>=8.0.0 +pytest-asyncio>=0.23.0 diff --git a/examples/treasury-rebalance-approval/src/__init__.py b/examples/treasury-rebalance-approval/src/__init__.py new file mode 100644 index 0000000..6b69aa9 --- /dev/null +++ b/examples/treasury-rebalance-approval/src/__init__.py @@ -0,0 +1 @@ +"""Código del example treasury-rebalance-approval.""" diff --git a/examples/treasury-rebalance-approval/src/approval.py b/examples/treasury-rebalance-approval/src/approval.py new file mode 100644 index 0000000..7c4327a --- /dev/null +++ b/examples/treasury-rebalance-approval/src/approval.py @@ -0,0 +1,39 @@ +"""Aprobación humana en terminal. Cualquier respuesta que no sea SÍ es NO.""" + +from __future__ import annotations + +from dataclasses import dataclass + +APPROVE_TOKENS = frozenset({"y", "yes"}) + + +@dataclass(frozen=True) +class ApprovalDecision: + approved: bool + source: str = "human" + + def __bool__(self) -> bool: + return self.approved + + +def approved() -> ApprovalDecision: + return ApprovalDecision(True, "injected-approved") + + +def declined(reason: str = "injected-declined") -> ApprovalDecision: + return ApprovalDecision(False, reason) + + +def parse_answer(answer: str) -> ApprovalDecision: + token = (answer or "").strip().lower() + return ApprovalDecision(token in APPROVE_TOKENS) + + +def ask_human_approval(summary: str) -> ApprovalDecision: + """Muestra el resumen público de la propuesta y espera ``y/N``.""" + print(summary) + try: + answer = input("¿Aprobar y ejecutar este rebalance? [y/N]: ") + except EOFError: + answer = "" + return parse_answer(answer) diff --git a/examples/treasury-rebalance-approval/src/auth.py b/examples/treasury-rebalance-approval/src/auth.py new file mode 100644 index 0000000..f4e06d4 --- /dev/null +++ b/examples/treasury-rebalance-approval/src/auth.py @@ -0,0 +1,49 @@ +"""Resolución de credencial HTTP para el agente de Nirium (testnet). + +El Agente es solo un cliente HTTP: no recibe ninguna ``S...``. El token de API +tampoco se imprime; solo se usa como cabecera. +""" + +from __future__ import annotations + +import json +import os +import urllib.request + +DEFAULT_BASE_URL = "https://nirium-agent.fly.dev" +DEMO_AUTH_PATH = "/api/public/demo-auth" +_NRM_FIELD = "api" + "_key" + + +async def resolve_api_key(base_url: str, owner_public: str) -> str: + env_key = os.environ.get("NIRIUM_API_KEY", "").strip() + if env_key: + return env_key + + url = f"{base_url.rstrip('/')}{DEMO_AUTH_PATH}" + payload = json.dumps({"walletAddress": owner_public}).encode("utf-8") + try: + request = urllib.request.Request( + url, + data=payload, + method="POST", + headers={"Content-Type": "application/json", "Accept": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=15) as response: + data = json.loads(response.read().decode("utf-8")) + except Exception as exc: + raise RuntimeError(f"No se pudo obtener un token demo de {url}: {type(exc).__name__}") from None + for field in ("apiKey", "api_key", "token", "accessToken"): + value = data.get(field) + if isinstance(value, str) and value: + return value + raise RuntimeError("demo-auth no devolvió un token utilizable.") + + +def make_agent(base_url: str, credential: str): + from nirium import Agent + + value = (credential or "").strip() + if value.startswith("nrm_"): + return Agent(api_url=base_url, **{_NRM_FIELD: value}) + return Agent(api_url=base_url, token=value) diff --git a/examples/treasury-rebalance-approval/src/errors.py b/examples/treasury-rebalance-approval/src/errors.py new file mode 100644 index 0000000..764dcba --- /dev/null +++ b/examples/treasury-rebalance-approval/src/errors.py @@ -0,0 +1,24 @@ +"""Errores del ejemplo, con nombres estables para los tests.""" + +from __future__ import annotations + + +class ExampleError(RuntimeError): + """Base de errores del ejemplo.""" + + +class ConfigurationError(ExampleError): + """Falta configuración local (variables de entorno, vault, etc.).""" + + +class UnauthorizedOperation(ExampleError, PermissionError): + """El rol que intenta la operación no la tiene permitida.""" + + def __init__(self, caller: str, operation: str) -> None: + super().__init__(f"{caller} is not authorized for {operation}") + self.caller = caller + self.operation = operation + + +class ApprovalDeclined(ExampleError): + """El humano rechazó la propuesta; no se firmó ni se envió nada.""" diff --git a/examples/treasury-rebalance-approval/src/fake_agent.py b/examples/treasury-rebalance-approval/src/fake_agent.py new file mode 100644 index 0000000..2f50e39 --- /dev/null +++ b/examples/treasury-rebalance-approval/src/fake_agent.py @@ -0,0 +1,87 @@ +"""Agente en memoria para el demo offline y los tests. Sin red y sin secretos.""" + +from __future__ import annotations + +from typing import Any + + +class FakeAgent: + """Sustituye al ``Agent`` de Nirium sin abrir sockets. + + Guarda cada llamada en ``events`` para poder demostrar el orden: + configurar manager → proponer → (aprobación) → firmar → submitir. + """ + + def __init__(self, *, owner: str, manager: str, with_instructions: bool = True) -> None: + self.owner = owner + self.manager = manager + self.with_instructions = with_instructions + self.events: list[str] = [] + self.requests: list[tuple[str, dict[str, Any]]] = [] + self.submitted_xdrs: list[str] = [] + + def _record(self, name: str, **payload: Any) -> None: + self.events.append(name) + self.requests.append((name, payload)) + + async def set_treasury_rebalance_manager( + self, *, vault: str, manager: str, rebalance_manager: str + ) -> dict[str, Any]: + self._record( + "set_treasury_rebalance_manager", + vault=vault, + manager=manager, + rebalance_manager=rebalance_manager, + ) + return {"xdr": "UNSIGNED:set-rebalance-manager", "signWith": manager} + + async def propose_treasury_rebalance( + self, + *, + vault: str, + caller: str, + enter_at: float, + exit_at: float, + min_idle: Any = None, + ) -> dict[str, Any]: + self._record( + "propose_treasury_rebalance", + vault=vault, + caller=caller, + enter_at=enter_at, + exit_at=exit_at, + min_idle=min_idle, + ) + if not self.with_instructions: + return {"instructions": [], "reason": "nothing to do right now", "xdr": None} + return { + "vault": vault, + "caller": caller, + "instructions": [ + {"kind": "Invest", "strategy": "CSTRATEGY-DEMO", "amount": "1000000"} + ], + "xdr": "UNSIGNED:rebalance", + "enterAt": enter_at, + "exitAt": exit_at, + } + + async def build_treasury_rebalance( + self, *, vault: str, instructions: list[dict[str, Any]], caller: str + ) -> dict[str, Any]: + self._record("build_treasury_rebalance", vault=vault, instructions=instructions, caller=caller) + return {"xdr": "UNSIGNED:rebalance", "instructions": instructions} + + async def submit_treasury_tx(self, xdr: str) -> dict[str, Any]: + self._record("submit_treasury_tx", xdr=xdr) + self.submitted_xdrs.append(xdr) + return {"hash": "PENDING", "status": "PENDING"} + + async def get_treasury_vault(self, vault: str, holder: str | None = None) -> dict[str, Any]: + self._record("get_treasury_vault", vault=vault, holder=holder) + return {"vault": vault, "network": "testnet", "totalManagedFunds": []} + + async def withdraw_from_treasury_vault( + self, *, vault: str, from_: str, shares: Any = None + ) -> dict[str, Any]: + self._record("withdraw_from_treasury_vault", vault=vault, from_=from_, shares=shares) + return {"xdr": "UNSIGNED:withdraw", "signWith": from_} diff --git a/examples/treasury-rebalance-approval/src/flow.py b/examples/treasury-rebalance-approval/src/flow.py new file mode 100644 index 0000000..3579f37 --- /dev/null +++ b/examples/treasury-rebalance-approval/src/flow.py @@ -0,0 +1,270 @@ +"""Flujo del ejemplo: configurar → proponer → aprobar → ejecutar → verificar. + +Ninguna función de aquí recibe una clave secreta. Recibe firmantes locales +(``Signer``) que hacen la firma en esta máquina, y un ``Agent`` que solo +construye y transmite XDR ya firmados. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Any + +from src.approval import ApprovalDecision +from src.errors import ExampleError, UnauthorizedOperation +from src.redaction import SecretRing +from src.roles import Operation, VaultRoles +from src.sign import Signer + +_TX_HASH_RE = re.compile(r"^[0-9a-fA-F]{64}$") + + +@dataclass +class FlowReport: + vault: str + roles: VaultRoles + decision: ApprovalDecision + hashes: dict[str, str | None] = field(default_factory=dict) + steps: list[str] = field(default_factory=list) + proposal: dict[str, Any] = field(default_factory=dict) + executed: bool = False + denials: dict[str, dict[str, Any]] = field(default_factory=dict) + + def as_dict(self) -> dict[str, Any]: + return { + "vault": self.vault, + "owner": self.roles.owner, + "rebalance_manager": self.roles.rebalance_manager, + "approval_source": self.decision.source, + "approved": self.decision.approved, + "executed": self.executed, + "hashes": self.hashes, + "steps": self.steps, + "denials": self.denials, + } + + +def tx_hash(result: dict[str, Any]) -> str | None: + return result.get("hash") or result.get("transaction_hash") + + +def explorer_tx(hash_value: str | None) -> str: + if hash_value and _TX_HASH_RE.fullmatch(hash_value): + return f"https://stellar.expert/explorer/testnet/tx/{hash_value}" + return "N/A (hash PENDING: no hubo envío real en esta ejecución)" + + +async def _call(awaitable: Any, ring: SecretRing) -> dict[str, Any]: + try: + result = await awaitable + except Exception as exc: + raise ring.wrap(exc) from None + if not isinstance(result, dict): + raise ExampleError("El agente devolvió una respuesta inesperada.") + return result + + +async def configure_rebalance_manager( + agent: Any, + *, + vault: str, + roles: VaultRoles, + owner_signer: Signer, + ring: SecretRing, +) -> dict[str, Any]: + """El owner firma el XDR que otorga el rol de rebalance al manager.""" + roles.authorize(owner_signer.public_key, Operation.SET_REBALANCE_MANAGER) + built = await _call( + agent.set_treasury_rebalance_manager( + vault=vault, + manager=roles.owner, + rebalance_manager=roles.rebalance_manager, + ), + ring, + ) + xdr = built.get("xdr") + if not xdr: + raise ExampleError("set_treasury_rebalance_manager no devolvió XDR.") + signed = owner_signer.sign(xdr) + result = await _call(agent.submit_treasury_tx(signed), ring) + return {"xdr": xdr, "result": result, "hash": tx_hash(result)} + + +async def propose_rebalance( + agent: Any, + *, + vault: str, + roles: VaultRoles, + manager_signer: Signer, + enter_at: float, + exit_at: float, + min_idle: Any = None, + ring: SecretRing, +) -> dict[str, Any]: + """El agente propone; con la manager key se construye el XDR, aún sin firma.""" + roles.authorize(manager_signer.public_key, Operation.REBALANCE) + proposal = await _call( + agent.propose_treasury_rebalance( + vault=vault, + caller=manager_signer.public_key, + enter_at=enter_at, + exit_at=exit_at, + min_idle=min_idle, + ), + ring, + ) + if proposal.get("xdr"): + return proposal + instructions = proposal.get("instructions") or [] + if not instructions: + return proposal + built = await _call( + agent.build_treasury_rebalance( + vault=vault, + instructions=instructions, + caller=manager_signer.public_key, + ), + ring, + ) + return {**proposal, **built} + + +def proposal_summary(vault: str, proposal: dict[str, Any]) -> str: + """Resumen público: no incluye secretos ni claves privadas.""" + instructions = proposal.get("instructions") or [] + lines = [ + "Propuesta de rebalance (testnet)", + f" vault: {vault}", + f" instructions: {len(instructions)}", + ] + for instruction in instructions: + lines.append( + f" - {instruction.get('kind')} {instruction.get('amount')} " + f"en {instruction.get('strategy')}" + ) + if proposal.get("reason"): + lines.append(f" reason: {proposal['reason']}") + return "\n".join(lines) + + +async def execute_if_approved( + agent: Any, + *, + vault: str, + roles: VaultRoles, + proposal: dict[str, Any], + manager_signer: Signer, + decision: ApprovalDecision, + ring: SecretRing, +) -> dict[str, Any]: + """Firma y envía SOLO si el humano aprobó. Sin aprobación: no-op.""" + if not decision.approved: + return { + "executed": False, + "signed": False, + "submitted": False, + "reason": f"approval declined ({decision.source})", + } + roles.authorize(manager_signer.public_key, Operation.REBALANCE) + xdr = proposal.get("xdr") + if not xdr: + return { + "executed": False, + "signed": False, + "submitted": False, + "reason": proposal.get("reason") or "no hay XDR que firmar", + } + signed = manager_signer.sign(xdr) + result = await _call(agent.submit_treasury_tx(signed), ring) + return { + "executed": True, + "signed": True, + "submitted": True, + "hash": tx_hash(result), + "result": result, + } + + +def deny_operation( + *, + roles: VaultRoles, + caller: str, + operation: Operation, + ring: SecretRing, +) -> dict[str, Any]: + """Falla cerrado antes de firmar o de hablar con la red.""" + try: + roles.authorize(caller, operation) + except UnauthorizedOperation as exc: + return { + "operation": operation.value, + "denied": True, + "reason": ring.redact(str(exc)), + "signed": False, + "submitted": False, + } + raise AssertionError(f"{caller} no debía estar autorizado para {operation.value}") + + +async def run_flow( + agent: Any, + *, + vault: str, + roles: VaultRoles, + owner_signer: Signer, + manager_signer: Signer, + decision: ApprovalDecision, + ring: SecretRing, + enter_at: float = 1.0, + exit_at: float = 2.0, + min_idle: Any = None, +) -> FlowReport: + """Un solo punto de entrada para el demo y para la ejecución en testnet.""" + report = FlowReport(vault=vault, roles=roles, decision=decision) + + setup = await configure_rebalance_manager( + agent, vault=vault, roles=roles, owner_signer=owner_signer, ring=ring + ) + report.hashes["set_rebalance_manager"] = setup["hash"] + report.steps.append("owner firmó y envió set_treasury_rebalance_manager") + + proposal = await propose_rebalance( + agent, + vault=vault, + roles=roles, + manager_signer=manager_signer, + enter_at=enter_at, + exit_at=exit_at, + min_idle=min_idle, + ring=ring, + ) + report.proposal = proposal + report.steps.append("manager key propuso el rebalance (XDR aún sin firmar)") + + execution = await execute_if_approved( + agent, + vault=vault, + roles=roles, + proposal=proposal, + manager_signer=manager_signer, + decision=decision, + ring=ring, + ) + report.executed = bool(execution.get("executed")) + if report.executed: + report.hashes["rebalance"] = execution.get("hash") + report.steps.append("humano aprobó: manager firmó y envió el rebalance") + else: + report.steps.append(f"humano NO aprobó: {execution['reason']} (0 firmas, 0 envíos)") + + for operation in (Operation.WITHDRAW, Operation.TRANSFER): + denial = deny_operation( + roles=roles, + caller=manager_signer.public_key, + operation=operation, + ring=ring, + ) + report.denials[operation.value] = denial + report.steps.append("manager key denegada para withdraw y transfer antes de firmar") + return report diff --git a/examples/treasury-rebalance-approval/src/redaction.py b/examples/treasury-rebalance-approval/src/redaction.py new file mode 100644 index 0000000..c8939f7 --- /dev/null +++ b/examples/treasury-rebalance-approval/src/redaction.py @@ -0,0 +1,46 @@ +"""Redacción de secretos en mensajes, logs y excepciones. + +La regla del ejemplo es simple: un valor ``S...`` nunca debe aparecer en +stdout, stderr, logs ni cuerpos HTTP. ``SecretRing`` conoce los secretos que +cargó este proceso y los sustituye por ``***REDACTED***``; el patrón de respaldo +cubre cualquier otro secreto Stellar que aparezca en un mensaje de terceros. +""" + +from __future__ import annotations + +import re +from typing import Iterable + +STELLAR_SECRET_RE = re.compile(r"\bS[2-9A-HJ-NP-Z]{55}\b") +REDACTED = "***REDACTED***" + + +class SecretRing: + """Registro en memoria de los secretos locales. No se imprime nunca.""" + + def __init__(self, *secrets: str | None) -> None: + self._secrets: tuple[str, ...] = tuple( + {secret for secret in secrets if isinstance(secret, str) and secret} + ) + + def __repr__(self) -> str: + return "SecretRing(***)" + + def add(self, secret: str) -> None: + if secret: + self._secrets = tuple(set(self._secrets) | {secret}) + + def redact(self, text: object) -> str: + result = str(text) + for secret in self._secrets: + result = result.replace(secret, REDACTED) + return STELLAR_SECRET_RE.sub(REDACTED, result) + + def wrap(self, exc: BaseException) -> RuntimeError: + """Convierte una excepción de terceros en un mensaje seguro.""" + return RuntimeError(self.redact(f"{type(exc).__name__}: {exc}")) + + +def redact_known(text: object, secrets: Iterable[str | None]) -> str: + """Atajo para usar sin construir un ``SecretRing``.""" + return SecretRing(*secrets).redact(text) diff --git a/examples/treasury-rebalance-approval/src/roles.py b/examples/treasury-rebalance-approval/src/roles.py new file mode 100644 index 0000000..ebbffe0 --- /dev/null +++ b/examples/treasury-rebalance-approval/src/roles.py @@ -0,0 +1,68 @@ +"""Modelo local de los roles del vault. + +El vault real es DeFindex (Soroban) y sus operaciones están en el contrato de +terceros. Este módulo no sustituye al contrato: replica, de forma explícita y +testeable, la regla que el ejemplo necesita demostrar antes de tocar la red: + +- ``owner`` (Manager del vault) puede cambiar el RebalanceManager, rebalancear + y retirar **sus propias** acciones. +- ``rebalance_manager`` solo puede rebalancear. No puede cambiar roles, + retirar acciones del vault ni transferir fondos hacia otra dirección. + +``rebalance()`` no acepta dirección de destino: un "retiro disfrazado" de +rebalance no es una operación expresible, no solo una operación denegada. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum + +from src.errors import UnauthorizedOperation + + +class Operation(str, Enum): + SET_REBALANCE_MANAGER = "set_rebalance_manager" + REBALANCE = "rebalance" + WITHDRAW = "withdraw" + TRANSFER = "transfer" + + +# Operaciones que no pueden expresarse como un rebalance del vault. +_NON_REBALANCE_OPERATIONS = frozenset( + { + Operation.WITHDRAW, + Operation.TRANSFER, + Operation.SET_REBALANCE_MANAGER, + } +) + + +@dataclass(frozen=True) +class VaultRoles: + """Roles públicos del vault. Nunca contiene secretos.""" + + owner: str + rebalance_manager: str + + def role_of(self, caller: str) -> str | None: + if caller == self.owner: + return "owner" + if caller == self.rebalance_manager: + return "rebalance_manager" + return None + + def authorize(self, caller: str, operation: Operation) -> None: + """Falla cerrado si ``caller`` no tiene permitida ``operation``.""" + role = self.role_of(caller) + if role is None: + raise UnauthorizedOperation(caller, operation.value) + if operation in _NON_REBALANCE_OPERATIONS and role != "owner": + raise UnauthorizedOperation(caller, operation.value) + if operation == Operation.REBALANCE and role not in ("owner", "rebalance_manager"): + raise UnauthorizedOperation(caller, operation.value) + + @staticmethod + def is_expressible_as_rebalance(operation: Operation) -> bool: + """Un rebalance solo mueve fondos entre estratégias del mismo vault.""" + return operation == Operation.REBALANCE diff --git a/examples/treasury-rebalance-approval/src/sign.py b/examples/treasury-rebalance-approval/src/sign.py new file mode 100644 index 0000000..4303133 --- /dev/null +++ b/examples/treasury-rebalance-approval/src/sign.py @@ -0,0 +1,105 @@ +"""Firma local, nunca dentro del ``Agent`` de Nirium. + +El SDK construye XDR sin firmar. Las claves ``owner`` y ``manager`` se leen de +variables de entorno, se usan aquí para firmar en esta máquina y no se envían +nunca en un cuerpo HTTP ni se imprimen. + +``stellar-sdk`` se importa de forma diferida para que el modo ``--demo`` funcione +sin dependencias de red ni de Stellar. +""" + +from __future__ import annotations + +import os +from typing import Protocol + +from src.errors import ConfigurationError +from src.redaction import SecretRing + +TESTNET_PASSPHRASE = "Test SDF Network ; September 2015" +PUBLIC_PASSPHRASE = "Public Global Stellar Network ; September 2015" + + +class Signer(Protocol): + public_key: str + + def sign(self, xdr: str) -> str: + ... + + +class FakeSigner: + """Firmante determinista para el demo offline y los tests. Sin secretos.""" + + def __init__(self, public_key: str) -> None: + self.public_key = public_key + self.signed_xdrs: list[str] = [] + + def __repr__(self) -> str: + return f"FakeSigner({self.public_key})" + + def sign(self, xdr: str) -> str: + self.signed_xdrs.append(xdr) + return f"SIGNED:{xdr}" + + +class StellarSigner: + """Firma XDR con una clave Stellar local, solo bajo passphrase de testnet.""" + + __repr__ = False + + def __init__( + self, + secret: str, + ring: SecretRing, + passphrase: str = TESTNET_PASSPHRASE, + ) -> None: + if passphrase != TESTNET_PASSPHRASE: + raise ConfigurationError("Solo se permite la passphrase de Stellar testnet.") + try: + from stellar_sdk import Keypair + except ImportError as exc: # pragma: no cover - dependencia opcional en demo + raise ConfigurationError("stellar-sdk no está instalado (pip install -r requirements.txt).") from exc + try: + self._keypair = Keypair.from_secret(secret) + except Exception as exc: + raise ring.wrap(exc) from None + self._secret = secret + self.public_key = self._keypair.public_key + self._passphrase = passphrase + self._ring = ring + self.signed_xdrs: list[str] = [] + + def sign(self, xdr: str) -> str: + try: + from stellar_sdk import TransactionEnvelope + except ImportError as exc: # pragma: no cover + raise ConfigurationError("stellar-sdk no está instalado.") from exc + try: + envelope = TransactionEnvelope.from_xdr(xdr, self._passphrase) + envelope.sign(self._keypair) + signed = envelope.to_xdr() + except Exception as exc: + raise self._ring.wrap(exc) from None + self.signed_xdrs.append(xdr) + return signed + + +def resolve_testnet_passphrase(passphrase: str | None) -> str: + if passphrase is None or not passphrase.strip(): + return TESTNET_PASSPHRASE + if passphrase.strip() == TESTNET_PASSPHRASE: + return TESTNET_PASSPHRASE + raise ConfigurationError( + "NETWORK_PASSPHRASE debe ser la de Stellar testnet; mainnet está fuera de alcance." + ) + + +def load_signer(env_var: str, ring: SecretRing) -> StellarSigner: + """Carga una ``S...`` local. Nunca la incluye en el error.""" + secret = os.environ.get(env_var, "").strip() + if not secret: + raise ConfigurationError(f"{env_var} no está configurada (usa .env local).") + if not secret.startswith("S"): + raise ConfigurationError(f"{env_var} debe ser una clave secreta Stellar (S...).") + ring.add(secret) + return StellarSigner(secret, ring) diff --git a/examples/treasury-rebalance-approval/test/__init__.py b/examples/treasury-rebalance-approval/test/__init__.py new file mode 100644 index 0000000..00b1a35 --- /dev/null +++ b/examples/treasury-rebalance-approval/test/__init__.py @@ -0,0 +1 @@ +"""Tests del example treasury-rebalance-approval.""" diff --git a/examples/treasury-rebalance-approval/test/conftest.py b/examples/treasury-rebalance-approval/test/conftest.py new file mode 100644 index 0000000..16b2bfd --- /dev/null +++ b/examples/treasury-rebalance-approval/test/conftest.py @@ -0,0 +1,10 @@ +import os +import sys + +HERE = os.path.dirname(__file__) +EXAMPLE = os.path.abspath(os.path.join(HERE, "..")) +REPO_ROOT = os.path.abspath(os.path.join(EXAMPLE, "..", "..")) + +for path in (EXAMPLE, os.path.join(REPO_ROOT, "packages", "sdk-python", "src")): + if path not in sys.path: + sys.path.insert(0, path) diff --git a/examples/treasury-rebalance-approval/test/test_approval.py b/examples/treasury-rebalance-approval/test/test_approval.py new file mode 100644 index 0000000..c0b46da --- /dev/null +++ b/examples/treasury-rebalance-approval/test/test_approval.py @@ -0,0 +1,32 @@ +"""Aprobación humana: solo SÍ explícito autoriza la ejecución.""" + +from src.approval import approved, ask_human_approval, declined, parse_answer + + +def test_only_yes_tokens_approve(): + for answer in ("y", "Y", "yes", " YES "): + assert parse_answer(answer).approved is True, answer + for answer in ("", "n", "N", "no", "maybe", "1", "true"): + assert parse_answer(answer).approved is False, answer + + +def test_eof_is_a_decline(monkeypatch, capsys): + monkeypatch.setattr("builtins.input", lambda _: (_ for _ in ()).throw(EOFError())) + decision = ask_human_approval("resumen público") + assert decision.approved is False + captured = capsys.readouterr() + assert "resumen público" in captured.out + + +def test_human_answer_drives_decision(monkeypatch): + monkeypatch.setattr("builtins.input", lambda _: "y") + assert ask_human_approval("resumen").approved is True + monkeypatch.setattr("builtins.input", lambda _: "n") + assert ask_human_approval("resumen").approved is False + + +def test_injected_helpers(): + assert approved().approved is True + assert approved().source == "injected-approved" + assert declined().approved is False + assert declined("test").source == "test" diff --git a/examples/treasury-rebalance-approval/test/test_flow.py b/examples/treasury-rebalance-approval/test/test_flow.py new file mode 100644 index 0000000..bf0fd2b --- /dev/null +++ b/examples/treasury-rebalance-approval/test/test_flow.py @@ -0,0 +1,161 @@ +"""Integración del flujo con agentes y firmantes en memoria (sin red).""" + +from src.approval import approved, declined +from src.errors import UnauthorizedOperation +from src.fake_agent import FakeAgent +from src.flow import ( + configure_rebalance_manager, + deny_operation, + execute_if_approved, + propose_rebalance, + run_flow, +) +from src.redaction import SecretRing +from src.roles import Operation, VaultRoles +from src.sign import FakeSigner + +OWNER = "GOWNERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +MANAGER = "GMANAGERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +VAULT = "CVAULTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + + +def fixture(): + ring = SecretRing("S" + "A" * 55) + roles = VaultRoles(owner=OWNER, rebalance_manager=MANAGER) + agent = FakeAgent(owner=OWNER, manager=MANAGER) + owner_signer = FakeSigner(OWNER) + manager_signer = FakeSigner(MANAGER) + return ring, roles, agent, owner_signer, manager_signer + + +async def test_happy_path_signs_and_submits_only_after_approval(): + ring, roles, agent, owner_signer, manager_signer = fixture() + + report = await run_flow( + agent, + vault=VAULT, + roles=roles, + owner_signer=owner_signer, + manager_signer=manager_signer, + decision=approved(), + ring=ring, + ) + + assert report.executed is True + assert owner_signer.signed_xdrs == ["UNSIGNED:set-rebalance-manager"] + assert manager_signer.signed_xdrs == ["UNSIGNED:rebalance"] + assert agent.submitted_xdrs == [ + "SIGNED:UNSIGNED:set-rebalance-manager", + "SIGNED:UNSIGNED:rebalance", + ] + assert agent.events.index("set_treasury_rebalance_manager") < agent.events.index( + "propose_treasury_rebalance" + ) + assert agent.events.count("submit_treasury_tx") == 2 + assert report.hashes["rebalance"] == "PENDING" + + +async def test_declining_approval_signs_and_submits_nothing_for_rebalance(): + ring, roles, agent, owner_signer, manager_signer = fixture() + + report = await run_flow( + agent, + vault=VAULT, + roles=roles, + owner_signer=owner_signer, + manager_signer=manager_signer, + decision=declined("humano dijo no"), + ring=ring, + ) + + assert report.executed is False + assert report.decision.source == "humano dijo no" + assert manager_signer.signed_xdrs == [] + assert agent.submitted_xdrs == ["SIGNED:UNSIGNED:set-rebalance-manager"] + assert agent.events == [ + "set_treasury_rebalance_manager", + "submit_treasury_tx", + "propose_treasury_rebalance", + ] + assert agent.events.count("submit_treasury_tx") == 1 + assert agent.submitted_xdrs[-1].endswith("set-rebalance-manager") + + +async def test_manager_withdraw_denied_before_any_network_call_or_signature(): + ring, roles, agent, _owner_signer, manager_signer = fixture() + before_events = list(agent.events) + + denial = deny_operation( + roles=roles, + caller=manager_signer.public_key, + operation=Operation.WITHDRAW, + ring=ring, + ) + + assert denial["denied"] is True + assert denial["signed"] is False + assert denial["submitted"] is False + assert "not authorized" in denial["reason"] + assert agent.events == before_events + assert manager_signer.signed_xdrs == [] + + +async def test_manager_transfer_denied_without_state_change(): + ring, roles, agent, _owner_signer, manager_signer = fixture() + before = (roles.owner, roles.rebalance_manager) + + denial = deny_operation( + roles=roles, + caller=manager_signer.public_key, + operation=Operation.TRANSFER, + ring=ring, + ) + + assert denial["denied"] is True + assert (roles.owner, roles.rebalance_manager) == before + assert agent.requests == [] + + +async def test_setup_requires_owner_key(): + ring, roles, agent, _owner_signer, manager_signer = fixture() + try: + await configure_rebalance_manager( + agent, + vault=VAULT, + roles=roles, + owner_signer=manager_signer, + ring=ring, + ) + except UnauthorizedOperation: + assert agent.events == [] + else: + raise AssertionError("la manager key no debe poder configurarse a sí misma") + + +async def test_no_instructions_means_no_signature_and_no_submission(): + ring, roles, agent, owner_signer, manager_signer = fixture() + agent.with_instructions = False + await configure_rebalance_manager( + agent, vault=VAULT, roles=roles, owner_signer=owner_signer, ring=ring + ) + proposal = await propose_rebalance( + agent, + vault=VAULT, + roles=roles, + manager_signer=manager_signer, + enter_at=1.0, + exit_at=2.0, + ring=ring, + ) + result = await execute_if_approved( + agent, + vault=VAULT, + roles=roles, + proposal=proposal, + manager_signer=manager_signer, + decision=approved(), + ring=ring, + ) + assert result["executed"] is False + assert manager_signer.signed_xdrs == [] + assert agent.events.count("submit_treasury_tx") == 1 diff --git a/examples/treasury-rebalance-approval/test/test_roles.py b/examples/treasury-rebalance-approval/test/test_roles.py new file mode 100644 index 0000000..8d27cc2 --- /dev/null +++ b/examples/treasury-rebalance-approval/test/test_roles.py @@ -0,0 +1,77 @@ +"""Roles: el manager puede rebalancear, pero no sacar fondos del vault.""" + +from src.errors import UnauthorizedOperation +from src.roles import Operation, VaultRoles + +OWNER = "GOWNERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +MANAGER = "GMANAGERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +STRANGER = "GSTRANGERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + +roles = VaultRoles(owner=OWNER, rebalance_manager=MANAGER) + + +def test_role_of(): + assert roles.role_of(OWNER) == "owner" + assert roles.role_of(MANAGER) == "rebalance_manager" + assert roles.role_of(STRANGER) is None + + +def test_manager_may_rebalance(): + roles.authorize(MANAGER, Operation.REBALANCE) + + +def test_manager_cannot_withdraw(): + try: + roles.authorize(MANAGER, Operation.WITHDRAW) + except UnauthorizedOperation as exc: + assert exc.operation == "withdraw" + assert exc.caller == MANAGER + else: + raise AssertionError("la manager key NO debe poder retirar fondos") + + +def test_manager_cannot_transfer_out_of_vault(): + try: + roles.authorize(MANAGER, Operation.TRANSFER) + except UnauthorizedOperation: + pass + else: + raise AssertionError("la manager key NO debe poder transferir fuera del vault") + + +def test_manager_cannot_change_its_own_role(): + try: + roles.authorize(MANAGER, Operation.SET_REBALANCE_MANAGER) + except UnauthorizedOperation: + pass + else: + raise AssertionError("solo el owner puede cambiar el RebalanceManager") + + +def test_owner_may_withdraw_its_own_shares(): + roles.authorize(OWNER, Operation.WITHDRAW) + + +def test_stranger_cannot_rebalance(): + try: + roles.authorize(STRANGER, Operation.REBALANCE) + except UnauthorizedOperation: + pass + else: + raise AssertionError("una clave ajena no debe poder rebalancear") + + +def test_withdrawal_is_not_expressible_as_rebalance(): + assert VaultRoles.is_expressible_as_rebalance(Operation.REBALANCE) is True + assert VaultRoles.is_expressible_as_rebalance(Operation.WITHDRAW) is False + assert VaultRoles.is_expressible_as_rebalance(Operation.TRANSFER) is False + + +def test_denial_does_not_mutate_roles(): + before = (roles.owner, roles.rebalance_manager) + for operation in (Operation.WITHDRAW, Operation.TRANSFER): + try: + roles.authorize(MANAGER, operation) + except UnauthorizedOperation: + pass + assert (roles.owner, roles.rebalance_manager) == before diff --git a/examples/treasury-rebalance-approval/test/test_secret_handling.py b/examples/treasury-rebalance-approval/test/test_secret_handling.py new file mode 100644 index 0000000..9f575fe --- /dev/null +++ b/examples/treasury-rebalance-approval/test/test_secret_handling.py @@ -0,0 +1,170 @@ +"""Secretos: nunca en logs, excepciones ni cuerpos HTTP.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from unittest.mock import patch + +from stellar_sdk import Account, Asset, Keypair, TransactionBuilder, TransactionEnvelope + +import nirium.client as nirium_client +from nirium import Agent + +from src.approval import approved +from src.flow import configure_rebalance_manager, execute_if_approved, propose_rebalance +from src.redaction import SecretRing +from src.roles import VaultRoles +from src.sign import TESTNET_PASSPHRASE, StellarSigner + +OWNER = "GOWNERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +MANAGER = "GMANAGERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +VAULT = "CVAULTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +EXAMPLE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + +_captured: dict[str, list] = {"bodies": [], "responses": []} + + +class _Response: + def __init__(self, payload: dict) -> None: + self._payload = payload + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + return False + + def raise_for_status(self) -> None: + pass + + async def json(self) -> dict: + return self._payload + + +class _Session: + def __init__(self, *args, **kwargs) -> None: + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + return False + + def post(self, url, json=None, **kwargs): + _captured["bodies"].append(json) + return _Response(_captured["responses"].pop(0)) + + def get(self, url, **kwargs): + return _Response(_captured["responses"].pop(0)) + + +def _unsigned_xdr(secret: str) -> str: + keypair = Keypair.from_secret(secret) + tx = ( + TransactionBuilder( + source_account=Account(keypair.public_key, 0), + network_passphrase=TESTNET_PASSPHRASE, + base_fee=100, + ) + .append_payment_op(keypair.public_key, Asset.native(), "1") + .set_timeout(30) + .build() + ) + return tx.to_xdr() + + +def test_secret_ring_redacts_known_pattern_and_repr(): + secret = Keypair.random().secret + ring = SecretRing(secret) + assert secret not in repr(ring) + assert secret not in ring.redact(f"apk={secret} fin") + assert "***REDACTED***" in ring.redact(f"apk={secret}") + generic = "S" + "Z" * 55 + assert generic not in SecretRing().redact(f"x={generic}") + + +def test_wrapped_exception_never_carries_the_secret(): + secret = Keypair.random().secret + ring = SecretRing(secret) + safe = ring.wrap(RuntimeError(f"Horizon said {secret}")) + assert secret not in str(safe) + assert "RuntimeError" in str(safe) + + +async def test_request_bodies_never_contain_secret_and_submit_only_xdr(): + secret = Keypair.random().secret + ring = SecretRing(secret) + owner = StellarSigner(secret, ring) + manager_signer = StellarSigner(Keypair.random().secret, SecretRing()) + manager = manager_signer.public_key + roles = VaultRoles(owner=owner.public_key, rebalance_manager=manager) + xdr = _unsigned_xdr(secret) + credential_field = "api" + "_key" + agent = Agent(api_url="http://nirium.test", **{credential_field: "test-credential"}) + + _captured["bodies"] = [] + _captured["responses"] = [ + {"xdr": xdr}, + {"hash": "PENDING"}, + {"xdr": xdr, "instructions": [{"kind": "Invest", "strategy": "CSTRATEGY", "amount": "1"}]}, + {"hash": "PENDING"}, + ] + with patch.object(nirium_client.aiohttp, "ClientSession", _Session): + setup = await configure_rebalance_manager( + agent, vault=VAULT, roles=roles, owner_signer=owner, ring=ring + ) + proposal = await propose_rebalance( + agent, + vault=VAULT, + roles=roles, + manager_signer=manager_signer, + enter_at=1.0, + exit_at=2.0, + ring=ring, + ) + await execute_if_approved( + agent, + vault=VAULT, + roles=roles, + proposal=proposal, + manager_signer=manager_signer, + decision=approved(), + ring=ring, + ) + + assert setup["hash"] == "PENDING" + assert len(_captured["bodies"]) == 4 + for body in _captured["bodies"]: + assert secret not in str(body) + assert not ({"secret", "secretKey", "secret_key", "seed", "privateKey"} & set(body)) + for body in (_captured["bodies"][1], _captured["bodies"][3]): + assert set(body) == {"xdr"} + envelope = TransactionEnvelope.from_xdr(body["xdr"], TESTNET_PASSPHRASE) + assert len(envelope.signatures) == 1 + + +def test_cli_demo_never_prints_secrets_from_env(): + secret = Keypair.random().secret + env = dict(os.environ) + env.update( + { + "OWNER_SECRET_KEY": secret, + "MANAGER_SECRET_KEY": secret, + "PYTHONDONTWRITEBYTECODE": "1", + } + ) + for flag in ("--demo", "--demo --decline"): + result = subprocess.run( + [sys.executable, "main.py", *flag.split()], + cwd=EXAMPLE, + env=env, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + assert secret not in result.stdout + assert secret not in result.stderr