zenwave 0.4.0

Ergonomic HTTP client framework.
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
//! Middleware for managing cookies in HTTP requests and responses.

use crate::header;
use crate::{Endpoint, Middleware, Request, Response};
use http_kit::HttpError;
use http_kit::cookie::{Cookie, CookieJar};
use http_kit::header::HeaderValue;
use http_kit::middleware::MiddlewareError;
#[cfg(not(target_arch = "wasm32"))]
use serde::{Deserialize, Serialize};

#[cfg(not(target_arch = "wasm32"))]
use {
    async_fs,
    async_lock::Mutex as AsyncMutex,
    serde_json,
    std::{
        collections::HashMap,
        convert::TryFrom,
        io::ErrorKind,
        path::{Path, PathBuf},
        sync::{Arc, LazyLock},
    },
};

#[cfg(not(target_arch = "wasm32"))]
use time::OffsetDateTime;

/// Middleware for managing cookies in HTTP requests and responses.
#[derive(Debug)]
pub struct CookieStore {
    store: CookieJar,
    #[cfg(not(target_arch = "wasm32"))]
    persistence: Option<Persistence>,
}

/// Errors encountered while handling HTTP cookies.
#[derive(Debug, thiserror::Error)]
pub enum CookieError {
    /// Failed to read persisted cookies from disk.
    #[error("Failed to load cookies from disk: {0}")]
    FailToLoadCookiesFromDisk(std::io::Error),

    /// Failed to decode persisted cookie data.
    #[error("Failed to parse cookies from disk: {0}")]
    FailToParseCookiesFromDisk(serde_json::Error),

    /// Failed to write cookies to the persistence layer.
    #[error("Failed to persist cookies to disk: {0}")]
    FailToPersistCookiesToDisk(std::io::Error),

    /// Encountered an invalid cookie header value.
    #[error("Invalid cookie header")]
    InvalidCookieHeader,
}
impl HttpError for CookieError {}

// Convert CookieError to unified zenwave::Error
impl From<CookieError> for crate::Error {
    fn from(err: CookieError) -> Self {
        use crate::error::CookieErrorKind;

        let kind = match err {
            CookieError::FailToLoadCookiesFromDisk(e) => CookieErrorKind::LoadFailed(e),
            CookieError::FailToParseCookiesFromDisk(e) => CookieErrorKind::ParseFailed(e),
            CookieError::FailToPersistCookiesToDisk(e) => CookieErrorKind::PersistFailed(e),
            CookieError::InvalidCookieHeader => CookieErrorKind::InvalidHeader,
        };

        Self::Cookie(kind)
    }
}

impl Default for CookieStore {
    fn default() -> Self {
        Self {
            store: CookieJar::new(),
            #[cfg(not(target_arch = "wasm32"))]
            persistence: None,
        }
    }
}

impl CookieStore {
    /// Enable persistent storage using the default path for the current crate.
    #[cfg(not(target_arch = "wasm32"))]
    #[must_use]
    pub fn persistent_default() -> Self {
        default_cookie_path().map_or_else(Self::default, Self::persistent_with_path)
    }

