feat(rago): close the remaining Lago REST routes
Instant-fee estimates (single and batch) and enriched events; API logs recorded by middleware with secrets masked; security logs for API key, webhook endpoint and password events; activity log show; usage analytics; organization gRPC token; invoice/credit note document requests; flat quote-version routes; order form mark_as_signed. Webhook endpoints now store the requested signature algorithm, and jwt endpoints are delivered with an RS256 JWT (RAGO_RSA_PRIVATE_KEY) whose public key is served at /webhooks/public_key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5d4666f7bf
commit
70af9a6740
3
apps/rago/Cargo.lock
generated
3
apps/rago/Cargo.lock
generated
@ -2454,7 +2454,9 @@ dependencies = [
|
||||
"egress-guard",
|
||||
"hmac",
|
||||
"rago-core",
|
||||
"rand 0.8.8",
|
||||
"reqwest",
|
||||
"rsa",
|
||||
"rust_decimal",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@ -2769,6 +2771,7 @@ dependencies = [
|
||||
"pkcs1",
|
||||
"pkcs8",
|
||||
"rand_core 0.6.4",
|
||||
"sha2",
|
||||
"signature",
|
||||
"spki",
|
||||
"subtle",
|
||||
|
||||
257
apps/rago/crates/rago-api/src/lago_events.rs
Normal file
257
apps/rago/crates/rago-api/src/lago_events.rs
Normal file
@ -0,0 +1,257 @@
|
||||
//! Lago REST parity for events:
|
||||
//!
|
||||
//! * `POST /events/estimate_instant_fees` and `/events/batch_estimate_instant_fees`
|
||||
//! (`Fees::EstimateInstant::*`): what an event would cost on the
|
||||
//! subscription's pay-in-advance standard and percentage charges, priced at
|
||||
//! the event's charge filter, without storing anything;
|
||||
//! * `GET /events_enriched`: the subscription's events as each charge reads
|
||||
//! them (value, charge, filter, pricing group), the Postgres twin of Lago's
|
||||
//! enriched-events store.
|
||||
|
||||
use axum::extract::{Query, State};
|
||||
use axum::Json;
|
||||
use chrono::{NaiveDateTime, Utc};
|
||||
use rago_billing::charge_fees::{buckets, FilterSpec};
|
||||
use rago_core::models::{BillableMetric, Charge, Event, Subscription};
|
||||
use rust_decimal::Decimal;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::auth::Authed;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::handlers::{req_s, s};
|
||||
use crate::state::AppState;
|
||||
|
||||
async fn subscription(st: &AppState, org: Uuid, external_id: &str) -> ApiResult<Subscription> {
|
||||
st.db.find_subscription_by_external_id(org, external_id).await?.ok_or_else(|| ApiError::NotFound("subscription".into()))
|
||||
}
|
||||
|
||||
/// The units one event carries for a metric (Lago: the field value, or 1
|
||||
/// when the metric has no field), rounded like the metric.
|
||||
fn event_units(metric: &BillableMetric, event: &Event) -> Decimal {
|
||||
let units = match metric.field_name.as_deref().filter(|f| !f.is_empty()) {
|
||||
Some(f) => event.field_value(f),
|
||||
None => Decimal::ONE,
|
||||
};
|
||||
let precision = metric.rounding_precision.unwrap_or(0).max(0) as u32;
|
||||
match metric.rounding_function.as_deref() {
|
||||
Some("ceil") => rago_billing::aggregation::ceil_dp(units, precision),
|
||||
Some("floor") => rago_billing::aggregation::floor_dp(units, precision),
|
||||
Some("round") => units.round_dp_with_strategy(precision, rust_decimal::RoundingStrategy::MidpointAwayFromZero),
|
||||
_ => units,
|
||||
}
|
||||
}
|
||||
|
||||
/// The filter an event falls in for a charge (`None`: the default bucket),
|
||||
/// with the properties it is priced at and its pricing group values.
|
||||
fn bucket_of(charge: &Charge, filters: &[FilterSpec], event: &Event) -> (Option<Uuid>, Value, Value) {
|
||||
let all = buckets(charge, filters);
|
||||
let bucket = all.iter().find(|b| b.filter_id.is_some() && b.contains(event)).or_else(|| all.iter().find(|b| b.filter_id.is_none()));
|
||||
match bucket {
|
||||
Some(b) => {
|
||||
let grouped: serde_json::Map<String, Value> = b
|
||||
.group_keys
|
||||
.iter()
|
||||
.map(|k| (k.clone(), event.properties.get(k).cloned().unwrap_or(Value::Null)))
|
||||
.collect();
|
||||
(b.filter_id, b.properties.clone(), Value::Object(grouped))
|
||||
}
|
||||
None => (None, charge.properties.clone(), json!({})),
|
||||
}
|
||||
}
|
||||
|
||||
fn event_from(org: Uuid, sub: &Subscription, raw: &Value) -> ApiResult<Event> {
|
||||
let now = Utc::now();
|
||||
Ok(Event {
|
||||
id: Uuid::new_v4(),
|
||||
organization_id: org,
|
||||
customer_id: Some(sub.customer_id),
|
||||
subscription_id: Some(sub.id),
|
||||
transaction_id: s(raw, "transaction_id").unwrap_or_else(|| Uuid::new_v4().to_string()),
|
||||
code: req_s(raw, "code")?,
|
||||
properties: match raw.get("properties") {
|
||||
Some(p @ Value::Object(_)) => p.clone(),
|
||||
None | Some(Value::Null) => json!({}),
|
||||
Some(_) => return Err(ApiError::validation("properties", "value_is_invalid")),
|
||||
},
|
||||
external_customer_id: None,
|
||||
external_subscription_id: Some(sub.external_id.clone()),
|
||||
timestamp: Some(now.naive_utc()),
|
||||
precise_total_amount_cents: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
deleted_at: None,
|
||||
persisted: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// One estimated fee (Lago's instant-fee payload).
|
||||
async fn estimate(st: &AppState, sub: &Subscription, plan_currency: &rago_core::money::Currency, charge: &Charge, metric: &BillableMetric, event: Event) -> ApiResult<Value> {
|
||||
let event = rago_billing::events::with_expression(Some(metric), event).map_err(|e| ApiError::Validation(json!({ "event": [format!("expression_evaluation_failed: {e}")] })))?;
|
||||
let filters = st.db.charge_filter_specs(charge.id).await?;
|
||||
let (filter_id, properties, _) = bucket_of(charge, &filters, &event);
|
||||
let units = event_units(metric, &event);
|
||||
let amount = rago_billing::instant::instant_amount(charge.charge_model, &properties, units).unwrap_or_default();
|
||||
let exponent = plan_currency.exponent();
|
||||
let rounded = amount.round_dp_with_strategy(exponent, rust_decimal::RoundingStrategy::MidpointAwayFromZero);
|
||||
let subunit = plan_currency.subunit_to_unit_decimal();
|
||||
let amount_cents: i64 = (rounded * subunit).trunc().try_into().unwrap_or(0);
|
||||
let unit_amount = if rounded.is_zero() || units.is_zero() { Decimal::ZERO } else { rounded / units };
|
||||
let external_customer_id = st.db.customer_external_id(sub.customer_id).await?;
|
||||
Ok(json!({
|
||||
"lago_id": null,
|
||||
"lago_charge_id": charge.id,
|
||||
"lago_charge_filter_id": filter_id,
|
||||
"lago_invoice_id": null,
|
||||
"lago_subscription_id": sub.id,
|
||||
"external_subscription_id": sub.external_id,
|
||||
"lago_customer_id": sub.customer_id,
|
||||
"external_customer_id": external_customer_id,
|
||||
"item": {
|
||||
"type": "charge",
|
||||
"code": metric.code,
|
||||
"name": metric.name,
|
||||
"invoice_display_name": charge.invoice_display_name.clone().unwrap_or_else(|| metric.name.clone()),
|
||||
"lago_item_id": metric.id,
|
||||
"item_type": "BillableMetric",
|
||||
"grouped_by": {},
|
||||
},
|
||||
"pay_in_advance": true,
|
||||
"invoiceable": charge.invoiceable,
|
||||
"amount_cents": amount_cents,
|
||||
"amount_currency": plan_currency.code(),
|
||||
"precise_amount": amount.normalize().to_string(),
|
||||
"total_amount_cents": amount_cents,
|
||||
"taxes_amount_cents": 0,
|
||||
"units": units.normalize().to_string(),
|
||||
"precise_unit_amount": (unit_amount * subunit).normalize().to_string(),
|
||||
"events_count": 1,
|
||||
"payment_status": "pending",
|
||||
"event_transaction_id": event.transaction_id,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The subscription's instant charges with their metrics.
|
||||
async fn instant_charges(st: &AppState, sub: &Subscription) -> ApiResult<Vec<(Charge, BillableMetric)>> {
|
||||
let mut out = Vec::new();
|
||||
for c in st.db.charges_for_plan(sub.plan_id).await? {
|
||||
if !c.pay_in_advance || !rago_billing::instant::is_instant(c.charge_model) {
|
||||
continue;
|
||||
}
|
||||
let Some(mid) = c.billable_metric_id else { continue };
|
||||
let m = st.db.find_billable_metric(mid).await?;
|
||||
out.push((c, m));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `POST /events/estimate_instant_fees` — `{ event: { code, external_subscription_id, properties } }`.
|
||||
pub async fn estimate_instant_fees(State(st): State<AppState>, auth: Authed, Json(body): Json<Value>) -> ApiResult<Json<Value>> {
|
||||
let org = auth.organization.id;
|
||||
let e = body.get("event").unwrap_or(&body);
|
||||
let sub = subscription(&st, org, &req_s(e, "external_subscription_id")?).await?;
|
||||
let plan = st.db.find_plan(sub.plan_id).await?;
|
||||
let event = event_from(org, &sub, e)?;
|
||||
let matched: Vec<(Charge, BillableMetric)> = instant_charges(&st, &sub).await?.into_iter().filter(|(_, m)| m.code == event.code).collect();
|
||||
if matched.is_empty() {
|
||||
return Err(ApiError::validation("code", "does_not_match_an_instant_charge"));
|
||||
}
|
||||
let mut fees = Vec::new();
|
||||
for (c, m) in &matched {
|
||||
fees.push(estimate(&st, &sub, &plan.currency(), c, m, event.clone()).await?);
|
||||
}
|
||||
Ok(Json(json!({ "fees": fees })))
|
||||
}
|
||||
|
||||
/// `POST /events/batch_estimate_instant_fees` — `{ events: [...] }` on one subscription.
|
||||
pub async fn batch_estimate_instant_fees(State(st): State<AppState>, auth: Authed, Json(body): Json<Value>) -> ApiResult<Json<Value>> {
|
||||
let org = auth.organization.id;
|
||||
let events = body.get("events").and_then(Value::as_array).filter(|e| !e.is_empty()).ok_or_else(|| ApiError::validation("events", "value_is_mandatory"))?;
|
||||
if events.len() > 100 {
|
||||
return Err(ApiError::validation("events", "too_many_events"));
|
||||
}
|
||||
let sub_ext = req_s(&events[0], "external_subscription_id")?;
|
||||
if events.iter().any(|e| s(e, "external_subscription_id").as_deref() != Some(sub_ext.as_str())) {
|
||||
return Err(ApiError::validation("external_subscription_id", "all_events_must_share_one_subscription"));
|
||||
}
|
||||
let sub = subscription(&st, org, &sub_ext).await?;
|
||||
let plan = st.db.find_plan(sub.plan_id).await?;
|
||||
let charges = instant_charges(&st, &sub).await?;
|
||||
if charges.is_empty() {
|
||||
return Err(ApiError::validation("code", "does_not_match_an_instant_charge"));
|
||||
}
|
||||
let mut fees = Vec::new();
|
||||
for raw in events {
|
||||
let event = event_from(org, &sub, raw)?;
|
||||
for (c, m) in charges.iter().filter(|(_, m)| m.code == event.code) {
|
||||
fees.push(estimate(&st, &sub, &plan.currency(), c, m, event.clone()).await?);
|
||||
}
|
||||
}
|
||||
Ok(Json(json!({ "fees": fees })))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct EnrichedQuery {
|
||||
pub external_subscription_id: Option<String>,
|
||||
pub code: Option<String>,
|
||||
pub timestamp_from: Option<String>,
|
||||
pub timestamp_to: Option<String>,
|
||||
pub page: Option<i64>,
|
||||
pub per_page: Option<i64>,
|
||||
}
|
||||
|
||||
fn at(raw: Option<&str>) -> ApiResult<Option<NaiveDateTime>> {
|
||||
match raw {
|
||||
None | Some("") => Ok(None),
|
||||
Some(v) => chrono::DateTime::parse_from_rfc3339(v)
|
||||
.map(|d| Some(d.naive_utc()))
|
||||
.map_err(|_| ApiError::validation("timestamp", "invalid_format")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /events_enriched?external_subscription_id=&code=×tamp_from=×tamp_to=`.
|
||||
pub async fn events_enriched(State(st): State<AppState>, auth: Authed, Query(q): Query<EnrichedQuery>) -> ApiResult<Json<Value>> {
|
||||
let org = auth.organization.id;
|
||||
let ext = q.external_subscription_id.as_deref().filter(|s| !s.is_empty()).ok_or_else(|| ApiError::validation("external_subscription_id", "value_is_mandatory"))?;
|
||||
let sub = subscription(&st, org, ext).await?;
|
||||
let from = at(q.timestamp_from.as_deref())?.unwrap_or_default();
|
||||
let to = at(q.timestamp_to.as_deref())?.unwrap_or_else(|| Utc::now().naive_utc());
|
||||
let per_page = q.per_page.unwrap_or(100).clamp(1, 1000);
|
||||
let page = q.page.unwrap_or(1).max(1);
|
||||
let mut rows = Vec::new();
|
||||
for c in st.db.charges_for_plan(sub.plan_id).await? {
|
||||
let Some(mid) = c.billable_metric_id else { continue };
|
||||
let metric = st.db.find_billable_metric(mid).await?;
|
||||
if q.code.as_deref().is_some_and(|code| code != metric.code) {
|
||||
continue;
|
||||
}
|
||||
let filters = st.db.charge_filter_specs(c.id).await?;
|
||||
for e in st.db.events_for_external_subscription(org, &sub.external_id, &metric.code, from, to).await? {
|
||||
let (filter_id, _, grouped) = bucket_of(&c, &filters, &e);
|
||||
let value = event_units(&metric, &e);
|
||||
rows.push((
|
||||
e.timestamp,
|
||||
json!({
|
||||
"transaction_id": e.transaction_id,
|
||||
"lago_subscription_id": sub.id,
|
||||
"external_subscription_id": sub.external_id,
|
||||
"code": e.code,
|
||||
"timestamp": e.timestamp.map(|t| t.and_utc().to_rfc3339()),
|
||||
"properties": e.properties,
|
||||
"value": value.normalize().to_string(),
|
||||
"decimal_value": value.normalize().to_string(),
|
||||
"lago_charge_id": c.id,
|
||||
"lago_charge_filter_id": filter_id,
|
||||
"grouped_by": grouped,
|
||||
"enriched_at": e.created_at.to_rfc3339(),
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
rows.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
let total = rows.len() as i64;
|
||||
let start = ((page - 1) * per_page) as usize;
|
||||
let events: Vec<Value> = rows.into_iter().skip(start).take(per_page as usize).map(|(_, v)| v).collect();
|
||||
Ok(Json(json!({ "events": events, "meta": crate::pagination::meta(page, per_page, total) })))
|
||||
}
|
||||
401
apps/rago/crates/rago-api/src/lago_logs.rs
Normal file
401
apps/rago/crates/rago-api/src/lago_logs.rs
Normal file
@ -0,0 +1,401 @@
|
||||
//! Lago REST routes for audit logs, usage analytics and document/quote aliases:
|
||||
//! `GET /activity_logs/:id`, `/api_logs(/:request_id)`, `/security_logs(/:id)`,
|
||||
//! `GET /analytics/usage`, `GET /organizations/grpc_token`, the
|
||||
//! `POST /invoices/:id/download_pdf|download_xml` and
|
||||
//! `POST /credit_notes/:id/download_pdf` document requests, and the flat
|
||||
//! `quote_versions` routes. The API-log recorder middleware lives here too.
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{OriginalUri, Path, Query, Request, State};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::Response;
|
||||
use axum::Json;
|
||||
use chrono::{Duration, NaiveDate, Utc};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::auth::Authed;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::pagination::{self, PageParams};
|
||||
use crate::state::AppState;
|
||||
|
||||
// ---- activity logs ---------------------------------------------------------
|
||||
|
||||
/// `GET /activity_logs/:activity_id`.
|
||||
pub async fn show_activity_log(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let log = st
|
||||
.db
|
||||
.find_activity_log(auth.organization.id, id)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::NotFound("activity_log".into()))?;
|
||||
Ok(Json(json!({ "activity_log": log })))
|
||||
}
|
||||
|
||||
// ---- api logs ----------------------------------------------------------------
|
||||
|
||||
fn api_log_json(r: &rago_db::rest_parity::ApiLogRow) -> Value {
|
||||
json!({
|
||||
"request_id": r.request_id,
|
||||
"api_key_id": r.api_key_id,
|
||||
"api_version": r.api_version,
|
||||
"http_method": r.http_method,
|
||||
"http_status": r.http_status,
|
||||
"request_path": r.request_path,
|
||||
"request_origin": r.request_origin,
|
||||
"client": r.client,
|
||||
"request_body": r.request_body,
|
||||
"logged_at": r.created_at.and_utc().to_rfc3339(),
|
||||
"created_at": r.created_at.and_utc().to_rfc3339(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `GET /api_logs`.
|
||||
pub async fn list_api_logs(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Query(pg): Query<PageParams>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let (rows, total) = st.db.list_api_logs(auth.organization.id, pg.per_page(), pg.offset()).await?;
|
||||
Ok(Json(json!({
|
||||
"api_logs": rows.iter().map(api_log_json).collect::<Vec<_>>(),
|
||||
"meta": pagination::meta(pg.page(), pg.per_page(), total),
|
||||
})))
|
||||
}
|
||||
|
||||
/// `GET /api_logs/:request_id`.
|
||||
pub async fn show_api_log(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Path(request_id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = st
|
||||
.db
|
||||
.find_api_log(auth.organization.id, request_id)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::NotFound("api_log".into()))?;
|
||||
Ok(Json(json!({ "api_log": api_log_json(&row) })))
|
||||
}
|
||||
|
||||
/// Keys whose values never reach the API log.
|
||||
const SECRET_KEYS: [&str; 7] = ["password", "secret", "token", "api_key", "hmac", "private_key", "authorization"];
|
||||
/// The largest request body kept in the API log.
|
||||
const MAX_LOGGED_BODY: usize = 64 * 1024;
|
||||
|
||||
/// A request body with secret-looking fields replaced by `[FILTERED]`.
|
||||
pub fn mask_secrets(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::Object(map) => Value::Object(
|
||||
map.iter()
|
||||
.map(|(k, v)| {
|
||||
let lower = k.to_lowercase();
|
||||
let masked = if SECRET_KEYS.iter().any(|s| lower.contains(s)) {
|
||||
Value::String("[FILTERED]".into())
|
||||
} else {
|
||||
mask_secrets(v)
|
||||
};
|
||||
(k.clone(), masked)
|
||||
})
|
||||
.collect::<Map<_, _>>(),
|
||||
),
|
||||
Value::Array(items) => Value::Array(items.iter().map(mask_secrets).collect()),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Middleware: record every mutating API request (Lago `ApiLog`) after it
|
||||
/// runs, with the caller's key, status, path and a secret-masked body.
|
||||
pub async fn record_api_log(State(st): State<AppState>, req: Request, next: Next) -> Response {
|
||||
let method = req.method().clone();
|
||||
if !matches!(method.as_str(), "POST" | "PUT" | "PATCH" | "DELETE") {
|
||||
return next.run(req).await;
|
||||
}
|
||||
let path = req
|
||||
.extensions()
|
||||
.get::<OriginalUri>()
|
||||
.map(|u| u.0.path().to_string())
|
||||
.unwrap_or_else(|| req.uri().path().to_string());
|
||||
let (token, origin, client) = {
|
||||
let header = |name: &str| req.headers().get(name).and_then(|v| v.to_str().ok()).map(str::to_string);
|
||||
(
|
||||
header("authorization").and_then(|v| v.strip_prefix("Bearer ").map(str::to_string)),
|
||||
header("origin"),
|
||||
header("user-agent"),
|
||||
)
|
||||
};
|
||||
let (parts, body) = req.into_parts();
|
||||
let Ok(bytes) = axum::body::to_bytes(body, MAX_LOGGED_BODY * 16).await else {
|
||||
return Response::builder().status(413).body(Body::from("request body too large")).unwrap_or_default();
|
||||
};
|
||||
let logged_body = (bytes.len() <= MAX_LOGGED_BODY)
|
||||
.then(|| serde_json::from_slice::<Value>(&bytes).ok())
|
||||
.flatten()
|
||||
.map(|v| mask_secrets(&v));
|
||||
let response = next.run(Request::from_parts(parts, Body::from(bytes))).await;
|
||||
|
||||
let Some(token) = token else { return response };
|
||||
match crate::auth::resolve_bearer(&st, &token).await {
|
||||
Ok(Some((key, org))) => {
|
||||
let version = if path.starts_with("/api/v2") { "v2" } else { "v1" };
|
||||
let status = i32::from(response.status().as_u16());
|
||||
if let Err(e) = st
|
||||
.db
|
||||
.insert_api_log(
|
||||
org.id,
|
||||
Uuid::new_v4(),
|
||||
Some(key.id),
|
||||
version,
|
||||
method.as_str(),
|
||||
status,
|
||||
&path,
|
||||
origin.as_deref(),
|
||||
client.as_deref(),
|
||||
logged_body.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "api log write failed");
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(error = ?e, "api log: bearer resolution failed"),
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
// ---- security logs ---------------------------------------------------------
|
||||
|
||||
fn security_log_json(r: &rago_db::rest_parity::SecurityLogRow) -> Value {
|
||||
json!({
|
||||
"log_id": r.id,
|
||||
"log_type": r.log_type,
|
||||
"log_event": r.log_event,
|
||||
"user_id": r.user_id,
|
||||
"api_key_id": r.api_key_id,
|
||||
"resources": r.resources,
|
||||
"device_info": r.device_info,
|
||||
"logged_at": r.created_at.and_utc().to_rfc3339(),
|
||||
"created_at": r.created_at.and_utc().to_rfc3339(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `GET /security_logs`.
|
||||
pub async fn list_security_logs(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Query(pg): Query<PageParams>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let (rows, total) = st.db.list_security_logs(auth.organization.id, pg.per_page(), pg.offset()).await?;
|
||||
Ok(Json(json!({
|
||||
"security_logs": rows.iter().map(security_log_json).collect::<Vec<_>>(),
|
||||
"meta": pagination::meta(pg.page(), pg.per_page(), total),
|
||||
})))
|
||||
}
|
||||
|
||||
/// `GET /security_logs/:log_id`.
|
||||
pub async fn show_security_log(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = st
|
||||
.db
|
||||
.find_security_log(auth.organization.id, id)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::NotFound("security_log".into()))?;
|
||||
Ok(Json(json!({ "security_log": security_log_json(&row) })))
|
||||
}
|
||||
|
||||
// ---- usage analytics -------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Deserialize, Default)]
|
||||
pub struct UsageParams {
|
||||
pub from_date: Option<NaiveDate>,
|
||||
pub to_date: Option<NaiveDate>,
|
||||
pub external_subscription_id: Option<String>,
|
||||
}
|
||||
|
||||
/// The longest window `GET /analytics/usage` serves, in days.
|
||||
const MAX_USAGE_DAYS: i64 = 366;
|
||||
|
||||
/// `GET /analytics/usage` — daily usage amounts (default: the last 30 days).
|
||||
pub async fn usage_analytics(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Query(q): Query<UsageParams>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let to = q.to_date.unwrap_or_else(|| Utc::now().date_naive());
|
||||
let from = q.from_date.unwrap_or(to - Duration::days(30));
|
||||
if from > to || (to - from).num_days() > MAX_USAGE_DAYS {
|
||||
return Err(ApiError::validation("from_date", "invalid_date_range"));
|
||||
}
|
||||
let rows = st
|
||||
.db
|
||||
.daily_usage(auth.organization.id, from, to, q.external_subscription_id.as_deref())
|
||||
.await?;
|
||||
let currency = auth.organization.default_currency.clone();
|
||||
let usages: Vec<Value> = rows
|
||||
.iter()
|
||||
.map(|(day, sub, cents)| {
|
||||
json!({
|
||||
"start_of_period_dt": day,
|
||||
"end_of_period_dt": day,
|
||||
"external_subscription_id": sub,
|
||||
"amount_currency": currency,
|
||||
"amount_cents": cents,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "usages": usages })))
|
||||
}
|
||||
|
||||
// ---- organization grpc token ------------------------------------------------
|
||||
|
||||
/// `GET /organizations/grpc_token`.
|
||||
pub async fn grpc_token(auth: Authed) -> ApiResult<Json<Value>> {
|
||||
let token = rago_graphql::auth::issue_grpc_jwt(auth.organization.id);
|
||||
Ok(Json(json!({ "organization": { "grpc_token": token } })))
|
||||
}
|
||||
|
||||
// ---- document requests ---------------------------------------------------------
|
||||
|
||||
/// The public base URL documents are served from (`RAGO_API_URL`, else relative).
|
||||
fn api_base() -> String {
|
||||
std::env::var("RAGO_API_URL")
|
||||
.or_else(|_| std::env::var("LAGO_API_URL"))
|
||||
.map(|u| u.trim_end_matches('/').to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn invoice_with_url(st: &AppState, id: Uuid, key: &str, suffix: &str) -> ApiResult<Json<Value>> {
|
||||
let inv = st.db.find_invoice(id).await?.ok_or_else(|| ApiError::NotFound("invoice".into()))?;
|
||||
let fees = st.db.fees_for_invoice(inv.id).await?;
|
||||
let mut body = crate::serializers::invoice(&inv, &fees);
|
||||
body[key] = json!(format!("{}/api/v1/invoices/{id}/{suffix}", api_base()));
|
||||
Ok(Json(json!({ "invoice": body })))
|
||||
}
|
||||
|
||||
/// `POST /invoices/:id/download_pdf` — the invoice with its `file_url`
|
||||
/// (documents render on demand, so the URL is ready immediately).
|
||||
pub async fn invoice_download_pdf(
|
||||
State(st): State<AppState>,
|
||||
_auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
invoice_with_url(&st, id, "file_url", "download").await
|
||||
}
|
||||
|
||||
/// `POST /invoices/:id/download_xml` — the invoice with its `xml_url`.
|
||||
pub async fn invoice_download_xml(
|
||||
State(st): State<AppState>,
|
||||
_auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
invoice_with_url(&st, id, "xml_url", "download.xml").await
|
||||
}
|
||||
|
||||
/// `POST /credit_notes/:id/download_pdf` — the credit note with its `file_url`.
|
||||
pub async fn credit_note_download_pdf(
|
||||
State(st): State<AppState>,
|
||||
_auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let cn = st.db.find_credit_note(id).await?.ok_or_else(|| ApiError::NotFound("credit_note".into()))?;
|
||||
let mut body = crate::serializers::credit_note(&cn);
|
||||
body["file_url"] = json!(format!("{}/api/v1/credit_notes/{id}/download", api_base()));
|
||||
Ok(Json(json!({ "credit_note": body })))
|
||||
}
|
||||
|
||||
// ---- flat quote-version routes ------------------------------------------------
|
||||
|
||||
async fn version_quote(st: &AppState, org: Uuid, id: Uuid) -> ApiResult<Uuid> {
|
||||
st.db
|
||||
.quote_version_detail(org, id)
|
||||
.await?
|
||||
.map(|v| v.quote_id)
|
||||
.ok_or_else(|| ApiError::NotFound("quote_version".into()))
|
||||
}
|
||||
|
||||
/// `GET /quotes/:id/versions`.
|
||||
pub async fn list_quote_versions(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let org = auth.organization.id;
|
||||
st.db.quote_detail(org, id).await?.ok_or_else(|| ApiError::NotFound("quote".into()))?;
|
||||
let versions = st.db.quote_version_details(org, id).await?;
|
||||
Ok(Json(json!({
|
||||
"quote_versions": versions.iter().map(crate::order_flow::version_json).collect::<Vec<_>>(),
|
||||
})))
|
||||
}
|
||||
|
||||
/// `GET /quote_versions/:id`.
|
||||
pub async fn show_quote_version(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let v = st
|
||||
.db
|
||||
.quote_version_detail(auth.organization.id, id)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::NotFound("quote_version".into()))?;
|
||||
Ok(Json(json!({ "quote_version": crate::order_flow::version_json(&v) })))
|
||||
}
|
||||
|
||||
/// `POST /quote_versions/:id/approve`.
|
||||
pub async fn approve_quote_version(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
body: Option<Json<Value>>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let quote = version_quote(&st, auth.organization.id, id).await?;
|
||||
crate::order_flow::approve_version(State(st), auth, Path((quote, id)), body).await
|
||||
}
|
||||
|
||||
/// `POST /quote_versions/:id/void`.
|
||||
pub async fn void_quote_version(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let quote = version_quote(&st, auth.organization.id, id).await?;
|
||||
crate::order_flow::void_version(State(st), auth, Path((quote, id))).await
|
||||
}
|
||||
|
||||
/// `POST /quote_versions/:id/clone` — a new draft copied from this version.
|
||||
pub async fn clone_quote_version(
|
||||
State(st): State<AppState>,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let org = auth.organization.id;
|
||||
let quote = version_quote(&st, org, id).await?;
|
||||
let body = crate::order_flow::NewVersionBody { from_version_id: Some(id) };
|
||||
crate::order_flow::create_version(State(st), auth, Path(quote), Some(Json(body))).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn secrets_are_masked_at_any_depth() {
|
||||
let body = json!({
|
||||
"customer": { "name": "A", "api_key": "k", "nested": [{ "password": "p" }] },
|
||||
"webhook": { "hmac_key": "h", "url": "u" },
|
||||
});
|
||||
let m = mask_secrets(&body);
|
||||
assert_eq!(m["customer"]["name"], "A");
|
||||
assert_eq!(m["customer"]["api_key"], "[FILTERED]");
|
||||
assert_eq!(m["customer"]["nested"][0]["password"], "[FILTERED]");
|
||||
assert_eq!(m["webhook"]["hmac_key"], "[FILTERED]");
|
||||
assert_eq!(m["webhook"]["url"], "u");
|
||||
}
|
||||
}
|
||||
@ -23,6 +23,8 @@ pub mod crud;
|
||||
pub mod customer_lists;
|
||||
pub mod emit;
|
||||
pub mod error;
|
||||
pub mod lago_events;
|
||||
pub mod lago_logs;
|
||||
pub mod lago_plans;
|
||||
pub mod lago_wallets;
|
||||
pub mod fixed_charges;
|
||||
@ -163,7 +165,7 @@ pub fn router(state: AppState) -> Router {
|
||||
.route("/quotes/:id", get(order_flow::show_quote))
|
||||
.route("/quotes/:id/accept", post(breadth::accept_quote))
|
||||
.route("/quotes/:id/void", post(order_flow::void_quote))
|
||||
.route("/quotes/:id/versions", post(order_flow::create_version))
|
||||
.route("/quotes/:id/versions", post(order_flow::create_version).get(lago_logs::list_quote_versions))
|
||||
.route("/quotes/:id/versions/:version_id", put(order_flow::update_version))
|
||||
.route("/quotes/:id/versions/:version_id/approve", post(order_flow::approve_version))
|
||||
.route("/quotes/:id/versions/:version_id/void", post(order_flow::void_version))
|
||||
@ -308,6 +310,26 @@ pub fn router(state: AppState) -> Router {
|
||||
.route("/wallet_transactions/:id/consumptions", get(lago_wallets::wallet_transaction_consumptions))
|
||||
.route("/wallet_transactions/:id/fundings", get(lago_wallets::wallet_transaction_fundings))
|
||||
.route("/wallets/:id/wallet_transactions", get(lago_wallets::wallet_wallet_transactions))
|
||||
.route("/events/estimate_instant_fees", post(lago_events::estimate_instant_fees))
|
||||
.route("/events/batch_estimate_instant_fees", post(lago_events::batch_estimate_instant_fees))
|
||||
.route("/events_enriched", get(lago_events::events_enriched))
|
||||
.route("/activity_logs/:id", get(lago_logs::show_activity_log))
|
||||
.route("/api_logs", get(lago_logs::list_api_logs))
|
||||
.route("/api_logs/:request_id", get(lago_logs::show_api_log))
|
||||
.route("/security_logs", get(lago_logs::list_security_logs))
|
||||
.route("/security_logs/:id", get(lago_logs::show_security_log))
|
||||
.route("/analytics/usage", get(lago_logs::usage_analytics))
|
||||
.route("/organizations/grpc_token", get(lago_logs::grpc_token))
|
||||
.route("/webhooks/public_key", get(resources::webhooks_public_key))
|
||||
.route("/webhooks/json_public_key", get(resources::webhooks_json_public_key))
|
||||
.route("/invoices/:id/download_pdf", post(lago_logs::invoice_download_pdf))
|
||||
.route("/invoices/:id/download_xml", post(lago_logs::invoice_download_xml))
|
||||
.route("/credit_notes/:id/download_pdf", post(lago_logs::credit_note_download_pdf))
|
||||
.route("/order_forms/:id/mark_as_signed", post(order_flow::sign_order_form))
|
||||
.route("/quote_versions/:id", get(lago_logs::show_quote_version))
|
||||
.route("/quote_versions/:id/approve", post(lago_logs::approve_quote_version))
|
||||
.route("/quote_versions/:id/void", post(lago_logs::void_quote_version))
|
||||
.route("/quote_versions/:id/clone", post(lago_logs::clone_quote_version))
|
||||
.route("/customers/:external_id/payment_methods", get(payments::customer_payment_methods))
|
||||
.route("/payment_receipts/:invoice_id/resend_email", post(payments::resend_payment_receipt))
|
||||
// --- v1 analytics (data API)
|
||||
@ -336,8 +358,12 @@ pub fn router(state: AppState) -> Router {
|
||||
.route("/applied_rate_cards/:id/rate_phases", post(catalog_v2::create_rate_phase).get(catalog_v2::list_rate_phases));
|
||||
|
||||
// Tenant isolation: reject any request referencing another org's record ids.
|
||||
let v1 = v1.layer(axum::middleware::from_fn_with_state(state.clone(), tenancy::guard));
|
||||
let v2 = v2.layer(axum::middleware::from_fn_with_state(state.clone(), tenancy::guard));
|
||||
let v1 = v1
|
||||
.layer(axum::middleware::from_fn_with_state(state.clone(), tenancy::guard))
|
||||
.layer(axum::middleware::from_fn_with_state(state.clone(), lago_logs::record_api_log));
|
||||
let v2 = v2
|
||||
.layer(axum::middleware::from_fn_with_state(state.clone(), tenancy::guard))
|
||||
.layer(axum::middleware::from_fn_with_state(state.clone(), lago_logs::record_api_log));
|
||||
|
||||
Router::new()
|
||||
.route("/health", get(health))
|
||||
|
||||
@ -60,7 +60,7 @@ fn quote_json(q: &QuoteDetail) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
fn version_json(v: &QuoteVersionDetail) -> Value {
|
||||
pub(crate) fn version_json(v: &QuoteVersionDetail) -> Value {
|
||||
json!({
|
||||
"lago_id": v.id,
|
||||
"lago_quote_id": v.quote_id,
|
||||
|
||||
@ -125,6 +125,32 @@ fn webhook_endpoint_json(id: Uuid, url: &str, algo: &str) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// A requested `signature_algo`: `hmac`, or `jwt` when the deployment has an
|
||||
/// RSA key (`RAGO_RSA_PRIVATE_KEY`) to sign with.
|
||||
fn signature_algo(requested: Option<&str>) -> ApiResult<Option<&'static str>> {
|
||||
match requested {
|
||||
None => Ok(None),
|
||||
Some("hmac") => Ok(Some("hmac")),
|
||||
Some("jwt") if rago_integrations::webhooks::JwtSigner::global().is_some() => Ok(Some("jwt")),
|
||||
Some("jwt") => Err(ApiError::Validation(json!({ "signature_algo": ["jwt_signing_not_configured"] }))),
|
||||
Some(_) => Err(ApiError::Validation(json!({ "signature_algo": ["value_is_invalid"] }))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /webhooks/public_key` — base64 of the RS256 public key PEM (Lago's
|
||||
/// shape), so receivers can verify `jwt` signatures. 404 without a key.
|
||||
pub async fn webhooks_public_key(_auth: Authed) -> ApiResult<String> {
|
||||
rago_integrations::webhooks::JwtSigner::global()
|
||||
.map(|s| s.public_key_base64())
|
||||
.ok_or_else(|| ApiError::NotFound("public_key".into()))
|
||||
}
|
||||
|
||||
/// `GET /webhooks/json_public_key` — the same key as `{ webhook: { public_key } }`.
|
||||
pub async fn webhooks_json_public_key(auth: Authed) -> ApiResult<Json<Value>> {
|
||||
let key = webhooks_public_key(auth).await?;
|
||||
Ok(Json(json!({ "webhook": { "public_key": key } })))
|
||||
}
|
||||
|
||||
/// `POST /webhook_endpoints` — register an outbound webhook endpoint.
|
||||
pub async fn create_webhook_endpoint(
|
||||
State(st): State<AppState>,
|
||||
@ -133,8 +159,11 @@ pub async fn create_webhook_endpoint(
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let p = wrapped(&body, "webhook_endpoint");
|
||||
let url = req_s(p, "webhook_url")?;
|
||||
let id = st.db.insert_webhook_endpoint_returning(auth.organization.id, &url).await?;
|
||||
let algo = s(p, "signature_algo").unwrap_or_else(|| "jwt".into());
|
||||
let algo = signature_algo(s(p, "signature_algo").as_deref())?.unwrap_or("hmac");
|
||||
let id = st.db.insert_webhook_endpoint_with_algo(auth.organization.id, &url, algo).await?;
|
||||
st.db
|
||||
.record_security_event(auth.organization.id, "webhook_endpoint", "webhook_endpoint.created", None, Some(auth.api_key.id), json!({ "webhook_url": url, "signature_algo": algo }))
|
||||
.await;
|
||||
Ok(Json(json!({ "webhook_endpoint": webhook_endpoint_json(id, &url, &algo) })))
|
||||
}
|
||||
|
||||
@ -162,23 +191,26 @@ pub async fn show_webhook_endpoint(
|
||||
/// `PUT /webhook_endpoints/:id` — update the URL / signature algorithm.
|
||||
pub async fn update_webhook_endpoint(
|
||||
State(st): State<AppState>,
|
||||
_auth: Authed,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<Value>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let p = wrapped(&body, "webhook_endpoint");
|
||||
let (id, url, algo) = st
|
||||
.db
|
||||
.update_webhook_endpoint(id, s(p, "webhook_url").as_deref(), s(p, "signature_algo").as_deref())
|
||||
.update_webhook_endpoint(id, s(p, "webhook_url").as_deref(), signature_algo(s(p, "signature_algo").as_deref())?)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::NotFound("webhook_endpoint".into()))?;
|
||||
st.db
|
||||
.record_security_event(auth.organization.id, "webhook_endpoint", "webhook_endpoint.updated", None, Some(auth.api_key.id), json!({ "webhook_url": url, "signature_algo": algo }))
|
||||
.await;
|
||||
Ok(Json(json!({ "webhook_endpoint": webhook_endpoint_json(id, &url, &algo) })))
|
||||
}
|
||||
|
||||
/// `DELETE /webhook_endpoints/:id` — remove an endpoint.
|
||||
pub async fn destroy_webhook_endpoint(
|
||||
State(st): State<AppState>,
|
||||
_auth: Authed,
|
||||
auth: Authed,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let (id, url, algo) = st
|
||||
@ -187,6 +219,9 @@ pub async fn destroy_webhook_endpoint(
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::NotFound("webhook_endpoint".into()))?;
|
||||
st.db.delete_webhook_endpoint(id).await?;
|
||||
st.db
|
||||
.record_security_event(auth.organization.id, "webhook_endpoint", "webhook_endpoint.deleted", None, Some(auth.api_key.id), json!({ "webhook_url": url }))
|
||||
.await;
|
||||
Ok(Json(json!({ "webhook_endpoint": webhook_endpoint_json(id, &url, &algo) })))
|
||||
}
|
||||
|
||||
|
||||
196
apps/rago/crates/rago-api/tests/parity_logs.rs
Normal file
196
apps/rago/crates/rago-api/tests/parity_logs.rs
Normal file
@ -0,0 +1,196 @@
|
||||
// Postgres-backed suite: opt in with `--features pg-tests` and DATABASE_URL set.
|
||||
#![cfg(feature = "pg-tests")]
|
||||
|
||||
//! Lago REST parity: instant-fee estimates, enriched events, API and
|
||||
//! security logs, activity log show, usage analytics, gRPC token, document
|
||||
//! requests and the flat quote-version routes.
|
||||
|
||||
mod parity;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
|
||||
/// A sum metric `tokens` on a pay-in-advance standard charge at 0.5 per unit.
|
||||
async fn instant_setup(a: &parity::Api) {
|
||||
a.customer("cust-i").await;
|
||||
a.ok("POST", "/api/v1/billable_metrics", Some(json!({ "billable_metric": { "name": "Tokens", "code": "tokens", "aggregation_type": "sum_agg", "field_name": "tokens" } }))).await;
|
||||
a.ok(
|
||||
"POST",
|
||||
"/api/v1/plans",
|
||||
Some(json!({ "plan": { "name": "Instant", "code": "inst", "interval": "monthly", "amount_cents": 0, "amount_currency": "USD",
|
||||
"charges": [{ "billable_metric_code": "tokens", "charge_model": "standard", "pay_in_advance": true, "properties": { "amount": "0.5" } }] } })),
|
||||
)
|
||||
.await;
|
||||
a.ok("POST", "/api/v1/subscriptions", Some(json!({ "subscription": { "external_customer_id": "cust-i", "plan_code": "inst", "external_id": "sub-i" } }))).await;
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "rago_db::MIGRATOR")]
|
||||
async fn instant_fee_estimates_price_without_storing(pool: PgPool) {
|
||||
let a = parity::api(pool).await;
|
||||
instant_setup(&a).await;
|
||||
let one = a
|
||||
.ok("POST", "/api/v1/events/estimate_instant_fees", Some(json!({ "event": { "code": "tokens", "external_subscription_id": "sub-i", "properties": { "tokens": 7 } } })))
|
||||
.await;
|
||||
let fee = &one["fees"][0];
|
||||
assert_eq!(fee["amount_cents"], 350, "{one}");
|
||||
assert_eq!(fee["units"], "7");
|
||||
assert_eq!(fee["item"]["code"], "tokens");
|
||||
let batch = a
|
||||
.ok(
|
||||
"POST",
|
||||
"/api/v1/events/batch_estimate_instant_fees",
|
||||
Some(json!({ "events": [
|
||||
{ "code": "tokens", "external_subscription_id": "sub-i", "properties": { "tokens": 2 } },
|
||||
{ "code": "tokens", "external_subscription_id": "sub-i", "properties": { "tokens": 4 } },
|
||||
] })),
|
||||
)
|
||||
.await;
|
||||
let cents: Vec<i64> = batch["fees"].as_array().unwrap().iter().map(|f| f["amount_cents"].as_i64().unwrap()).collect();
|
||||
assert_eq!(cents, vec![100, 200]);
|
||||
// Mixed subscriptions and unknown codes are refused.
|
||||
let (st, _) = a
|
||||
.call("POST", "/api/v1/events/batch_estimate_instant_fees", Some(json!({ "events": [
|
||||
{ "code": "tokens", "external_subscription_id": "sub-i" },
|
||||
{ "code": "tokens", "external_subscription_id": "other" },
|
||||
] })))
|
||||
.await;
|
||||
assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let (st, _) = a
|
||||
.call("POST", "/api/v1/events/estimate_instant_fees", Some(json!({ "event": { "code": "nope", "external_subscription_id": "sub-i" } })))
|
||||
.await;
|
||||
assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
// Nothing was stored.
|
||||
let enriched = a.ok("GET", "/api/v1/events_enriched?external_subscription_id=sub-i", None).await;
|
||||
assert!(enriched["events"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "rago_db::MIGRATOR")]
|
||||
async fn enriched_events_show_how_charges_read_them(pool: PgPool) {
|
||||
let a = parity::api(pool).await;
|
||||
instant_setup(&a).await;
|
||||
a.ok("POST", "/api/v1/events", Some(json!({ "event": { "transaction_id": "t1", "code": "tokens", "external_subscription_id": "sub-i", "properties": { "tokens": 4 } } }))).await;
|
||||
let v = a.ok("GET", "/api/v1/events_enriched?external_subscription_id=sub-i&code=tokens", None).await;
|
||||
let e = &v["events"][0];
|
||||
assert_eq!(e["transaction_id"], "t1", "{v}");
|
||||
assert_eq!(e["value"], "4");
|
||||
assert!(e["lago_charge_id"].is_string());
|
||||
assert_eq!(v["meta"]["total_count"], 1);
|
||||
assert_eq!(a.call("GET", "/api/v1/events_enriched", None).await.0, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "rago_db::MIGRATOR")]
|
||||
async fn api_and_security_logs_record_mutations_with_secrets_masked(pool: PgPool) {
|
||||
let a = parity::api(pool).await;
|
||||
a.ok("POST", "/api/v1/customers", Some(json!({ "customer": { "external_id": "c-log", "name": "Log", "metadata_password": "hunter2" } }))).await;
|
||||
a.ok("GET", "/api/v1/customers", None).await;
|
||||
let logs = a.ok("GET", "/api/v1/api_logs", None).await;
|
||||
let rows = logs["api_logs"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 1, "only mutations are logged: {logs}");
|
||||
assert_eq!(rows[0]["http_method"], "POST");
|
||||
assert_eq!(rows[0]["http_status"], 200);
|
||||
assert_eq!(rows[0]["request_path"], "/api/v1/customers");
|
||||
assert_eq!(rows[0]["request_body"]["customer"]["metadata_password"], "[FILTERED]");
|
||||
assert_eq!(rows[0]["request_body"]["customer"]["name"], "Log");
|
||||
let id = rows[0]["request_id"].as_str().unwrap();
|
||||
assert_eq!(a.ok("GET", &format!("/api/v1/api_logs/{id}"), None).await["api_log"]["request_id"], id);
|
||||
// Another org sees neither the list entries nor the row.
|
||||
let other = a.other_org_token().await;
|
||||
assert_eq!(a.call_as(&other, "GET", &format!("/api/v1/api_logs/{id}"), None).await.0, StatusCode::NOT_FOUND);
|
||||
|
||||
// Webhook endpoint changes land in the security log.
|
||||
let made = a.ok("POST", "/api/v1/webhook_endpoints", Some(json!({ "webhook_endpoint": { "webhook_url": "https://hooks.example/a" } }))).await;
|
||||
assert_eq!(made["webhook_endpoint"]["signature_algo"], "hmac", "the stored algo is reported");
|
||||
let wid = made["webhook_endpoint"]["lago_id"].as_str().unwrap();
|
||||
a.ok("DELETE", &format!("/api/v1/webhook_endpoints/{wid}"), None).await;
|
||||
let sec = a.ok("GET", "/api/v1/security_logs", None).await;
|
||||
let events: Vec<&str> = sec["security_logs"].as_array().unwrap().iter().map(|l| l["log_event"].as_str().unwrap()).collect();
|
||||
assert_eq!(events, vec!["webhook_endpoint.deleted", "webhook_endpoint.created"]);
|
||||
let lid = sec["security_logs"][0]["log_id"].as_str().unwrap();
|
||||
assert_eq!(a.ok("GET", &format!("/api/v1/security_logs/{lid}"), None).await["security_log"]["log_type"], "webhook_endpoint");
|
||||
assert_eq!(a.call_as(&other, "GET", &format!("/api/v1/security_logs/{lid}"), None).await.0, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "rago_db::MIGRATOR")]
|
||||
async fn webhook_signature_algo_is_validated(pool: PgPool) {
|
||||
let a = parity::api(pool).await;
|
||||
let (st, v) = a
|
||||
.call("POST", "/api/v1/webhook_endpoints", Some(json!({ "webhook_endpoint": { "webhook_url": "https://hooks.example/b", "signature_algo": "md5" } })))
|
||||
.await;
|
||||
assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY, "{v}");
|
||||
// No RSA key in the test environment: jwt is refused, the public key 404s.
|
||||
if std::env::var("RAGO_RSA_PRIVATE_KEY").is_err() {
|
||||
let (st, _) = a
|
||||
.call("POST", "/api/v1/webhook_endpoints", Some(json!({ "webhook_endpoint": { "webhook_url": "https://hooks.example/b", "signature_algo": "jwt" } })))
|
||||
.await;
|
||||
assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert_eq!(a.call("GET", "/api/v1/webhooks/json_public_key", None).await.0, StatusCode::NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "rago_db::MIGRATOR")]
|
||||
async fn analytics_usage_grpc_token_and_activity_log(pool: PgPool) {
|
||||
let a = parity::api(pool.clone()).await;
|
||||
let today = chrono::Utc::now().date_naive();
|
||||
sqlx::query(
|
||||
"INSERT INTO daily_usages (organization_id, subscription_external_id, usage_date, amount_cents, refreshed_at, created_at) VALUES ($1,'s1',$2,250,now(),now())",
|
||||
)
|
||||
.bind(a.org.id)
|
||||
.bind(today)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("daily usage row");
|
||||
let v = a.ok("GET", "/api/v1/analytics/usage", None).await;
|
||||
assert_eq!(v["usages"][0]["amount_cents"], 250, "{v}");
|
||||
assert_eq!(v["usages"][0]["external_subscription_id"], "s1");
|
||||
assert_eq!(a.call("GET", "/api/v1/analytics/usage?from_date=2026-02-01&to_date=2026-01-01", None).await.0, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
|
||||
let t = a.ok("GET", "/api/v1/organizations/grpc_token", None).await;
|
||||
let token = t["organization"]["grpc_token"].as_str().unwrap();
|
||||
assert_eq!(token.split('.').count(), 3);
|
||||
// It is not a dashboard session.
|
||||
assert_eq!(a.call_as(token, "GET", "/api/v1/customers", None).await.0, StatusCode::UNAUTHORIZED);
|
||||
|
||||
let id = uuid::Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO activity_logs (id, organization_id, activity_type, resource_type, resource_id, payload, created_at) VALUES ($1,$2,'customer.created','Customer',$3,'{}',now())")
|
||||
.bind(id)
|
||||
.bind(a.org.id)
|
||||
.bind(uuid::Uuid::new_v4())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("activity row");
|
||||
let log = a.ok("GET", &format!("/api/v1/activity_logs/{id}"), None).await;
|
||||
assert_eq!(log["activity_log"]["activity_id"], id.to_string(), "{log}");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "rago_db::MIGRATOR")]
|
||||
async fn document_requests_and_flat_quote_versions(pool: PgPool) {
|
||||
let a = parity::api(pool).await;
|
||||
a.customer("cust-q").await;
|
||||
let q = a
|
||||
.ok("POST", "/api/v1/quotes", Some(json!({ "quote": { "external_customer_id": "cust-q", "line_items": [{ "name": "Setup", "unit_amount_cents": 5000, "units": 1 }] } })))
|
||||
.await;
|
||||
let qid = q["quote"]["lago_id"].as_str().unwrap().to_string();
|
||||
let versions = a.ok("GET", &format!("/api/v1/quotes/{qid}/versions"), None).await;
|
||||
let v1 = versions["quote_versions"][0]["lago_id"].as_str().unwrap().to_string();
|
||||
assert_eq!(a.ok("GET", &format!("/api/v1/quote_versions/{v1}"), None).await["quote_version"]["version_number"], 1);
|
||||
let approved = a.ok("POST", &format!("/api/v1/quote_versions/{v1}/approve"), None).await;
|
||||
assert_eq!(approved["quote_version"]["status"], "approved", "{approved}");
|
||||
let cloned = a.ok("POST", &format!("/api/v1/quote_versions/{v1}/clone"), None).await;
|
||||
let v2 = cloned["quote_version"]["lago_id"].as_str().unwrap().to_string();
|
||||
assert_eq!(cloned["quote_version"]["status"], "draft");
|
||||
assert_eq!(cloned["quote_version"]["version_number"], 2);
|
||||
assert_eq!(a.ok("POST", &format!("/api/v1/quote_versions/{v2}/void"), None).await["quote_version"]["status"], "voided");
|
||||
let other = a.other_org_token().await;
|
||||
assert_eq!(a.call_as(&other, "GET", &format!("/api/v1/quote_versions/{v1}"), None).await.0, StatusCode::NOT_FOUND);
|
||||
|
||||
// An invoice: document requests answer with the download URLs.
|
||||
let inv = a
|
||||
.ok("POST", "/api/v1/invoices", Some(json!({ "invoice": { "external_customer_id": "cust-q", "currency": "USD", "fees": [{ "name": "One-off", "unit_amount_cents": 1200, "units": 1 }] } })))
|
||||
.await;
|
||||
let iid = inv["invoice"]["lago_id"].as_str().unwrap();
|
||||
let pdf = a.ok("POST", &format!("/api/v1/invoices/{iid}/download_pdf"), None).await;
|
||||
assert!(pdf["invoice"]["file_url"].as_str().unwrap().ends_with(&format!("/api/v1/invoices/{iid}/download")));
|
||||
let xml = a.ok("POST", &format!("/api/v1/invoices/{iid}/download_xml"), None).await;
|
||||
assert!(xml["invoice"]["xml_url"].as_str().unwrap().ends_with("/download.xml"));
|
||||
}
|
||||
71
apps/rago/crates/rago-billing/src/instant.rs
Normal file
71
apps/rago/crates/rago-billing/src/instant.rs
Normal file
@ -0,0 +1,71 @@
|
||||
//! `Charges::EstimateInstant::{Standard,Percentage}Service` — the amount one
|
||||
//! event costs on a pay-in-advance charge, without reading stored events
|
||||
//! (Lago `POST /events/estimate_instant_fees`).
|
||||
|
||||
use rago_core::enums::ChargeModel;
|
||||
use rust_decimal::Decimal;
|
||||
use serde_json::Value;
|
||||
|
||||
fn dec(props: &Value, key: &str) -> Option<Decimal> {
|
||||
match props.get(key)? {
|
||||
Value::String(s) if !s.trim().is_empty() => s.trim().parse().ok(),
|
||||
Value::Number(n) => n.to_string().parse().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The amount (main currency unit) of `units` under `properties`, or `None`
|
||||
/// for a charge model that cannot be estimated instantly (only standard and
|
||||
/// percentage can). Negative units cost nothing.
|
||||
pub fn instant_amount(model: ChargeModel, properties: &Value, units: Decimal) -> Option<Decimal> {
|
||||
if units.is_sign_negative() {
|
||||
return Some(Decimal::ZERO);
|
||||
}
|
||||
match model {
|
||||
ChargeModel::Standard => Some(units * dec(properties, "amount").unwrap_or_default()),
|
||||
ChargeModel::Percentage => {
|
||||
let rate = dec(properties, "rate").unwrap_or_default();
|
||||
let mut amount = units * rate / Decimal::from(100) + dec(properties, "fixed_amount").unwrap_or_default();
|
||||
if let Some(min) = dec(properties, "per_transaction_min_amount") {
|
||||
amount = amount.max(min);
|
||||
}
|
||||
if let Some(max) = dec(properties, "per_transaction_max_amount") {
|
||||
amount = amount.min(max);
|
||||
}
|
||||
Some(amount)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a charge model can be estimated instantly.
|
||||
pub fn is_instant(model: ChargeModel) -> bool {
|
||||
matches!(model, ChargeModel::Standard | ChargeModel::Percentage)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rust_decimal_macros::dec;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn standard_is_units_times_amount() {
|
||||
assert_eq!(instant_amount(ChargeModel::Standard, &json!({ "amount": "0.5" }), dec!(12)), Some(dec!(6.0)));
|
||||
assert_eq!(instant_amount(ChargeModel::Standard, &json!({ "amount": "2" }), dec!(-3)), Some(Decimal::ZERO));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentage_adds_the_fixed_amount_and_clamps_per_transaction() {
|
||||
let p = json!({ "rate": "2", "fixed_amount": "0.3", "per_transaction_min_amount": "1", "per_transaction_max_amount": "5" });
|
||||
assert_eq!(instant_amount(ChargeModel::Percentage, &p, dec!(100)), Some(dec!(2.3)));
|
||||
assert_eq!(instant_amount(ChargeModel::Percentage, &p, dec!(10)), Some(dec!(1)), "the minimum");
|
||||
assert_eq!(instant_amount(ChargeModel::Percentage, &p, dec!(1000)), Some(dec!(5)), "the maximum");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_models_are_not_instant() {
|
||||
assert_eq!(instant_amount(ChargeModel::Graduated, &json!({}), dec!(1)), None);
|
||||
assert!(!is_instant(ChargeModel::Package));
|
||||
}
|
||||
}
|
||||
@ -34,6 +34,7 @@ pub mod expression;
|
||||
pub mod fees;
|
||||
pub mod fixed_charges;
|
||||
pub mod generate;
|
||||
pub mod instant;
|
||||
pub mod invoices;
|
||||
mod json;
|
||||
pub mod prepaid;
|
||||
|
||||
@ -2303,12 +2303,26 @@ impl Db {
|
||||
|
||||
/// Insert a webhook endpoint, returning its id.
|
||||
pub async fn insert_webhook_endpoint_returning(&self, org: Uuid, url: &str) -> Result<Uuid> {
|
||||
self.insert_webhook_endpoint_with_algo(org, url, "hmac").await
|
||||
}
|
||||
|
||||
/// Insert a webhook endpoint with its signature algorithm (`hmac`|`jwt`).
|
||||
pub async fn insert_webhook_endpoint_with_algo(&self, org: Uuid, url: &str, algo: &str) -> Result<Uuid> {
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO webhook_endpoints (id, organization_id, webhook_url, signature_algo, created_at, updated_at) VALUES ($1,$2,$3,'hmac',now(),now())")
|
||||
.bind(id).bind(org).bind(url).execute(&self.pool).await?;
|
||||
sqlx::query("INSERT INTO webhook_endpoints (id, organization_id, webhook_url, signature_algo, created_at, updated_at) VALUES ($1,$2,$3,$4,now(),now())")
|
||||
.bind(id).bind(org).bind(url).bind(algo).execute(&self.pool).await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// The signature algorithm of an org's endpoint by URL (`hmac` if unknown).
|
||||
pub async fn webhook_endpoint_algo(&self, org: Uuid, url: &str) -> Result<String> {
|
||||
let algo: Option<String> = sqlx::query_scalar(
|
||||
"SELECT signature_algo FROM webhook_endpoints WHERE organization_id = $1 AND webhook_url = $2 ORDER BY created_at LIMIT 1",
|
||||
)
|
||||
.bind(org).bind(url).fetch_optional(&self.pool).await?;
|
||||
Ok(algo.unwrap_or_else(|| "hmac".into()))
|
||||
}
|
||||
|
||||
/// Webhook endpoints for an org `(id, webhook_url, signature_algo)`.
|
||||
pub async fn list_webhook_endpoints(&self, org: Uuid) -> Result<Vec<(Uuid, String, String)>> {
|
||||
let rows = sqlx::query("SELECT id, webhook_url, signature_algo FROM webhook_endpoints WHERE organization_id = $1 ORDER BY created_at")
|
||||
|
||||
@ -729,6 +729,43 @@ impl Db {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record a security event (Lago `Utils::SecurityLog.produce`). A failed
|
||||
/// write never fails the action it audits; it is logged instead.
|
||||
pub async fn record_security_event(
|
||||
&self,
|
||||
org: Uuid,
|
||||
log_type: &str,
|
||||
log_event: &str,
|
||||
user_id: Option<Uuid>,
|
||||
api_key_id: Option<Uuid>,
|
||||
resources: Value,
|
||||
) {
|
||||
let device = serde_json::json!({});
|
||||
if let Err(e) = self
|
||||
.insert_security_log(org, log_type, log_event, user_id, api_key_id, &resources, &device)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, org = %org, log_event, "security log write failed");
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a user security event in every organization the user is an
|
||||
/// active member of (password events are not scoped to one org).
|
||||
pub async fn record_user_security_event(&self, user_id: Uuid, log_event: &str, resources: Value) {
|
||||
let done = sqlx::query(
|
||||
"INSERT INTO security_logs (organization_id, log_type, log_event, user_id, resources, device_info) \
|
||||
SELECT organization_id, 'user', $2, $1, $3, '{}'::jsonb FROM memberships WHERE user_id = $1 AND status = 'active'",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(log_event)
|
||||
.bind(&resources)
|
||||
.execute(&self.pool)
|
||||
.await;
|
||||
if let Err(e) = done {
|
||||
tracing::warn!(error = %e, user = %user_id, log_event, "security log write failed");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_security_logs(&self, org: Uuid, limit: i64, offset: i64) -> Result<(Vec<SecurityLogRow>, i64)> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT * FROM security_logs WHERE organization_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
|
||||
|
||||
@ -14,7 +14,7 @@ use uuid::Uuid;
|
||||
|
||||
use crate::admin_inputs4::*;
|
||||
use crate::auth;
|
||||
use crate::context::{db, require_org};
|
||||
use crate::context::{current_user, db, require_org};
|
||||
use crate::types::ApiKey;
|
||||
use crate::types_admin::Tax;
|
||||
use crate::types_admin2::BillingEntity;
|
||||
@ -74,6 +74,7 @@ impl AdminMutation4 {
|
||||
let user_id = Uuid::new_v4();
|
||||
db(ctx).insert_user(user_id, &email, Some(&digest)).await?;
|
||||
db(ctx).insert_membership(Uuid::new_v4(), org.id, user_id, "admin", &json!([])).await?;
|
||||
db(ctx).record_security_event(org.id, "user", "user.signed_up", Some(user_id), None, json!({ "email": email })).await;
|
||||
Ok(LoginPayload { token: auth::issue_jwt(user_id), user: User { id: user_id.into(), email } })
|
||||
}
|
||||
|
||||
@ -108,6 +109,7 @@ impl AdminMutation4 {
|
||||
let id = Uuid::new_v4();
|
||||
let token = auth::random_token();
|
||||
db(ctx).insert_password_reset(id, user_id, &token).await?;
|
||||
db(ctx).record_user_security_event(user_id, "user.password_reset_requested", json!({ "email": email })).await;
|
||||
Ok(id.into())
|
||||
}
|
||||
|
||||
@ -121,6 +123,7 @@ impl AdminMutation4 {
|
||||
db(ctx).update_user_password(user_id, &digest).await?;
|
||||
db(ctx).delete_password_reset(reset_id).await?;
|
||||
let (_, email) = db(ctx).find_user(user_id).await?.ok_or_else(|| async_graphql::Error::new("user_not_found"))?;
|
||||
db(ctx).record_user_security_event(user_id, "user.password_edited", json!({ "email": email })).await;
|
||||
Ok(LoginPayload { token: auth::issue_jwt(user_id), user: User { id: user_id.into(), email } })
|
||||
}
|
||||
|
||||
@ -215,6 +218,10 @@ impl AdminMutation4 {
|
||||
async fn rotate_api_key(&self, ctx: &Context<'_>, id: ID, name: Option<String>) -> Result<ApiKey> {
|
||||
let org = require_org(ctx)?;
|
||||
let (new_id, value, name) = db(ctx).rotate_api_key(org.id, uuid(&id)?, name.as_deref()).await?.ok_or_else(|| async_graphql::Error::new("api_key_not_found"))?;
|
||||
let actor = current_user(ctx).map(|u| u.id);
|
||||
db(ctx)
|
||||
.record_security_event(org.id, "api_key", "api_key.rotated", actor, Some(new_id), json!({ "rotated_from": id.to_string(), "name": name }))
|
||||
.await;
|
||||
Ok(ApiKey { id: new_id.into(), name, value, created_at: Utc::now().to_rfc3339() })
|
||||
}
|
||||
|
||||
@ -225,6 +232,8 @@ impl AdminMutation4 {
|
||||
if !db(ctx).destroy_api_key(org.id, uid).await? {
|
||||
return Err(async_graphql::Error::new("api_key_not_found"));
|
||||
}
|
||||
let actor = current_user(ctx).map(|u| u.id);
|
||||
db(ctx).record_security_event(org.id, "api_key", "api_key.deleted", actor, Some(uid), json!({})).await;
|
||||
Ok(uid.into())
|
||||
}
|
||||
|
||||
|
||||
@ -94,6 +94,13 @@ pub fn issue_sso_jwt(user_id: Uuid, organization_id: Uuid, provider: &str) -> St
|
||||
}))
|
||||
}
|
||||
|
||||
/// Lago `Auth::GrpcTokenService`: an organization-scoped HS256 token for the
|
||||
/// event-processing gRPC side channel. It carries no `sub`, so it can never be
|
||||
/// accepted as a dashboard session by [`verify_jwt_claims`].
|
||||
pub fn issue_grpc_jwt(organization_id: Uuid) -> String {
|
||||
sign_jwt(serde_json::json!({ "organization_id": organization_id.to_string(), "aud": "rago-grpc" }))
|
||||
}
|
||||
|
||||
fn sign_jwt(mut claims: serde_json::Value) -> String {
|
||||
let header = b64url(br#"{"alg":"HS256","typ":"JWT"}"#);
|
||||
let exp = (Utc::now() + Duration::days(1)).timestamp();
|
||||
|
||||
@ -771,6 +771,8 @@ impl Mutation {
|
||||
updated_at: now(),
|
||||
};
|
||||
db(ctx).insert_api_key(&key).await?;
|
||||
let actor = crate::context::current_user(ctx).map(|u| u.id);
|
||||
db(ctx).record_security_event(org.id, "api_key", "api_key.created", actor, Some(key.id), json!({ "name": key.name })).await;
|
||||
Ok(ApiKey {
|
||||
id: key.id.into(),
|
||||
name: key.name,
|
||||
|
||||
@ -23,9 +23,12 @@ async-trait.workspace = true
|
||||
hmac.workspace = true
|
||||
sha2.workspace = true
|
||||
base64.workspace = true
|
||||
# RS256 webhook signatures (Lago `signature_algo: jwt`).
|
||||
rsa = { version = "0.9", default-features = false, features = ["std", "pem", "sha2"] }
|
||||
reqwest = { workspace = true, optional = true }
|
||||
# Outbound webhooks reach public addresses only (shared with rithub).
|
||||
egress-guard = { path = "../egress-guard", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true }
|
||||
rand = "0.8"
|
||||
|
||||
158
apps/rago/crates/rago-integrations/src/webhooks/jwt.rs
Normal file
158
apps/rago/crates/rago-integrations/src/webhooks/jwt.rs
Normal file
@ -0,0 +1,158 @@
|
||||
//! RS256 webhook signatures (Lago `signature_algo: jwt`).
|
||||
//!
|
||||
//! Lago signs `X-Lago-Signature` as a JWT over `{ "data": <payload JSON
|
||||
//! string>, "iss": <API URL> }` with the deployment's RSA key, and publishes
|
||||
//! the public key at `GET /webhooks/public_key` (base64 of the PEM) so a
|
||||
//! receiver verifies without a shared secret.
|
||||
//!
|
||||
//! The key comes from `RAGO_RSA_PRIVATE_KEY` (PKCS#8 or PKCS#1 PEM, raw or
|
||||
//! base64-encoded, like Lago's `LAGO_RSA_PRIVATE_KEY`); the issuer from
|
||||
//! `RAGO_API_URL` (else `LAGO_API_URL`).
|
||||
|
||||
use base64::Engine;
|
||||
use rsa::pkcs1::DecodeRsaPrivateKey;
|
||||
use rsa::pkcs1v15::SigningKey;
|
||||
use rsa::pkcs8::{DecodePrivateKey, EncodePublicKey, LineEnding};
|
||||
use rsa::signature::{SignatureEncoding, Signer};
|
||||
use rsa::RsaPrivateKey;
|
||||
use sha2::Sha256;
|
||||
|
||||
const B64URL: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
|
||||
/// A loaded RS256 webhook signer.
|
||||
#[derive(Clone)]
|
||||
pub struct JwtSigner {
|
||||
key: SigningKey<Sha256>,
|
||||
public_pem: String,
|
||||
issuer: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for JwtSigner {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("JwtSigner").field("issuer", &self.issuer).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a key could not be loaded.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum JwtKeyError {
|
||||
#[error("RAGO_RSA_PRIVATE_KEY is not an RSA private key in PEM form")]
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl JwtSigner {
|
||||
/// From a PEM (or base64 of a PEM) private key.
|
||||
pub fn from_pem(raw: &str, issuer: impl Into<String>) -> Result<Self, JwtKeyError> {
|
||||
let text = raw.trim();
|
||||
let pem = if text.starts_with("-----BEGIN") {
|
||||
text.to_string()
|
||||
} else {
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(text.replace(['\n', '\r'], "")).map_err(|_| JwtKeyError::Invalid)?;
|
||||
String::from_utf8(bytes).map_err(|_| JwtKeyError::Invalid)?
|
||||
};
|
||||
let key = RsaPrivateKey::from_pkcs8_pem(&pem).or_else(|_| RsaPrivateKey::from_pkcs1_pem(&pem)).map_err(|_| JwtKeyError::Invalid)?;
|
||||
let public_pem = key.to_public_key().to_public_key_pem(LineEnding::LF).map_err(|_| JwtKeyError::Invalid)?;
|
||||
Ok(Self { key: SigningKey::<Sha256>::new(key), public_pem, issuer: issuer.into() })
|
||||
}
|
||||
|
||||
/// From the environment; `None` when no key is configured.
|
||||
pub fn from_env() -> Result<Option<Self>, JwtKeyError> {
|
||||
let Some(raw) = std::env::var("RAGO_RSA_PRIVATE_KEY").ok().filter(|v| !v.trim().is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let issuer = std::env::var("RAGO_API_URL").or_else(|_| std::env::var("LAGO_API_URL")).unwrap_or_default();
|
||||
Self::from_pem(&raw, issuer).map(Some)
|
||||
}
|
||||
|
||||
/// The process-wide signer from the environment, loaded once. A malformed
|
||||
/// key is treated as absent (endpoints then sign with HMAC) and logged.
|
||||
pub fn global() -> Option<&'static JwtSigner> {
|
||||
static SIGNER: std::sync::OnceLock<Option<JwtSigner>> = std::sync::OnceLock::new();
|
||||
SIGNER
|
||||
.get_or_init(|| match Self::from_env() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("rago: {e}; webhook JWT signing disabled");
|
||||
None
|
||||
}
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The SPKI public key PEM.
|
||||
pub fn public_key_pem(&self) -> &str {
|
||||
&self.public_pem
|
||||
}
|
||||
|
||||
/// `GET /webhooks/public_key`: base64 of the PEM (Lago's shape).
|
||||
pub fn public_key_base64(&self) -> String {
|
||||
base64::engine::general_purpose::STANDARD.encode(self.public_pem.as_bytes())
|
||||
}
|
||||
|
||||
/// The `X-Lago-Signature` JWT for a payload JSON string.
|
||||
pub fn sign(&self, payload_json: &str) -> String {
|
||||
let header = B64URL.encode(br#"{"alg":"RS256","typ":"JWT"}"#);
|
||||
let claims = B64URL.encode(serde_json::json!({ "data": payload_json, "iss": self.issuer }).to_string());
|
||||
let input = format!("{header}.{claims}");
|
||||
let sig = self.key.sign(input.as_bytes());
|
||||
format!("{input}.{}", B64URL.encode(sig.to_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rsa::pkcs1v15::{Signature, VerifyingKey};
|
||||
use rsa::pkcs8::{DecodePublicKey, EncodePrivateKey};
|
||||
use rsa::signature::Verifier;
|
||||
use rsa::RsaPublicKey;
|
||||
|
||||
fn signer() -> JwtSigner {
|
||||
let key = RsaPrivateKey::new(&mut rand::thread_rng(), 2048).unwrap();
|
||||
let pem = key.to_pkcs8_pem(LineEnding::LF).unwrap();
|
||||
JwtSigner::from_pem(&base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()), "https://billing.example").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_signature_verifies_with_the_published_key_and_carries_the_payload() {
|
||||
let s = signer();
|
||||
let token = s.sign(r#"{"webhook_type":"invoice.created"}"#);
|
||||
let parts: Vec<&str> = token.split('.').collect();
|
||||
assert_eq!(parts.len(), 3);
|
||||
let published = String::from_utf8(base64::engine::general_purpose::STANDARD.decode(s.public_key_base64()).unwrap()).unwrap();
|
||||
let public = RsaPublicKey::from_public_key_pem(&published).unwrap();
|
||||
let verifier = VerifyingKey::<Sha256>::new(public);
|
||||
let sig = Signature::try_from(B64URL.decode(parts[2]).unwrap().as_slice()).unwrap();
|
||||
verifier.verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &sig).expect("RS256 verifies");
|
||||
let claims: serde_json::Value = serde_json::from_slice(&B64URL.decode(parts[1]).unwrap()).unwrap();
|
||||
assert_eq!(claims["data"], r#"{"webhook_type":"invoice.created"}"#);
|
||||
assert_eq!(claims["iss"], "https://billing.example");
|
||||
// A changed payload does not verify.
|
||||
assert!(verifier.verify(b"x.y", &sig).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_is_not_a_key() {
|
||||
assert!(JwtSigner::from_pem("not a key", "").is_err());
|
||||
assert!(!format!("{:?}", signer()).contains("PRIVATE"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod header_tests {
|
||||
use super::*;
|
||||
use crate::webhooks::{Signing, Webhook};
|
||||
use rsa::pkcs8::EncodePrivateKey;
|
||||
|
||||
#[test]
|
||||
fn jwt_endpoints_get_jwt_headers() {
|
||||
let key = RsaPrivateKey::new(&mut rand::thread_rng(), 2048).unwrap();
|
||||
let s = JwtSigner::from_pem(&key.to_pkcs8_pem(LineEnding::LF).unwrap(), "i").unwrap();
|
||||
let wh = Webhook::build(uuid::Uuid::new_v4(), "https://x.example/h", "invoice.created", "invoice", serde_json::json!({"a": 1}));
|
||||
let h = wh.signed_headers(Signing::Jwt(&s));
|
||||
assert!(h.contains(&("X-Lago-Signature-Algorithm".into(), "jwt".into())));
|
||||
assert_eq!(h.iter().find(|(k, _)| k == "X-Lago-Signature").unwrap().1.split('.').count(), 3);
|
||||
let h = wh.signed_headers(Signing::Hmac("k"));
|
||||
assert!(h.contains(&("X-Lago-Signature-Algorithm".into(), "hmac".into())));
|
||||
}
|
||||
}
|
||||
@ -24,8 +24,31 @@ use uuid::Uuid;
|
||||
use crate::transport::HttpTransport;
|
||||
|
||||
pub mod catalog;
|
||||
pub mod jwt;
|
||||
pub mod payloads;
|
||||
|
||||
pub use jwt::JwtSigner;
|
||||
|
||||
impl Signing<'_> {
|
||||
/// The signing for an endpoint's stored `signature_algo`: `jwt` uses the
|
||||
/// deployment key when one is configured, everything else HMAC.
|
||||
pub fn for_algo<'a>(algo: &str, hmac_key: &'a str, signer: Option<&'a JwtSigner>) -> Signing<'a> {
|
||||
match (algo, signer) {
|
||||
("jwt", Some(s)) => Signing::Jwt(s),
|
||||
_ => Signing::Hmac(hmac_key),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an endpoint's deliveries are signed (`webhook_endpoints.signature_algo`).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Signing<'a> {
|
||||
/// `base64(HMAC-SHA256(org.hmac_key, payload))`.
|
||||
Hmac(&'a str),
|
||||
/// RS256 JWT over `{data, iss}` with the deployment key.
|
||||
Jwt(&'a JwtSigner),
|
||||
}
|
||||
|
||||
pub use catalog::WebhookKind;
|
||||
|
||||
/// Webhook delivery status (`Webhook::STATUS`).
|
||||
@ -114,10 +137,21 @@ impl Webhook {
|
||||
|
||||
/// `Webhook#generate_headers`.
|
||||
pub fn headers(&self, hmac_key: &str) -> Vec<(String, String)> {
|
||||
self.signed_headers(Signing::Hmac(hmac_key))
|
||||
}
|
||||
|
||||
/// `Webhook#generate_headers` for either signature algorithm.
|
||||
pub fn signed_headers(&self, signing: Signing<'_>) -> Vec<(String, String)> {
|
||||
let (signature, algo) = match signing {
|
||||
Signing::Hmac(key) => (self.hmac_signature(key), "hmac"),
|
||||
Signing::Jwt(signer) => {
|
||||
(signer.sign(&serde_json::to_string(&self.payload).unwrap_or_default()), "jwt")
|
||||
}
|
||||
};
|
||||
vec![
|
||||
("Content-Type".into(), "application/json".into()),
|
||||
("X-Lago-Signature".into(), self.hmac_signature(hmac_key)),
|
||||
("X-Lago-Signature-Algorithm".into(), "hmac".into()),
|
||||
("X-Lago-Signature".into(), signature),
|
||||
("X-Lago-Signature-Algorithm".into(), algo.into()),
|
||||
("X-Lago-Unique-Key".into(), self.id.to_string()),
|
||||
]
|
||||
}
|
||||
@ -175,12 +209,21 @@ pub async fn deliver<T: HttpTransport>(
|
||||
transport: &T,
|
||||
webhook: &mut Webhook,
|
||||
hmac_key: &str,
|
||||
) -> bool {
|
||||
deliver_signed(transport, webhook, Signing::Hmac(hmac_key)).await
|
||||
}
|
||||
|
||||
/// [`deliver`] with the endpoint's chosen signature algorithm.
|
||||
pub async fn deliver_signed<T: HttpTransport>(
|
||||
transport: &T,
|
||||
webhook: &mut Webhook,
|
||||
signing: Signing<'_>,
|
||||
) -> bool {
|
||||
if let Err(refused) = egress_guard::check_url(&webhook.endpoint, webhook_policy()) {
|
||||
webhook.mark_unsuccessful(None, format!("blocked target: {refused}"), false);
|
||||
return false;
|
||||
}
|
||||
let headers = webhook.headers(hmac_key);
|
||||
let headers = webhook.signed_headers(signing);
|
||||
let body = serde_json::to_string(&webhook.payload).unwrap_or_default();
|
||||
|
||||
match transport.post_external(&webhook.endpoint, &headers, body).await {
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
|
||||
use chrono::{NaiveDate, Utc};
|
||||
use rago_db::Db;
|
||||
use rago_integrations::webhooks::{deliver, Webhook};
|
||||
use rago_integrations::webhooks::{deliver_signed, JwtSigner, Signing, Webhook};
|
||||
use rago_integrations::HttpTransport;
|
||||
use serde_json::{json, Value};
|
||||
use std::str::FromStr;
|
||||
@ -305,7 +305,9 @@ pub async fn redeliver_due_webhooks<T: HttpTransport>(
|
||||
updated_at: Utc::now(),
|
||||
};
|
||||
|
||||
let retrying = deliver(transport, &mut webhook, &hmac_key).await;
|
||||
let algo = db.webhook_endpoint_algo(w.organization_id, &w.endpoint).await?;
|
||||
let signing = Signing::for_algo(&algo, &hmac_key, JwtSigner::global());
|
||||
let retrying = deliver_signed(transport, &mut webhook, signing).await;
|
||||
let next_retry = retrying.then(|| backoff_secs(webhook.retries));
|
||||
db.update_webhook_retry(
|
||||
webhook.id,
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
use chrono::Utc;
|
||||
use rago_db::Db;
|
||||
use rago_integrations::webhooks::{deliver, Webhook, WebhookStatus};
|
||||
use rago_integrations::webhooks::{deliver_signed, JwtSigner, Signing, Webhook, WebhookStatus};
|
||||
use rago_integrations::HttpTransport;
|
||||
use serde_json::Value;
|
||||
use uuid::Uuid;
|
||||
@ -29,8 +29,10 @@ pub async fn emit_webhook<T: HttpTransport>(
|
||||
// Deliver, retrying on transient failures. The backoff is short-circuited to
|
||||
// an immediate re-attempt here (the schedule is unit-tested separately); a
|
||||
// production worker re-enqueues after `backoff_seconds`.
|
||||
let algo = db.webhook_endpoint_algo(organization_id, endpoint).await?;
|
||||
let signing = Signing::for_algo(&algo, hmac_key, JwtSigner::global());
|
||||
loop {
|
||||
let should_retry = deliver(transport, &mut webhook, hmac_key).await;
|
||||
let should_retry = deliver_signed(transport, &mut webhook, signing).await;
|
||||
if !should_retry {
|
||||
break;
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user