caelum0x d7cac9c38a fix(rago): trust Caddy's real IP hop, not client-forged XFF; release Mint hold on insert_event failure
client_ip() read the left-most X-Forwarded-For entry, which a direct
caller to Caddy can forge freely (Caddy appends, never strips, the real
peer address). This let attackers spoof the anon rate-limit bucket key
(observability.rs) and the buyer IP sent to Iyzico / persisted for
clock-triggered charges (checkout_webhooks.rs). Since Caddy is the sole
public listener and every rago host binds 127.0.0.1-only, there is
exactly one trusted hop: read the right-most XFF entry (Caddy's own
append) instead, and only that single hop - never fall through to
client-supplied entries if it's missing or unparsable. Updated the test
that previously locked in the vulnerable left-most behavior and added a
test asserting a forged left-most entry is never trusted.

ingest_event() placed a real-time wallet Mint hold before inserting the
event, but only released it on the Ok(false) duplicate-insert path. Any
other insert_event error (pool exhaustion, connection reset, ...)
propagated via `?` straight out of the function, leaving the hold open
with no corresponding `events` row - money silently reserved for an
event the caller was told failed, later captured by settle_invoice
against a line item that never existed. Now insert_event's Err path
releases the hold before returning the error, same as the duplicate
path.

Verified: cargo check -p rago-api clean; cargo test -p rago-api --lib
25/25 pass (incl. 2 new client_ip tests); standalone before/after repro
confirms the old left-most logic returns the forged "1.2.3.4" from
"X-Forwarded-For: 1.2.3.4, 9.9.9.9" while the fixed right-most logic
returns the real "9.9.9.9".
2026-11-03 15:55:17 +03:00
..

Rago

A faithful, from-scratch Rust rewrite of Lago — an open-source, usage-based billing / metering platform. Rago is a Lago-compatible billing service: metering, subscriptions, usage-based pricing, invoicing (with exact money), payments, webhooks, a GraphQL dashboard API, a REST API (v1 + v2), documents (PDF / XML), integrations (tax / accounting / CRM), and a durable background worker — all in one Cargo workspace.

Money is exact (rust_decimal, integer cents) end-to-end; there is no f64 money anywhere in the pipeline.

Run it

Option A — Docker Compose (one command)

cp .env.example .env
docker compose up --build
# API + GraphQL + worker daemon on http://localhost:3000
# add the ClickHouse event store:  docker compose --profile clickhouse up --build

Option B — the single supervising binary

# Postgres must be reachable via DATABASE_URL.
export DATABASE_URL=postgres://postgres:postgres@localhost:5432/rago
cargo run --release --bin rago-server

