atp-client 0.1.0

Framework-neutral ATP billing SDK with optional Axum routes, guards, caching, and JWT claims enrichment
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use crate::{
    AtpClient, BillingCacheConfig, BillingProvider, BillingSnapshot, CachedBillingClient,
    CheckoutInput, CheckoutRequest, CheckoutResponse, PortalInput, PortalResponse, SdkError,
    SdkResult, TierPolicy,
};
use async_trait::async_trait;
use axum::{
    Extension, Json, Router,
    body::Body,
    extract::{Request, State},
    http::{Extensions, HeaderMap, StatusCode},
    middleware::{self, Next},
    response::{IntoResponse, Response},
    routing::{get, post},
};
use std::{marker::PhantomData, sync::Arc};

#[derive(Debug, Clone)]
/// Billing identity derived from an application's already-authenticated Principal.
pub struct AuthenticatedBillingUser {
    /// Tenant-scoped identifier sent to ATP.
    pub user_id: String,
    /// Verified account email required for Checkout and Portal creation.
    pub email: Option<String>,
}

#[async_trait]
/// Resolves ATP identity after the application's existing authentication middleware.
///
/// Implementations must not trust caller-controlled identity headers unless those
/// headers have already been cryptographically authenticated by the application.
pub trait BillingUserResolver: Send + Sync + 'static {
    /// Maps request state to a tenant-scoped ATP user.
    async fn resolve(
        &self,
        headers: &HeaderMap,
        extensions: &Extensions,
    ) -> SdkResult<AuthenticatedBillingUser>;
}

/// Adapter for the common case where an existing authentication middleware
/// has already inserted its principal into Axum request extensions.
pub trait BillingPrincipal: Clone + Send + Sync + 'static {
    /// Returns the stable, tenant-scoped identifier used by ATP.
    fn billing_user_id(&self) -> &str;
    /// Returns the verified account email when Checkout/Portal routes are needed.
    fn billing_email(&self) -> Option<&str> {
        None
    }
}

/// Resolves a [`BillingPrincipal`] previously inserted into Axum extensions.
pub struct ExtensionBillingUserResolver<T>(PhantomData<T>);
impl<T> ExtensionBillingUserResolver<T> {
    /// Creates a resolver for extension type `T` without owning application state.
    pub fn new() -> Self {
        Self(PhantomData)
    }
}
impl<T> Default for ExtensionBillingUserResolver<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl<T: BillingPrincipal> BillingUserResolver for ExtensionBillingUserResolver<T> {
    async fn resolve(
        &self,
        _headers: &HeaderMap,
        extensions: &Extensions,
    ) -> SdkResult<AuthenticatedBillingUser> {
        let principal = extensions.get::<T>().ok_or(SdkError::Unauthorized)?;
        Ok(AuthenticatedBillingUser {
            user_id: principal.billing_user_id().into(),
            email: principal.billing_email().map(Into::into),
        })
    }
}

#[derive(Debug, Clone)]
/// Per-request billing facts injected before guarded business handlers run.
pub struct BillingContext {
    /// Identity derived from the authenticated application Principal.
    pub user: AuthenticatedBillingUser,
    /// Status and provenance used by the current request.
    pub snapshot: BillingSnapshot,
    tier_policy: TierPolicy,
}
impl BillingContext {
    /// Returns the current product tier.
    pub fn tier(&self) -> &str {
        &self.snapshot.status.tier
    }
    /// Returns total immediately spendable credits in this snapshot.
    ///
    /// This is suitable for an early guard, not as a replacement for atomic debit.
    pub fn credits(&self) -> u64 {
        self.snapshot.status.balance.total()
    }
    /// Returns whether this request is operating on stale or fallback status.
    pub fn degraded(&self) -> bool {
        self.snapshot.degraded
    }
}

#[derive(Clone)]
struct IntegrationState {
    client: AtpClient,
    provider: Arc<dyn BillingProvider>,
    resolver: Arc<dyn BillingUserResolver>,
    tier_policy: TierPolicy,
}

#[derive(Clone)]
/// Factory for same-origin billing endpoints and billing-context middleware.
///
/// The application's authentication layer must wrap the returned routes so that
/// the configured resolver can read its verified Principal.
pub struct BillingRouter {
    state: Arc<IntegrationState>,
}
impl BillingRouter {
    /// Creates billing routes with fail-closed authorization cache defaults.
    pub fn new(client: AtpClient, resolver: Arc<dyn BillingUserResolver>) -> Self {
        Self::with_cache(client, resolver, BillingCacheConfig::default())
    }
    /// Creates billing routes with an explicit status-cache policy.
    pub fn with_cache(
        client: AtpClient,
        resolver: Arc<dyn BillingUserResolver>,
        cache: BillingCacheConfig,
    ) -> Self {
        let provider = Arc::new(CachedBillingClient::new(client.clone(), cache));
        Self {
            state: Arc::new(IntegrationState {
                client,
                provider,
                resolver,
                tier_policy: TierPolicy::default(),
            }),
        }
    }
    /// Replaces the default `free < pro < team` tier hierarchy.
    pub fn tier_policy(mut self, policy: TierPolicy) -> Self {
        Arc::make_mut(&mut self.state).tier_policy = policy;
        self
    }

