uxar 0.1.3

Opinionated Rust web framework built on Axum for Postgres-backed JSON APIs
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use axum::{
    body::Body,
    extract::Request,
    http::{header, Method, StatusCode},
    response::Response,
};
use bytes::Bytes;
use rust_silos::SiloSet;
use std::{
    collections::HashMap,
    convert::Infallible,
    future::Future,
    io::Read,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};
use tower::Service;
use parking_lot::RwLock;

// Add these deps (recommended):
// percent-encoding = "2"
// mime_guess = "2"
// blake3 = "1"
use blake3::Hasher as Blake3;
use mime_guess::MimeGuess;
use percent_encoding::percent_decode_str;

pub struct AssetServe {
    silos: Arc<SiloSet>,
    prefix: Arc<str>,
    precompressed: bool,
    etag: bool,
    etag_cache: Arc<RwLock<HashMap<String, String>>>,
}

impl AssetServe {
    /// `folder` is the silo-root folder (e.g. "www" or "www/assets")
    pub fn new(silos: SiloSet, folder: &str) -> Self {
        Self {
            silos: Arc::new(silos),
            prefix: normalize_prefix(folder).into(),
            precompressed: false,
            etag: false,
            etag_cache: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// If enabled, will try `.br` then `.gz` variants based on Accept-Encoding.
    pub fn precompressed(mut self, enabled: bool) -> Self {
        self.precompressed = enabled;
        self
    }

    /// If enabled, returns strong ETags computed from served bytes (works for br/gz too).
    pub fn with_etag(mut self, enabled: bool) -> Self {
        self.etag = enabled;
        self
    }
}

impl Service<Request> for AssetServe {
    type Response = Response;
    type Error = Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;

    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: Request) -> Self::Future {
        let method = req.method().clone();
        let raw_path = req.uri().path().to_string();

        let silos = Arc::clone(&self.silos);
        let prefix = Arc::clone(&self.prefix);
        let precompressed = self.precompressed;
        let use_etag = self.etag;
        let cache = Arc::clone(&self.etag_cache);

        let accept_encoding = req
            .headers()
            .get(header::ACCEPT_ENCODING)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string());

        let if_none_match = if use_etag {
            req.headers()
                .get(header::IF_NONE_MATCH)
                .and_then(|v| v.to_str().ok())
                .map(|s| s.to_string())
        } else {
            None
        };

        Box::pin(async move {
            Ok(serve_file_impl(
                &silos,
                &prefix,
                &method,
                &raw_path,
                precompressed,
                accept_encoding.as_deref(),
                if_none_match.as_deref(),
                use_etag,
                &cache,
            )
            .await)
        })
    }
}

async fn serve_file_impl(
    silos: &SiloSet,
    prefix: &str,
    method: &Method,
    raw_path: &str,
    precompressed: bool,
    accept_encoding: Option<&str>,
    if_none_match: Option<&str>,
    use_etag: bool,
    cache: &RwLock<HashMap<String, String>>,
) -> Response {
    // Only GET/HEAD for static
    if *method != Method::GET && *method != Method::HEAD {
        return Response::builder()
            .status(StatusCode::METHOD_NOT_ALLOWED)
            .body(Body::empty())
            .unwrap();
    }

    // Decode & normalize path safely
    let clean_rel = match clean_rel_path(raw_path) {
        Some(p) => p,
        None => return not_found(),
    };

    // Build lookup path inside silo root
    let logical_path = join_prefix(prefix, &clean_rel);

    // Select and read bytes (possibly precompressed variant)
    let (served_path, bytes, content_encoding) = match read_best_variant(
        silos,
        &logical_path,
        precompressed,
        accept_encoding,
    )
    .await
    {
        Some(v) => v,
        None => return not_found(),
    };

    // Compute or retrieve cached ETag
    let etag_val = if use_etag {
        Some(get_or_compute_etag(cache, &served_path, &bytes, silos).await)
    } else {
        None
    };

    if let (Some(etag), Some(client_etag)) = (etag_val.as_deref(), if_none_match) {
        // Very simple exact match. (If client sends a list, you can extend later.)
        if client_etag.trim() == etag {
            return not_modified(etag, precompressed);
        }
    }

    // Build response headers
    let mut builder = Response::builder().status(StatusCode::OK);

    // Content-Type
    let mime = guess_mime(&served_path);
    builder = builder.header(header::CONTENT_TYPE, mime);

    // Content-Encoding for br/gz variants
    if let Some(enc) = content_encoding {
        builder = builder.header(header::CONTENT_ENCODING, enc);
    }

    // Vary if we do content negotiation
    if precompressed {
        builder = builder.header(header::VARY, "Accept-Encoding");
    }

    // Cache-Control policy
    builder = builder.header(header::CACHE_CONTROL, cache_control_for(&served_path));

    // ETag
    if let Some(etag) = etag_val.as_deref() {
        builder = builder.header(header::ETAG, etag);
    }

    // Content-Length
    builder = builder.header(header::CONTENT_LENGTH, bytes.len().to_string());

    // HEAD returns headers only
    if *method == Method::HEAD {
        return builder.body(Body::empty()).unwrap();
    }

    builder.body(Body::from(bytes)).unwrap()
}

