//! SyncKit SDK key claim / release / list endpoints. //! //! Server-to-server: the developer's backend sends the app's keys-endpoint //! secret (`app_secret`) in the JSON body (no JWT, no session). Each call //! looks up the app via `db::synckit::get_sync_app_by_keys_secret`, enforces //! billing status and (for `per_key` apps) the key cap, then performs the //! operation. //! //! The secret is deliberately not the app's `api_key`. That value is compiled //! into every shipped client, so anyone with a binary could recover it; when //! it gated these routes, they could spend the app's key cap and pollute claim //! attribution under the app's identity. The secret is generated from the //! dashboard, shown once, and belongs on a developer backend. An app that has //! not generated one cannot call these routes at all. There is no fallback //! to the api_key, by design (migration 175). //! //! See migration 117 for the underlying `sync_app_keys` schema (active claim //! is a row with `released_at IS NULL`; the unique index is partial). // // TODO Phase 4 integration tests: blocked on migration 117 applied to test DB use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; use serde_json::json; use sqlx::PgPool; use crate::{ db::{self, synckit_billing}, error::{AppError, Result}, }; use super::{ ClaimKeyRequest, ClaimKeyResponse, KeyInfo, ListKeysRequest, ListKeysResponse, ReleaseKeyRequest, ReleaseKeyResponse, }; /// `POST /api/sync/keys/claim`: server-to-server SDK key claim. /// /// Looks up the app by `app_secret`, then: /// - Internal apps bypass all billing checks. /// - Returns 402 `{ reason: "billing_inactive" }` when billing isn't active. /// - In `per_key` mode, returns 402 /// `{ reason: "key_limit_reached", key_cap, keys_claimed }` if the cap is /// reached and the key is not already actively claimed (re-claims are /// always idempotent OK). #[tracing::instrument(skip_all, name = "synckit::keys::claim")] pub(super) async fn claim( State(db): State, Json(req): Json, ) -> Result { let app = db::synckit::get_sync_app_by_keys_secret(&db, &req.app_secret) .await? .ok_or(AppError::Unauthorized)?; let billing = synckit_billing::get_app_with_billing(&db, app.id) .await? .ok_or(AppError::NotFound)?; // `key_cap` is enforced inside `claim_key`, under the usage-row lock, so // concurrent claims of distinct keys can't over-allocate. `None` means // uncapped (internal apps, or `bulk` developer apps). let key_cap = if billing.is_internal { None } else { if billing.billing_status != crate::db::SyncBillingStatus::Active { return Ok(( StatusCode::PAYMENT_REQUIRED, Json(json!({ "reason": "billing_inactive" })), ) .into_response()); } if billing.enforcement_mode == "per_key" { Some(billing.key_cap.unwrap_or(0)) } else { None } }; let result = synckit_billing::claim_key(&db, app.id, &req.key, key_cap).await?; if result.cap_reached { return Ok(( StatusCode::PAYMENT_REQUIRED, Json(json!({ "reason": "key_limit_reached", "key_cap": key_cap.unwrap_or(0), "keys_claimed": result.total_claimed, })), ) .into_response()); } Ok(Json(ClaimKeyResponse { newly_claimed: result.newly_claimed, total_claimed: result.total_claimed, }) .into_response()) } /// `POST /api/sync/keys/release`: server-to-server SDK key release. /// /// Always permitted (even when the app is canceled or suspended) so that /// cleanup paths can drain stale claims. #[tracing::instrument(skip_all, name = "synckit::keys::release")] pub(super) async fn release( State(db): State, Json(req): Json, ) -> Result { let app = db::synckit::get_sync_app_by_keys_secret(&db, &req.app_secret) .await? .ok_or(AppError::Unauthorized)?; let result = synckit_billing::release_key(&db, app.id, &req.key).await?; Ok(Json(ReleaseKeyResponse { newly_released: result.newly_released, total_claimed: result.total_claimed, })) } /// `POST /api/sync/keys/list`: paginated list of active key claims. /// /// Uses POST + body (not GET + query) for consistency with `/validate-app`, /// keeping the secret out of access logs. #[tracing::instrument(skip_all, name = "synckit::keys::list")] pub(super) async fn list( State(db): State, Json(req): Json, ) -> Result { let app = db::synckit::get_sync_app_by_keys_secret(&db, &req.app_secret) .await? .ok_or(AppError::Unauthorized)?; let limit = req.limit.unwrap_or(100).clamp(1, 1000) as i64; // Clamp the offset too (UX-M2): an unbounded offset becomes a giant SQL OFFSET // deep-scan, the same DoS-shaped cost the limit clamp guards against. let offset = (req.offset.unwrap_or(0) as i64).clamp(0, 1_000_000_000); let rows = synckit_billing::list_active_keys(&db, app.id, limit, offset).await?; let keys = rows .into_iter() .map(|r| KeyInfo { id: r.id, key: r.key, claimed_at: r.claimed_at, bytes_stored: r.bytes_stored, }) .collect(); Ok(Json(ListKeysResponse { keys })) } #[cfg(test)] mod tests { use super::super::{ ClaimKeyRequest, ClaimKeyResponse, ListKeysRequest, ListKeysResponse, ReleaseKeyRequest, ReleaseKeyResponse, }; #[test] fn claim_request_roundtrips() { let json = r#"{"app_secret":"abc","key":"dev-1"}"#; let req: ClaimKeyRequest = serde_json::from_str(json).unwrap(); assert_eq!(req.app_secret, "abc"); assert_eq!(req.key, "dev-1"); } #[test] fn claim_response_roundtrips() { let resp = ClaimKeyResponse { newly_claimed: true, total_claimed: 7, }; let s = serde_json::to_string(&resp).unwrap(); assert!(s.contains("\"newly_claimed\":true")); assert!(s.contains("\"total_claimed\":7")); } #[test] fn release_request_roundtrips() { let json = r#"{"app_secret":"abc","key":"dev-1"}"#; let req: ReleaseKeyRequest = serde_json::from_str(json).unwrap(); assert_eq!(req.app_secret, "abc"); assert_eq!(req.key, "dev-1"); } #[test] fn release_response_roundtrips() { let resp = ReleaseKeyResponse { newly_released: false, total_claimed: 3, }; let s = serde_json::to_string(&resp).unwrap(); assert!(s.contains("\"newly_released\":false")); assert!(s.contains("\"total_claimed\":3")); } #[test] fn list_request_defaults() { let json = r#"{"app_secret":"abc"}"#; let req: ListKeysRequest = serde_json::from_str(json).unwrap(); assert_eq!(req.app_secret, "abc"); assert!(req.limit.is_none()); assert!(req.offset.is_none()); } /// The api_key ships inside every client binary. A body naming it must not /// deserialize into a keys-endpoint request, or the closed hole reopens the /// first time someone copies an old snippet. #[test] fn api_key_field_is_not_accepted() { let json = r#"{"api_key":"abc","key":"dev-1"}"#; assert!(serde_json::from_str::(json).is_err()); assert!(serde_json::from_str::(json).is_err()); assert!(serde_json::from_str::(r#"{"api_key":"abc"}"#).is_err()); } #[test] fn list_response_empty_roundtrips() { let resp = ListKeysResponse { keys: vec![] }; let s = serde_json::to_string(&resp).unwrap(); assert_eq!(s, r#"{"keys":[]}"#); } }