    /// Enable persistent storage using the provided path.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn persistent_with_path(path: impl Into<PathBuf>) -> Self {
        Self {
            store: CookieJar::new(),
            persistence: Some(Persistence::new(path.into())),
        }
    }

    async fn prepare(&mut self) -> Result<(), CookieError> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            if let Some(path) = self
                .persistence
                .as_ref()
                .filter(|p| !p.initialized)
                .map(|p| p.path.clone())
            {
                self.load_from_disk(&path).await?;
                if let Some(persistence) = self
                    .persistence
                    .as_mut()
                    .filter(|persist| persist.path == path)
                {
                    persistence.initialized = true;
                }
            }
        }
        Ok(())
    }

    #[allow(unused_variables)]
    async fn finalize(&self, updated: bool) -> Result<(), CookieError> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            if updated && let Some(persistence) = &self.persistence {
                self.persist_to_path(&persistence.path).await?;
            }
        }
        Ok(())
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn load_from_disk(&mut self, path: &Path) -> Result<(), CookieError> {
        let lock = file_mutex(path).await;
        let _guard = lock.lock().await;

        let data = match async_fs::read(path).await {
            Ok(data) => data,
            Err(err) if err.kind() == ErrorKind::NotFound => {
                return Ok(());
            }
            Err(err) => return Err(CookieError::FailToLoadCookiesFromDisk(err)),
        };

        if !data.is_empty() {
            let cookies: Vec<PersistedCookie> =
                serde_json::from_slice(&data).map_err(CookieError::FailToParseCookiesFromDisk)?;
            for stored in cookies {
                self.store.add(stored.into_cookie());
            }
        }

        Ok(())
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn persist_to_path(&self, path: &Path) -> Result<(), CookieError> {
        let lock = file_mutex(path).await;
        let _guard = lock.lock().await;

        let snapshot: Vec<PersistedCookie> = self
            .store
            .iter()
            .map(|cookie| PersistedCookie::from_cookie(cookie.clone()))
            .collect();
        let data = serde_json::to_vec(&snapshot).expect("failed to serialize cookies to JSON"); // Safety: Serialization should not fail.

        if let Some(parent) = path.parent() {
            async_fs::create_dir_all(parent)
                .await
                .map_err(CookieError::FailToPersistCookiesToDisk)?;
        }

        let tmp = path.with_extension("tmp");
        async_fs::write(&tmp, &data)
            .await
            .map_err(CookieError::FailToPersistCookiesToDisk)?;
        async_fs::rename(&tmp, path)
            .await
            .map_err(CookieError::FailToPersistCookiesToDisk)?;

        Ok(())
    }
}