async fn read_best_variant(
    silos: &SiloSet,
    logical_path: &str,
    precompressed: bool,
    accept_encoding: Option<&str>,
) -> Option<(String, Bytes, Option<&'static str>)> {
    if !precompressed {
        let bytes = try_read_file(silos, logical_path).await?;
        return Some((logical_path.to_string(), bytes, None));
    }

    // Prefer br then gzip, but respect Accept-Encoding q=0
    let ae = AcceptEncoding::parse(accept_encoding);

    if ae.allows("br") {
        let p = format!("{logical_path}.br");
        if let Some(bytes) = try_read_file(silos, &p).await {
            return Some((p, bytes, Some("br")));
        }
    }

    if ae.allows("gzip") || ae.allows("gz") {
        let p = format!("{logical_path}.gz");
        if let Some(bytes) = try_read_file(silos, &p).await {
            return Some((p, bytes, Some("gzip")));
        }
    }

    // Fallback to identity
    let bytes = try_read_file(silos, logical_path).await?;
    Some((logical_path.to_string(), bytes, None))
}

async fn try_read_file(silos: &SiloSet, path: &str) -> Option<Bytes> {
    let file = silos.get_file(path)?;

    if file.is_embedded() {
        let mut reader = file.reader().ok()?;
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf).ok()?;
        Some(Bytes::from(buf))
    } else {
        tokio::fs::read(file.path()).await.ok().map(Bytes::from)
    }
}

/// Safely convert a URL path ("/a/b/../c") into a clean relative path ("a/b/c").
/// - percent-decodes
/// - rejects parent-dir and backslashes
/// - strips leading slashes
fn clean_rel_path(raw_path: &str) -> Option<String> {
    // raw_path is URI path (no query). Still, percent-decoding is needed.
    let stripped = raw_path.trim_start_matches('/');

    // Percent-decode. If invalid UTF-8, reject.
    let decoded = percent_decode_str(stripped).decode_utf8().ok()?;

    // Reject any backslashes early (Windows path games)
    if decoded.contains('\\') {
        return None;
    }

    // Normalize segments, rejecting ".." and "."
    let mut out = String::with_capacity(decoded.len());
    for seg in decoded.split('/') {
        if seg.is_empty() {
            continue;
        }
        if seg == "." || seg == ".." {
            return None;
        }
        // Disallow NUL or other weirdness
        if seg.contains('\0') {
            return None;
        }
        if !out.is_empty() {
            out.push('/');
        }
        out.push_str(seg);
    }

    Some(out)
}

fn normalize_prefix(folder: &str) -> String {
    if folder.is_empty() {
        return String::new();
    }
    let trimmed = folder.trim_matches('/');
    let mut s = String::with_capacity(trimmed.len() + 1);
    s.push_str(trimmed);
    s.push('/');
    s
}

