Skip to main content

cachekit/backend/
cachekitio_lock.rs

1//! [`LockableBackend`] implementation for the cachekit.io HTTP backend.
2
3use async_trait::async_trait;
4use serde::{Deserialize, Serialize};
5
6use super::cachekitio::{reqwest_err_sanitized, CachekitIO};
7use super::LockableBackend;
8use crate::error::BackendError;
9
10/// Lock capability token travels in this request header, never the query string
11/// (CWE-532): a `?lock_id=` query leaks the token into access/proxy logs and
12/// OpenTelemetry `http.url` spans. SaaS dual-reads header + legacy query during
13/// rollout, preferring the header. See protocol `spec/saas-api.md`.
14const LOCK_ID_HEADER: &str = "X-CacheKit-Lock-Id";
15
16impl CachekitIO {
17    /// Build the unlock request. Extracted so tests can assert the lock_id rides the
18    /// `X-CacheKit-Lock-Id` header and never appears in the URL (CWE-532).
19    fn release_request(
20        &self,
21        key: &str,
22        lock_id: &str,
23    ) -> Result<reqwest::RequestBuilder, BackendError> {
24        let url = self.lock_url(key)?;
25        Ok(self.with_standard_headers(
26            self.client()
27                .delete(&url)
28                .bearer_auth(self.api_key_str())
29                .header(LOCK_ID_HEADER, lock_id),
30        ))
31    }
32}
33
34// Wire contract is snake_case (`spec/saas-api.md` Lock Endpoints): `timeout_ms` in,
35// `lock_id` out. No serde rename — the Rust field names ARE the wire names.
36#[derive(Serialize)]
37struct LockAcquireRequest {
38    timeout_ms: u64,
39}
40
41#[derive(Deserialize)]
42#[serde(deny_unknown_fields)]
43struct LockAcquireResponse {
44    lock_id: Option<String>,
45}
46
47#[cfg(not(target_arch = "wasm32"))]
48#[cfg_attr(not(feature = "unsync"), async_trait)]
49#[cfg_attr(feature = "unsync", async_trait(?Send))]
50impl LockableBackend for CachekitIO {
51    async fn acquire_lock(
52        &self,
53        key: &str,
54        timeout_ms: u64,
55    ) -> Result<Option<String>, BackendError> {
56        let url = self.lock_url(key)?;
57
58        let body = serde_json::to_vec(&LockAcquireRequest { timeout_ms }).map_err(|e| {
59            BackendError::permanent(format!("failed to serialize lock request: {e}"))
60        })?;
61
62        let req = self.with_standard_headers(
63            self.client()
64                .post(&url)
65                .bearer_auth(self.api_key_str())
66                .header("Content-Type", "application/json")
67                .body(body),
68        );
69
70        let resp = req
71            .send()
72            .await
73            .map_err(|e| reqwest_err_sanitized(e, self.api_key_str()))?;
74
75        if !resp.status().is_success() {
76            return Err(self.error_from_response(resp).await);
77        }
78
79        let response: LockAcquireResponse = resp
80            .json()
81            .await
82            .map_err(|e| BackendError::transient(format!("failed to parse lock response: {e}")))?;
83
84        Ok(response.lock_id)
85    }
86
87    async fn release_lock(&self, key: &str, lock_id: &str) -> Result<bool, BackendError> {
88        // lock_id is a capability token → X-CacheKit-Lock-Id header, not the query string
89        // (CWE-532). See `release_request`.
90        let resp = self
91            .release_request(key, lock_id)?
92            .send()
93            .await
94            .map_err(|e| reqwest_err_sanitized(e, self.api_key_str()))?;
95
96        match resp.status().as_u16() {
97            200 | 204 => Ok(true),
98            404 => Ok(false),
99            _ => Err(self.error_from_response(resp).await),
100        }
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    /// Compile-time proof that CachekitIO implements LockableBackend.
109    fn _assert_lockable(_b: &dyn LockableBackend) {}
110
111    #[test]
112    fn cachekitio_is_lockable() {
113        fn _check(backend: &CachekitIO) {
114            _assert_lockable(backend);
115        }
116    }
117
118    #[test]
119    #[allow(clippy::expect_used)] // test-only: a failed build/missing header should panic loudly
120    fn release_lock_sends_token_in_header_not_url() {
121        let backend = CachekitIO::builder()
122            .api_url("https://api.cachekit.io")
123            .api_key("ck_test_key")
124            .build()
125            .expect("builder should succeed for the canonical host");
126
127        let req = backend
128            .release_request("my-key", "lock-secret-123")
129            .expect("release_request should build for a normal key")
130            .build()
131            .expect("request should build");
132
133        // CWE-532: the capability token must never appear in the URL.
134        let url = req.url();
135        assert!(url.query().is_none(), "unexpected query string: {url}");
136        assert!(
137            !url.as_str().contains("lock_id"),
138            "lock_id leaked into URL: {url}"
139        );
140        assert!(
141            !url.as_str().contains("lock-secret-123"),
142            "token leaked into URL: {url}"
143        );
144
145        // ...it rides the X-CacheKit-Lock-Id header under the exact wire name.
146        let header = req
147            .headers()
148            .get("X-CacheKit-Lock-Id")
149            .expect("X-CacheKit-Lock-Id header must be set");
150        assert_eq!(header, "lock-secret-123");
151    }
152
153    // Wire contract is snake_case (`spec/saas-api.md` Lock Endpoints): the server reads
154    // `timeout_ms` and writes `lock_id`. These tests pin the literal JSON so a serde
155    // rename can't silently break interop again.
156
157    #[test]
158    #[allow(clippy::expect_used)]
159    fn acquire_request_serializes_snake_case() {
160        let body = serde_json::to_string(&LockAcquireRequest { timeout_ms: 5000 })
161            .expect("request must serialize");
162        assert_eq!(body, r#"{"timeout_ms":5000}"#);
163    }
164
165    #[test]
166    #[allow(clippy::expect_used)]
167    fn acquire_response_parses_acquired_lock() {
168        let resp: LockAcquireResponse =
169            serde_json::from_str(r#"{"lock_id":"a1b2c3d4-0000-0000-0000-000000000000"}"#)
170                .expect("acquired response must parse");
171        assert_eq!(
172            resp.lock_id.as_deref(),
173            Some("a1b2c3d4-0000-0000-0000-000000000000")
174        );
175    }
176
177    #[test]
178    #[allow(clippy::expect_used)]
179    fn acquire_response_parses_contested_lock() {
180        // Contested lock: server returns 200 {"lock_id": null} (protocol#22).
181        let resp: LockAcquireResponse =
182            serde_json::from_str(r#"{"lock_id":null}"#).expect("contested response must parse");
183        assert_eq!(resp.lock_id, None);
184    }
185}