impl Middleware for CookieStore {
    type Error = CookieError;
    async fn handle<E: Endpoint>(
        &mut self,
        request: &mut Request,
        mut next: E,
    ) -> Result<Response, http_kit::middleware::MiddlewareError<E::Error, Self::Error>> {
        self.prepare().await.map_err(MiddlewareError::Middleware)?;

        let cookie_header = self
            .store
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(";");

        request.headers_mut().insert(
            header::COOKIE,
            HeaderValue::from_maybe_shared(cookie_header)
                .map_err(|_| MiddlewareError::Middleware(CookieError::InvalidCookieHeader))?,
        );

        let res = next
            .respond(request)
            .await
            .map_err(MiddlewareError::Endpoint)?;

        let mut updated = false;
        for set_cookie in res.headers().get_all(header::SET_COOKIE) {
            let set_cookie = set_cookie
                .to_str()
                .map_err(|_| MiddlewareError::Middleware(CookieError::InvalidCookieHeader))?;
            let cookie = set_cookie
                .parse::<Cookie>()
                .map_err(|_| MiddlewareError::Middleware(CookieError::InvalidCookieHeader))?;
            self.store.add(cookie);
            updated = true;
        }
        self.finalize(updated)
            .await
            .map_err(MiddlewareError::Middleware)?;
        Ok(res)
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
struct Persistence {
    path: PathBuf,
    initialized: bool,
}

#[cfg(not(target_arch = "wasm32"))]
impl Persistence {
    #[allow(clippy::missing_const_for_fn)]
    fn new(path: PathBuf) -> Self {
        Self {
            path,
            initialized: false,
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn default_cookie_path() -> Option<PathBuf> {
    let dir = dirs::data_local_dir()?;
    let crate_name = env!("CARGO_PKG_NAME");
    Some(dir.join(format!("zenwave_cookie_store_{crate_name}.json")))
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Serialize, Deserialize)]
struct PersistedCookie {
    name: String,
    value: String,
    domain: Option<String>,
    path: Option<String>,
    secure: bool,
    http_only: bool,
    expires: Option<i128>,
}

#[cfg(not(target_arch = "wasm32"))]
impl PersistedCookie {
    fn from_cookie(cookie: Cookie<'_>) -> Self {
        let owned = cookie.into_owned();
        Self {
            name: owned.name().to_string(),
            value: owned.value().to_string(),
            domain: owned.domain().map(ToString::to_string),
            path: owned.path().map(ToString::to_string),
            secure: owned.secure().unwrap_or(false),
            http_only: owned.http_only().unwrap_or(false),
            expires: owned
                .expires_datetime()
                .map(|dt| i128::from(dt.unix_timestamp())),
        }
    }

    fn into_cookie(self) -> Cookie<'static> {
        let mut builder = Cookie::build((self.name, self.value));
        if let Some(domain) = self.domain {
            builder = builder.domain(domain);
        }
        if let Some(path) = self.path {
            builder = builder.path(path);
        }
        builder = builder.secure(self.secure).http_only(self.http_only);
        if let Some(timestamp) = self.expires
            && let Ok(secs) = i64::try_from(timestamp)
            && let Ok(datetime) = OffsetDateTime::from_unix_timestamp(secs)
        {
            builder = builder.expires(datetime);
        }
        builder.build()
    }
}

#[cfg(not(target_arch = "wasm32"))]
static COOKIE_FILE_LOCKS: LazyLock<AsyncMutex<HashMap<PathBuf, Arc<AsyncMutex<()>>>>> =
    LazyLock::new(|| AsyncMutex::new(HashMap::new()));

#[cfg(not(target_arch = "wasm32"))]
async fn file_mutex(path: &Path) -> Arc<AsyncMutex<()>> {
    let mut map = COOKIE_FILE_LOCKS.lock().await;
    map.entry(path.to_path_buf())
        .or_insert_with(|| Arc::new(AsyncMutex::new(())))
        .clone()
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use std::convert::Infallible;

    use super::*;
    use http::{Request as HttpRequest, Response as HttpResponse, StatusCode};
    use http_kit::Body;
    use tempfile::tempdir;

    #[test]
    fn persistent_store_roundtrip() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("cookies.json");

        async_io::block_on(async {
            let mut store = CookieStore::persistent_with_path(path.clone());
            let mut request = HttpRequest::builder()
                .method(http_kit::Method::GET)
                .uri("https://example.com")
                .body(Body::empty())
                .unwrap();

            let mut endpoint = SetCookieEndpoint;
            store.handle(&mut request, &mut endpoint).await.unwrap();

            let mut restored = CookieStore::persistent_with_path(path.clone());
            let mut echo = RecordingEndpoint::default();
            let mut request = HttpRequest::builder()
                .method(http_kit::Method::GET)
                .uri("https://example.com")
                .body(Body::empty())
                .unwrap();
            restored.handle(&mut request, &mut echo).await.unwrap();

            let header = echo.last_cookie().expect("cookie header missing");
            assert!(header.contains("session=abc"));
            assert!(header.contains("theme=dark"));
        });
    }

    struct SetCookieEndpoint;

    impl Endpoint for SetCookieEndpoint {
        type Error = Infallible;
        fn respond(
            &mut self,
            _request: &mut Request,
        ) -> impl std::future::Future<Output = Result<Response, Self::Error>> {
            std::future::ready(Ok(HttpResponse::builder()
                .status(StatusCode::OK)
                .header(header::SET_COOKIE, "session=abc; Path=/")
                .header(header::SET_COOKIE, "theme=dark; Path=/")
                .body(Body::empty())
                .unwrap()))
        }
    }

    #[derive(Default)]
    struct RecordingEndpoint {
        last_cookie: Option<String>,
    }

    impl RecordingEndpoint {
        fn last_cookie(&self) -> Option<String> {
            self.last_cookie.clone()
        }
    }

    impl Endpoint for RecordingEndpoint {
        type Error = Infallible;
        fn respond(
            &mut self,
            request: &mut Request,
        ) -> impl std::future::Future<Output = Result<Response, Self::Error>> {
            self.last_cookie = request
                .headers()
                .get(header::COOKIE)
                .and_then(|value| value.to_str().ok())
                .map(str::to_owned);

            std::future::ready(Ok(HttpResponse::builder()
                .status(StatusCode::OK)
                .body(Body::empty())
                .unwrap()))
        }
    }
}