    /// Five same-origin endpoints intended for the third-party application's frontend.
    /// The router derives user_id/email from the existing authenticated principal;
    /// request JSON cannot impersonate another ATP user.
    pub fn into_router(self) -> Router {
        Router::new()
            .route("/api/billing/status", get(status))
            .route("/api/billing/balance", get(balance))
            .route("/api/billing/history", get(history))
            .route("/api/billing/checkout", post(checkout))
            .route("/api/billing/portal", post(portal))
            .route_layer({
                let state = self.state.clone();
                middleware::from_fn(move |request: Request, next: Next| {
                    let state = state.clone();
                    async move { resolve_identity(state, request, next).await }
                })
            })
            .with_state(self.state)
    }

    /// Load BillingContext after the application's existing authentication layer.
    /// Apply this only to routes that need billing information.
    pub fn with_context<S>(&self, router: Router<S>) -> Router<S>
    where
        S: Clone + Send + Sync + 'static,
    {
        let state = self.state.clone();
        router.layer(middleware::from_fn(move |request: Request, next: Next| {
            let state = state.clone();
            async move { load_context(state, request, next).await }
        }))
    }
}

async fn resolve(
    state: &IntegrationState,
    headers: &HeaderMap,
    extensions: &Extensions,
) -> SdkResult<AuthenticatedBillingUser> {
    state.resolver.resolve(headers, extensions).await
}
async fn resolve_identity(
    state: Arc<IntegrationState>,
    mut request: Request,
    next: Next,
) -> Result<Response, IntegrationError> {
    let headers = request.headers().clone();
    let extensions = request.extensions().clone();
    let user = resolve(&state, &headers, &extensions).await?;
    request.extensions_mut().insert(user);
    Ok(next.run(request).await)
}
async fn load_context(
    state: Arc<IntegrationState>,
    mut request: Request,
    next: Next,
) -> Result<Response, IntegrationError> {
    let headers = request.headers().clone();
    let extensions = request.extensions().clone();
    let user = resolve(&state, &headers, &extensions).await?;
    let snapshot = state.provider.billing_snapshot(&user.user_id).await?;
    request.extensions_mut().insert(BillingContext {
        user,
        snapshot,
        tier_policy: state.tier_policy.clone(),
    });
    Ok(next.run(request).await)
}

async fn status(
    State(state): State<Arc<IntegrationState>>,
    Extension(user): Extension<AuthenticatedBillingUser>,
) -> Result<Json<BillingSnapshot>, IntegrationError> {
    Ok(Json(state.provider.billing_snapshot(&user.user_id).await?))
}
async fn balance(
    State(state): State<Arc<IntegrationState>>,
    Extension(user): Extension<AuthenticatedBillingUser>,
) -> Result<Json<crate::Balance>, IntegrationError> {
    Ok(Json(
        state
            .provider
            .billing_snapshot(&user.user_id)
            .await?
            .status
            .balance,
    ))
}
async fn history(
    State(state): State<Arc<IntegrationState>>,
    Extension(user): Extension<AuthenticatedBillingUser>,
) -> Result<Json<Vec<crate::LedgerEntry>>, IntegrationError> {
    Ok(Json(state.client.ledger(&user.user_id).await?))
}
async fn checkout(
    State(state): State<Arc<IntegrationState>>,
    Extension(user): Extension<AuthenticatedBillingUser>,
    headers: HeaderMap,
    Json(input): Json<CheckoutInput>,
) -> Result<Json<CheckoutResponse>, IntegrationError> {
    let email = user.email.ok_or_else(|| {
        SdkError::Config(
            "authenticated principal does not expose an email required by Checkout".into(),
        )
    })?;
    let request = CheckoutRequest {
        user_id: user.user_id,
        email,
        purchase: input.purchase,
        success_url: input.success_url,
        cancel_url: input.cancel_url,
    };
    let key = headers
        .get("idempotency-key")
        .and_then(|value| value.to_str().ok())
        .map(Into::into)
        .unwrap_or_else(|| format!("checkout-{}", ulid::Ulid::new()));
    Ok(Json(state.client.checkout(&request, &key).await?))
}
async fn portal(
    State(state): State<Arc<IntegrationState>>,
    Extension(user): Extension<AuthenticatedBillingUser>,
    Json(input): Json<PortalInput>,
) -> Result<Json<PortalResponse>, IntegrationError> {
    let email = user.email.ok_or_else(|| {
        SdkError::Config(
            "authenticated principal does not expose an email required by Portal".into(),
        )
    })?;
    Ok(Json(PortalResponse {
        portal_url: state.client.portal(&email, &input.return_url).await?,
    }))
}