fn join_prefix(prefix: &str, rel: &str) -> String {
    if prefix.is_empty() {
        rel.to_string()
    } else if rel.is_empty() {
        // allow serving prefix root? usually not used; kept for completeness
        prefix.trim_end_matches('/').to_string()
    } else {
        let mut result = String::with_capacity(prefix.len() + rel.len());
        result.push_str(prefix);
        result.push_str(rel);
        result
    }
}

fn guess_mime(path: &str) -> String {
    // mime_guess returns a Mime; include charset for text types if you want.
    let guess: MimeGuess = mime_guess::from_path(path);
    guess
        .first_or_octet_stream()
        .essence_str()
        .to_string()
}

fn cache_control_for(path: &str) -> &'static str {
    // Conservative rule:
    // - HTML: no-cache (avoid hard-stale pages)
    // - Everything else: long cache, immutable-ish (best when filenames are hashed)
    if path.ends_with(".html") {
        "no-cache"
    } else {
        "public, max-age=31536000, immutable"
    }
}

async fn get_or_compute_etag(
    cache: &RwLock<HashMap<String, String>>,
    path: &str,
    bytes: &Bytes,
    silos: &SiloSet,
) -> String {
    let file = silos.get_file(path);
    let is_embedded = file.as_ref().map(|f| f.is_embedded()).unwrap_or(false);

    let cache_key = if is_embedded {
        path.to_string()
    } else {
        match file.as_ref().and_then(|f| std::fs::metadata(f.path()).ok()) {
            Some(meta) => {
                let mtime = meta.modified()
                    .ok()
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                format!("{path}:{mtime}:{}", meta.len())
            }
            None => return strong_etag(bytes),
        }
    };

    {
        let cache_read = cache.read();
        if let Some(etag) = cache_read.get(&cache_key) {
            return etag.clone();
        }
    }

    let etag = strong_etag(bytes);
    cache.write().insert(cache_key, etag.clone());
    etag
}

fn strong_etag(bytes: &Bytes) -> String {
    let mut h = Blake3::new();
    h.update(bytes);
    let digest = h.finalize();
    format!("\"{}\"", digest.to_hex())
}

fn not_modified(etag: &str, precompressed: bool) -> Response {
    let mut builder = Response::builder()
        .status(StatusCode::NOT_MODIFIED)
        .header(header::ETAG, etag);

    if precompressed {
        builder = builder.header(header::VARY, "Accept-Encoding");
    }

    builder.body(Body::empty()).unwrap()
}

fn not_found() -> Response {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(Body::empty())
        .unwrap()
}

/// Minimal Accept-Encoding parser that respects `q=0` disable.
/// Not a full RFC implementation, but avoids the biggest correctness bug.
#[derive(Debug, Clone)]
struct AcceptEncoding {
    br_q: f32,
    gzip_q: f32,
    star_q: f32,
}

impl AcceptEncoding {
    fn parse(h: Option<&str>) -> Self {
        // Defaults: identity implied; encodings not listed are not allowed unless '*'
        let mut ae = AcceptEncoding {
            br_q: -1.0,
            gzip_q: -1.0,
            star_q: -1.0,
        };

        let Some(s) = h else { return ae };

        for part in s.split(',') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }

            let mut pieces = part.split(';').map(|x| x.trim());
            let enc = pieces.next().unwrap_or("");
            let mut q = 1.0f32;

            for p in pieces {
                if let Some(v) = p.strip_prefix("q=") {
                    if let Ok(val) = v.parse::<f32>() {
                        q = val;
                    }
                }
            }

            match enc {
                "br" => ae.br_q = q,
                "gzip" | "gz" => ae.gzip_q = q,
                "*" => ae.star_q = q,
                _ => {}
            }
        }

        ae
    }

    fn allows(&self, enc: &str) -> bool {
        let q = match enc {
            "br" => self.br_q,
            "gzip" | "gz" => self.gzip_q,
            _ => -1.0,
        };

        if q >= 0.0 {
            return q > 0.0;
        }

        // Not explicitly mentioned: only allowed if '*' has q>0
        if self.star_q >= 0.0 {
            return self.star_q > 0.0;
        }

        // Otherwise: treat as not allowed
        false
    }
}