rago-server boots the REST + GraphQL API, the operator console at /admin, and the scheduler/worker daemon in a single process: subscription crons, the clock registry (invoice finalization, wallet top-ups/expiry, coupon expiry, usage snapshots), dunning, the once-a-day billing cycle (bill → invoice → webhooks → payment collection through each organization's provider), the durable job queue, and outbound webhook delivery. Embedded migrations run automatically on startup.

Option C — separate processes

cargo run --release --bin rago-api        # API only
cargo run --release --bin rago-worker      # durable worker / CLI (work, crons, dunning, daemon, ...)
cargo run --release --bin rago-scheduler   # billing scheduler

Bootstrapping a tenant (organization + API key)

Rago has no public signup. Create each consumer's organization and first key with the worker; it prints the key once as API_KEY=... (logs go to stderr):

rago-worker create-org --name "AutoGTM" [--slug autogtm] [--currency USD] [--email ops@example.com]
rago-worker create-api-key --org autogtm --name relay   # extra key; --org takes the id or slug

After that, sign in to /admin with the key and manage keys (create, rotate, delete) under Operations → API keys.

Live transports

Every external call — payments (Stripe / GoCardless / Adyen / Creem / Dodo Payments / Iyzico), Mint holds, outbound webhooks, tax/accounting/CRM aggregators, integration OAuth, SSO, the finance assistant, and email — goes through an injectable transport. Production builds use the real reqwest HTTP and SMTP transports:

cargo build --release --features live --bin rago-server   # what the Dockerfile builds

A build without live uses a disabled transport: outbound calls fail and are recorded as failures (nothing is ever marked paid or delivered without a real call). Tests inject scripted in-memory transports.

Payment providers are configured per organization from the console (Settings → Connect Stripe, GoCardless, Adyen, Creem, Dodo Payments or Iyzico). Secrets are sealed with RAGO_ENCRYPTION_KEY. Single-tenant deployments can instead set RAGO_PAYMENT_PROVIDER and that provider's RAGO_* keys (see .env.example). Stripe, GoCardless and Adyen charge a stored payment method: each customer gets a Stripe customer on first charge, and charges use their saved payment method. Creem and Dodo Payments (merchants of record) and Iyzico collect through a hosted checkout. The invoice's payment waits for the customer, its pay link is sent in payment.requires_action and shown in the customer portal, and the signed provider webhook settles it. Creem's API can only refund whole payments (POST /v1/refunds takes a transaction id and no amount), so a partial refund to a Creem payment is refused up front with partial_refund_unsupported (no credit note is created) and must be issued from the Creem dashboard. Dodo and Iyzico refund any amount. Iyzico needs each customer's name, email, country, address_line1, city and identity_number (TC kimlik no for Turkish buyers) on the customer record; an incomplete customer is refused with customer_details_missing naming the fields, and nothing is sent to Iyzico.

Customer portal

POST /api/v1/customers/:external_id/portal_sessions issues a signed, expiring link to /portal/:token (24 hours by default, 30 days at most; DELETE on the same path revokes every open link). The portal is free and works with any provider or none. It shows invoices with PDF download and a Pay button, usage this period per billable metric, and wallet balances with top-up. Customers manage a subscription on a confirmation page: they can switch to a cheaper plan (same currency and interval) at the end of the current period, or cancel immediately after ticking an explicit confirmation. A scheduled downgrade is activated by the billing clock (activate_subscriptions): the outgoing plan's closing period is billed, then the old subscription is terminated and the new one started in one transaction. Operators do the same with GET/POST/DELETE /api/v1/subscriptions/:external_id/plan_change ({ "plan_change": { "plan_code": "starter" } }). Customers can update their payment method when Stripe is the provider. GET /customers/:external_id/portal_url returns a portal link whenever the organization does not collect with Stripe.

Real-time wallets (Mint holds)

PUT /api/v1/wallets/:id/realtime with { "wallet": { "realtime_enabled": true, "realtime_policy": "reject" | "flag", "mint_account_id": "<customer's Mint account>" } } turns a USD wallet into a real-time wallet. Every event posted to /events is priced at its marginal cost by the plan's charge models and held on the customer's Mint account. The hold's idempotency key comes from the event's transaction_id, so a retried event is only held once. If the balance does not cover the event, reject answers 422 wallet_balance_insufficient and does not store it, while flag stores it and reports event.error. If Mint is unreachable, reject answers 503 and fails closed. When the invoice is finalized, the holds are captured to RAGO_MINT_PAYEE_ACCOUNT up to the amount due and applied as prepaid credit, and any surplus is released. Voiding an invoice releases holds that are still reserved for it and moves money already captured for it back from RAGO_MINT_PAYEE_ACCOUNT to the customer's Mint account (one idempotent Mint transfer per captured hold; failures are kept on the hold and retried with POST /api/v1/wallets/:id/realtime/reversals). The console's wallet page links to a real-time screen (GET /api/v1/wallets/:id/realtime/overview and /holds) with the live Mint balance, holds by event, top-ups, the Mint ledger, and a hosted top-up link (POST /api/v1/wallets/:id/realtime/top_ups). Set RAGO_MINT_URL, RAGO_MINT_API_KEY and RAGO_MINT_PAYEE_ACCOUNT to enable real-time wallets.

Configuration

All configuration is via environment variables — see .env.example. Key ones: DATABASE_URL, RAGO_API_ADDR, RAGO_TICK_SECS, RAGO_BILLING_HOUR, RAGO_RATE_LIMIT, RAGO_KEY_RATE_LIMIT, RUST_LOG, and the RAGO_* / SMTP live-transport keys.

API surface

Area Endpoint(s)
Health / metrics GET /health, GET /metrics (Prometheus)
GraphQL dashboard `GET
REST v1 /api/v1/* — customers, metrics, plans, subscriptions, events, invoices, wallets, coupons, credit notes, add-ons, quotes, data exports, entitlements, usage alerts, dunning campaigns, lifetime usage, integrations
REST v2 /api/v2/* — batch events ingestion, fee estimate, data-API analytics
Provider webhooks POST /webhooks/{stripe,gocardless,adyen,creem,dodo,iyzico}/:organization_id
Customer portal GET /portal/:token (+ invoice PDF, pay, wallet top-up, cancel, payment method)
Documents GET /api/v1/invoices/:id/download(.xml), .../receipt, /credit_notes/:id/download

Authentication is API-key bearer (Authorization: Bearer <key>) on REST; the GraphQL dashboard resolves the same principal.

Credit notes on later invoices

A credit note's credited amount (balance_amount_cents) is spent on the customer's next finalized invoices, as in Lago: after coupons and taxes, oldest note first, each note giving at most what is still due and keeping the rest of its balance. (Rago draws prepaid wallet credit when the invoice is created, so on subscription invoices the wallet is applied before credit notes; Lago applies credit notes first. Either way nothing is counted twice.) A note used up becomes credit_status: consumed. Each draw is listed in the invoice's credits (GET /api/v1/invoices/:id) and in the console's invoice page. Voiding an invoice gives the balance it used back to its notes.

Two Rago rules on top of Lago: a credit note only becomes spendable once its own invoice is paid (an unpaid invoice's credit note already lowers what that invoice owes), and a credit note cannot be issued on a draft invoice. A termination credit for a pay-in-advance fee whose invoice is still a draft (grace period) is kept as a draft credit note and is finalized, numbered and announced together with that invoice.

Observability

  • Prometheus metrics at GET /metrics: HTTP request counts, in-flight gauge, latency histogram, and domain counters (rago_invoices_generated_total, rago_emails_sent_total, rago_usage_alerts_fired_total, rago_webhooks_enqueued_total, response-class counters, rago_rate_limited_total).
  • tracing spans on every request (and the worker daemon).
  • Fixed-window rate limiting middleware: per credential (RAGO_KEY_RATE_LIMIT, default 3000/min, so one organization cannot exhaust the rest) and global (RAGO_RATE_LIMIT, default 6000/min); 429 with Retry-After.

Workspace layout

crates/
  rago-core          models, enums, exact-money primitives
  rago-billing       aggregation, charge models, fees/taxes, invoices, subscriptions, wallets, credit notes
  rago-db            sqlx (Postgres) repositories + embedded migrations
  rago-api           axum REST v1/v2 + GraphQL mount + observability (bins: rago-api, rago-server)
  rago-graphql       async-graphql dashboard (queries, mutations, Relay)
  rago-jobs          durable job queue, scheduler, crons, worker (bins: rago-worker, rago-scheduler)
  rago-integrations  payment providers, webhooks, tax/accounting/CRM, OAuth — injectable transport
  rago-mail          transactional email builders + injectable transport (capture / SMTP)
  rago-documents     dependency-free PDF writer + invoice/credit-note/receipt + invoice XML
  rago-clickhouse    ClickHouse event store (parity with Postgres)

Build & test

cargo build --workspace --release       # whole product
cargo build --features live --bin rago-server   # live transports
cargo test --workspace                   # DB-less tests (pg suites skipped)
cargo clippy --workspace                 # lints

Running the tests

Fast gate — no database needed

cargo test --workspace          # unit + in-memory integration tests
cargo test --workspace --lib    # unit tests only (fastest)

The Postgres-backed suites are gated behind the opt-in pg-tests cargo feature, so a plain cargo test skips them cleanly instead of panicking on a missing DATABASE_URL.

Full gate — real Postgres (#[sqlx::test])

The money-correctness suites (idempotency guards, re-bill guard, charge-retry dedupe, aggregator parity, GraphQL admin, REST CRUD) run against a real, per-test isolated + migrated Postgres:

colima start                                    # macOS: bring up Docker first
docker compose up -d postgres                   # postgres:17 on :5432
export DATABASE_URL=postgres://postgres:postgres@localhost:5432/rago
cargo test --workspace --features pg-tests      # everything, incl. pg suites

Notes:

  • If another Postgres already owns :5432, pick a free host port: RAGO_PG_PORT=5439 docker compose up -d postgres and point DATABASE_URL at localhost:5439.
  • #[sqlx::test] creates a fresh migrated database per test, so the connected user needs CREATEDB rights — the compose postgres superuser is fine.
  • Per-crate runs also work: cargo test -p rago-jobs -F pg-tests.

Status

Rago is a functionally-complete, faithful Lago-compatible billing service: metering → subscriptions → usage pricing → invoicing (exact money) → payments → webhooks → documents → GraphQL/REST → analytics → integrations → durable jobs, with observability and a one-command run story. Remaining work is owner-gated live-credential wiring, operational hardening, and niche e-invoicing formats.