#[derive(Clone)]
struct TierGuard {
    required: String,
}
#[derive(Clone, Copy)]
struct CreditsGuard {
    minimum: u64,
}
/// Wraps routes with a minimum-tier check against an existing [`BillingContext`].
///
/// Apply [`BillingRouter::with_context`] after this function so context loading is
/// outermost in Axum's layer order. Unknown tiers are denied.
pub fn require_tier<S>(router: Router<S>, required: impl Into<String>) -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    let guard = TierGuard {
        required: required.into(),
    };
    router.route_layer(middleware::from_fn(
        move |request: Request<Body>, next: Next| {
            let guard = guard.clone();
            async move { tier_guard(guard, request, next).await }
        },
    ))
}
/// Wraps routes with an early available-credit check against [`BillingContext`].
///
/// This improves UX but cannot reserve credits; the handler must still call debit.
pub fn require_credits<S>(router: Router<S>, minimum: u64) -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    let guard = CreditsGuard { minimum };
    router.route_layer(middleware::from_fn(
        move |request: Request<Body>, next: Next| async move {
            credits_guard(guard, request, next).await
        },
    ))
}
async fn tier_guard(guard: TierGuard, request: Request<Body>, next: Next) -> Response {
    let Some(context) = request.extensions().get::<BillingContext>() else {
        return integration_problem("billing_context_missing", StatusCode::INTERNAL_SERVER_ERROR);
    };
    if !context.tier_policy.allows(context.tier(), &guard.required) {
        return integration_problem("tier_required", StatusCode::FORBIDDEN);
    }
    next.run(request).await
}
async fn credits_guard(guard: CreditsGuard, request: Request<Body>, next: Next) -> Response {
    let Some(context) = request.extensions().get::<BillingContext>() else {
        return integration_problem("billing_context_missing", StatusCode::INTERNAL_SERVER_ERROR);
    };
    if context.credits() < guard.minimum {
        return integration_problem("insufficient_credits", StatusCode::PAYMENT_REQUIRED);
    }
    next.run(request).await
}
fn integration_problem(code: &str, status: StatusCode) -> Response {
    (status, Json(serde_json::json!({"error":{"code":code}}))).into_response()
}

struct IntegrationError(SdkError);
impl From<SdkError> for IntegrationError {
    fn from(value: SdkError) -> Self {
        Self(value)
    }
}
impl IntoResponse for IntegrationError {
    fn into_response(self) -> Response {
        let status = match self.0 {
            SdkError::Unauthorized => StatusCode::UNAUTHORIZED,
            SdkError::InsufficientCredits => StatusCode::PAYMENT_REQUIRED,
            SdkError::NotFound => StatusCode::NOT_FOUND,
            SdkError::Conflict => StatusCode::CONFLICT,
            _ => StatusCode::BAD_GATEWAY,
        };
        (status, Json(serde_json::json!({"error":{"code":"billing_unavailable","message":self.0.to_string()}}))).into_response()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::Request;
    use tower::ServiceExt;

    fn context(tier: &str) -> BillingContext {
        BillingContext {
            user: AuthenticatedBillingUser {
                user_id: "user-1".into(),
                email: None,
            },
            snapshot: BillingSnapshot {
                status: crate::BillingStatus {
                    app_id: "app-1".into(),
                    user_id: "user-1".into(),
                    tier: tier.into(),
                    subscription_status: "active".into(),
                    balance: crate::Balance {
                        app_id: "app-1".into(),
                        user_id: "user-1".into(),
                        subscription: 10,
                        ..Default::default()
                    },
                },
                source: crate::SnapshotSource::Fresh,
                degraded: false,
            },
            tier_policy: TierPolicy::default(),
        }
    }

    #[tokio::test]
    async fn tier_guard_uses_authenticated_billing_context() {
        let app = require_tier(
            Router::new().route("/", get(|| async { StatusCode::OK })),
            "pro",
        )
        .layer(Extension(context("free")));
        let response = app
            .oneshot(Request::get("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn higher_tier_passes_guard() {
        let app = require_tier(
            Router::new().route("/", get(|| async { StatusCode::OK })),
            "pro",
        )
        .layer(Extension(context("team")));
        let response = app
            .oneshot(Request::get("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }
}