atp-client 0.1.0

Framework-neutral ATP billing SDK with optional Axum routes, guards, caching, and JWT claims enrichment
Documentation
use crate::{BillingProvider, BillingSnapshot, SdkResult};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
/// Stable, namespaced billing facts to embed under the `atp` JWT claim.
///
/// These values are a point-in-time snapshot. `credits` must not be used as a
/// replacement for ATP's atomic debit operation.
pub struct AtpClaims {
    /// Version of this claims object, independent of the balance version.
    pub schema_version: u8,
    /// ATP tenant/application identifier that produced the snapshot.
    pub app_id: String,
    /// Product tier, such as `free`, `pro`, or `team`.
    pub tier: String,
    /// Current subscription lifecycle status.
    pub subscription_status: String,
    /// Sum of subscription, purchased, and available team credits at issue time.
    pub credits: u64,
    /// Team whose shared pool contributes to the balance, when applicable.
    pub team_id: Option<String>,
    /// Whether the claims came from an outage fallback or stale state.
    pub degraded: bool,
}

impl From<&BillingSnapshot> for AtpClaims {
    fn from(value: &BillingSnapshot) -> Self {
        Self {
            schema_version: 1,
            app_id: value.status.app_id.clone(),
            tier: value.status.tier.clone(),
            subscription_status: value.status.subscription_status.clone(),
            credits: value.status.balance.total(),
            team_id: value.status.balance.team_id.clone(),
            degraded: value.degraded,
        }
    }
}

/// Implement this for the claims object your existing authentication flow already signs.
/// The SDK never verifies, rewrites, or signs JWTs itself.
pub trait ClaimsTarget {
    /// Writes the namespaced ATP claims without modifying unrelated authentication claims.
    fn set_atp_claims(&mut self, claims: AtpClaims) -> SdkResult<()>;
}
impl ClaimsTarget for serde_json::Map<String, serde_json::Value> {
    fn set_atp_claims(&mut self, claims: AtpClaims) -> SdkResult<()> {
        self.insert(
            "atp".into(),
            serde_json::to_value(claims).expect("AtpClaims serialize"),
        );
        Ok(())
    }
}
impl ClaimsTarget for serde_json::Value {
    fn set_atp_claims(&mut self, claims: AtpClaims) -> SdkResult<()> {
        self.as_object_mut()
            .ok_or_else(|| {
                crate::SdkError::Config("JWT claims target must be a JSON object".into())
            })?
            .set_atp_claims(claims)
    }
}

/// Enriches an application's existing claims object before its normal JWT signer runs.
///
/// This type deliberately has no JWT verification or signing capability.
pub struct ClaimsEnricher<P> {
    provider: P,
}
impl<P: BillingProvider> ClaimsEnricher<P> {
    /// Creates an enricher backed by a raw or cached billing provider.
    pub fn new(provider: P) -> Self {
        Self { provider }
    }
    /// Loads billing state, writes `atp` claims, and returns the source snapshot.
    pub async fn enrich<T: ClaimsTarget>(
        &self,
        user_id: &str,
        claims: &mut T,
    ) -> SdkResult<BillingSnapshot> {
        let snapshot = self.provider.billing_snapshot(user_id).await?;
        claims.set_atp_claims(AtpClaims::from(&snapshot))?;
        Ok(snapshot)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn injects_namespaced_claim_without_touching_existing_fields() {
        let mut value = serde_json::json!({"sub":"user-1"});
        value
            .set_atp_claims(AtpClaims {
                schema_version: 1,
                app_id: "a".into(),
                tier: "pro".into(),
                subscription_status: "active".into(),
                credits: 3,
                team_id: None,
                degraded: false,
            })
            .unwrap();
        assert_eq!(value["sub"], "user-1");
        assert_eq!(value["atp"]["tier"], "pro");
    }

    #[test]
    fn rejects_non_object_claims_targets() {
        let mut value = serde_json::Value::Null;
        let result = value.set_atp_claims(AtpClaims {
            schema_version: 1,
            app_id: "a".into(),
            tier: "free".into(),
            subscription_status: "degraded".into(),
            credits: 0,
            team_id: None,
            degraded: true,
        });
        assert!(result.is_err());
    }
}