fynd-rpc 0.110.2

HTTP RPC server for Fynd DEX router
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! HTTP metrics middleware.
//!
//! Records `http_request_duration_seconds{endpoint, method, status}` (histogram; no user
//! labels so bucket cardinality stays bounded) and
//! `http_requests_total{endpoint, status, user_identity, user_plan, client_version}`
//! (counter carrying the per-client dimensions).
//!
//! `User-Identity` and `X-User-Plan` are injected by an upstream auth proxy in hosted
//! deployments; direct traffic (health probes, deployments without the proxy) falls back
//! to bounded sentinel values. A `User-Identity` value with bytes outside the label
//! alphabet is slugified, not discarded, so every client keeps its own series.

use std::time::Instant;

use actix_web::{
    body::MessageBody,
    dev::{ServiceRequest, ServiceResponse},
    http::header::HeaderMap,
    middleware::Next,
    HttpMessage, HttpRequest,
};
use metrics::{counter, histogram};
use serde::Serialize;

/// Who made a request: the proxy-injected client headers as sent, capped at
/// `MAX_CLIENT_VALUE_CHARS`, plus the bounded labels the metrics use for the same client.
#[derive(Debug, Clone, Serialize)]
pub struct ClientInfo {
    user_identity: String,
    user_plan: String,
    client_version: String,
    #[serde(skip)]
    labels: ClientLabels,
}

/// Longest header value a record keeps. `User-Identity` and `X-User-Plan` come from the
/// authenticating proxy, but `User-Agent` is whatever the caller sent, and a record is not the
/// place to store a kilobyte of it.
const MAX_CLIENT_VALUE_CHARS: usize = 128;

impl ClientInfo {
    /// Reads the proxy-injected headers.
    #[must_use]
    pub fn from_headers(headers: &HeaderMap) -> Self {
        let raw = |name: &str, absent: &str| {
            headers.get(name).map_or_else(
                || absent.to_string(),
                |value| {
                    String::from_utf8_lossy(value.as_bytes())
                        .chars()
                        .take(MAX_CLIENT_VALUE_CHARS)
                        .collect()
                },
            )
        };
        let user_identity = match raw("user-identity", "unknown") {
            value if value.is_empty() => "invalid".to_string(),
            value => value,
        };
        Self {
            user_identity,
            user_plan: raw("x-user-plan", "none"),
            client_version: raw("user-agent", "unknown"),
            labels: ClientLabels::from_headers(headers),
        }
    }

    /// Reads what the metrics middleware stashed for this request, falling back to the headers
    /// when it is not installed — an embedder may configure its own app.
    #[must_use]
    pub fn from_request(request: &HttpRequest) -> Self {
        request
            .extensions()
            .get::<Self>()
            .cloned()
            .unwrap_or_else(|| Self::from_headers(request.headers()))
    }

    /// The bounded values the metric labels carry.
    pub(crate) fn labels(&self) -> &ClientLabels {
        &self.labels
    }
}

/// Per-client label values extracted from proxy-injected headers.
#[derive(Debug, Clone)]
pub(crate) struct ClientLabels {
    pub(crate) user_identity: String,
    pub(crate) user_plan: String,
    pub(crate) client_version: String,
}

impl ClientLabels {
    pub(crate) fn from_headers(headers: &HeaderMap) -> Self {
        let header_value = |name: &str| {
            headers
                .get(name)
                .and_then(|value| value.to_str().ok())
        };
        Self {
            user_identity: match headers.get("user-identity") {
                Some(value) => {
                    slugify_label(value.as_bytes()).unwrap_or_else(|| "invalid".to_string())
                }
                None => "unknown".to_string(),
            },
            user_plan: header_value("x-user-plan")
                .map(|value| sanitize_label(value, "invalid").to_string())
                .unwrap_or_else(|| "none".to_string()),
            client_version: header_value("user-agent")
                .map(sanitize_client_version)
                .unwrap_or("unknown")
                .to_string(),
        }
    }
}

const MAX_LABEL_LEN: usize = 64;

fn is_label_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'/')
}

/// Accepts bounded, printable-ASCII label values (`[A-Za-z0-9._/-]`, ≤64 chars); anything
/// else — including a misconfigured or bypassed proxy forwarding attacker-controlled
/// input — collapses to `fallback`. Keeping label cardinality bounded is what keeps
/// Prometheus scraping cheap.
fn sanitize_label<'a>(value: &'a str, fallback: &'static str) -> &'a str {
    let well_formed =
        value.len() <= MAX_LABEL_LEN && !value.is_empty() && value.bytes().all(is_label_byte);
    if well_formed {
        value
    } else {
        fallback
    }
}

/// Rewrites a raw header value into a label value (`[A-Za-z0-9._/-]`, ≤64 bytes): every
/// other byte becomes `-` and the result is cut at 64 bytes. A well-formed value passes
/// through unchanged, so existing series keep their names. Returns `None` for an empty
/// value. Discarding the whole value instead would collapse every client whose name has a
/// space or a non-ASCII byte into one shared series, and the name would never be recorded.
fn slugify_label(value: &[u8]) -> Option<String> {
    if value.is_empty() {
        return None;
    }
    let slug = value
        .iter()
        .take(MAX_LABEL_LEN)
        .map(|&byte| if is_label_byte(byte) { byte as char } else { '-' })
        .collect();
    Some(slug)
}

/// Accepts only `product/version` tokens (e.g. `fynd-client/0.9.0`) as label values;
/// anything else collapses to `other`. Raw User-Agents are client-controlled and would
/// mint unbounded Prometheus series.
fn sanitize_client_version(user_agent: &str) -> &str {
    let mut parts = user_agent.splitn(2, '/');
    let (Some(product), Some(version)) = (parts.next(), parts.next()) else { return "other" };
    if product.is_empty() || version.is_empty() {
        return "other";
    }
    sanitize_label(user_agent, "other")
}

/// Emits both HTTP metrics for one completed request.
pub(crate) fn record_request(
    endpoint: &str,
    method: &str,
    status: u16,
    elapsed: std::time::Duration,
    client: &ClientLabels,
) {
    histogram!(
        "http_request_duration_seconds",
        "endpoint" => endpoint.to_string(),
        "method" => method.to_string(),
        "status" => status.to_string(),
    )
    .record(elapsed.as_secs_f64());
    counter!(
        "http_requests_total",
        "endpoint" => endpoint.to_string(),
        "status" => status.to_string(),
        "user_identity" => client.user_identity.clone(),
        "user_plan" => client.user_plan.clone(),
        "client_version" => client.client_version.clone(),
    )
    .increment(1);
}

/// Actix middleware: times every request and records the metrics above.
pub(crate) async fn http_metrics_middleware(
    req: ServiceRequest,
    next: Next<impl MessageBody>,
) -> Result<ServiceResponse<impl MessageBody>, actix_web::Error> {
    let start = Instant::now();
    // Matched route pattern, not the raw path: unmatched requests (scanners, typos) must
    // not mint unbounded label values.
    let endpoint = req
        .match_pattern()
        .unwrap_or_else(|| "other".to_string());
    let method = req.method().to_string();
    // Stashed so the quote handler reads the headers once per request rather than twice.
    let client = ClientInfo::from_headers(req.headers());
    req.extensions_mut()
        .insert(client.clone());

    let result = next.call(req).await;

    let status = match &result {
        Ok(response) => response.status().as_u16(),
        Err(error) => error
            .as_response_error()
            .status_code()
            .as_u16(),
    };
    record_request(&endpoint, &method, status, start.elapsed(), client.labels());
    result
}

#[cfg(test)]
mod tests {
    use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};

    use super::*;

    /// Finds the debug value recorded for `name` carrying every label in `labels`.
    fn find_metric<'a>(
        recorded: &'a [(
            metrics_util::CompositeKey,
            Option<metrics::Unit>,
            Option<metrics::SharedString>,
            metrics_util::debugging::DebugValue,
        )],
        name: &str,
        labels: &[(&str, &str)],
    ) -> &'a metrics_util::debugging::DebugValue {
        recorded
            .iter()
            .find(|(key, _, _, _)| {
                key.key().name() == name &&
                    labels
                        .iter()
                        .all(|(label_key, label_value)| {
                            key.key()
                                .labels()
                                .any(|l| l.key() == *label_key && l.value() == *label_value)
                        })
            })
            .map(|(_, _, _, value)| value)
            .unwrap_or_else(|| panic!("missing {name}{labels:?}, got {recorded:?}"))
    }

    #[test]
    fn client_labels_read_proxy_headers() {
        let mut headers = HeaderMap::new();
        headers.insert(HeaderName::from_static("user-identity"), HeaderValue::from_static("alice"));
        headers.insert(HeaderName::from_static("x-user-plan"), HeaderValue::from_static("scale"));
        headers.insert(
            HeaderName::from_static("user-agent"),
            HeaderValue::from_static("fynd-client/0.9.0"),
        );

        let labels = ClientLabels::from_headers(&headers);
        assert_eq!(labels.user_identity, "alice");
        assert_eq!(labels.user_plan, "scale");
        assert_eq!(labels.client_version, "fynd-client/0.9.0");
    }

    #[test]
    fn client_labels_default_to_sentinels() {
        let labels = ClientLabels::from_headers(&HeaderMap::new());
        assert_eq!(labels.user_identity, "unknown");
        assert_eq!(labels.user_plan, "none");
        assert_eq!(labels.client_version, "unknown");
    }

    #[test]
    fn slugify_label_passes_well_formed_value() {
        assert_eq!(
            slugify_label(b"fynd-preissue-20260720-014"),
            Some("fynd-preissue-20260720-014".to_string())
        );
        assert_eq!(slugify_label(b"Relay"), Some("Relay".to_string()));
        let max_len_value = "a".repeat(64);
        assert_eq!(slugify_label(max_len_value.as_bytes()), Some(max_len_value.clone()));
    }

    #[test]
    fn slugify_label_replaces_illegal_bytes() {
        assert_eq!(slugify_label(b"Relay - FOMO"), Some("Relay---FOMO".to_string()));
        assert_eq!(
            slugify_label(b"scale; DROP TABLE users"),
            Some("scale--DROP-TABLE-users".to_string())
        );
        // `É` is two UTF-8 bytes, so it becomes two hyphens.
        assert_eq!(slugify_label("Émile".as_bytes()), Some("--mile".to_string()));
    }

    #[test]
    fn slugify_label_truncates_to_max_len() {
        let oversized = "a".repeat(65);
        assert_eq!(slugify_label(oversized.as_bytes()), Some("a".repeat(64)));
    }

    #[test]
    fn slugify_label_rejects_empty_value() {
        assert_eq!(slugify_label(b""), None);
    }

    #[test]
    fn sanitize_client_version_accepts_product_token() {
        assert_eq!(sanitize_client_version("fynd-client/0.9.0"), "fynd-client/0.9.0");
    }

    #[test]
    fn sanitize_client_version_rejects_browser_user_agent() {
        // Contains spaces and parens, which are not valid token characters.
        assert_eq!(sanitize_client_version("Mozilla/5.0 (X11; Linux) AppleWebKit/537.36"), "other");
    }

    #[test]
    fn sanitize_client_version_rejects_over_length_cap() {
        let long_version = "a".repeat(64);
        let user_agent = format!("fynd-client/{long_version}");
        assert!(user_agent.len() > 64);
        assert_eq!(sanitize_client_version(&user_agent), "other");
    }

    #[test]
    fn client_labels_sanitizes_garbage_user_agent() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("user-agent"),
            HeaderValue::from_static("Mozilla/5.0 (X11; Linux) AppleWebKit/537.36"),
        );
        let labels = ClientLabels::from_headers(&headers);
        assert_eq!(labels.client_version, "other");
    }

    #[test]
    fn client_labels_slugifies_user_identity() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("user-identity"),
            HeaderValue::from_static("Relay - FOMO"),
        );
        let labels = ClientLabels::from_headers(&headers);
        assert_eq!(labels.user_identity, "Relay---FOMO");
    }

    #[test]
    fn test_client_info_keeps_what_the_client_sent() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("user-identity"),
            HeaderValue::from_static("Relay - FOMO"),
        );
        headers.insert(
            HeaderName::from_static("user-agent"),
            HeaderValue::from_static("Mozilla/5.0 (X11; Linux)"),
        );
        let oversized = "a".repeat(80);
        headers.insert(
            HeaderName::from_static("x-user-plan"),
            HeaderValue::from_str(&oversized).unwrap(),
        );

        let info = ClientInfo::from_headers(&headers);
        assert_eq!(info.user_identity, "Relay - FOMO");
        assert_eq!(info.user_plan, oversized, "the record is not bound by label length");
        assert_eq!(info.client_version, "Mozilla/5.0 (X11; Linux)");

        // The metric labels stay bounded and slugified.
        assert_eq!(info.labels().user_identity, "Relay---FOMO");
        assert_eq!(info.labels().user_plan, "invalid");
        assert_eq!(info.labels().client_version, "other");
    }

    #[test]
    fn test_client_info_caps_value_length() {
        let mut headers = HeaderMap::new();
        let long_agent = "x".repeat(MAX_CLIENT_VALUE_CHARS + 50);
        headers.insert(
            HeaderName::from_static("user-agent"),
            HeaderValue::from_str(&long_agent).unwrap(),
        );

        let info = ClientInfo::from_headers(&headers);
        assert_eq!(info.client_version.chars().count(), MAX_CLIENT_VALUE_CHARS);
    }

    #[test]
    fn test_client_info_defaults_to_sentinels() {
        let info = ClientInfo::from_headers(&HeaderMap::new());
        assert_eq!(info.user_identity, "unknown");
        assert_eq!(info.user_plan, "none");
        assert_eq!(info.client_version, "unknown");
    }

    #[test]
    fn test_client_info_marks_empty_identity_invalid() {
        let mut headers = HeaderMap::new();
        headers.insert(HeaderName::from_static("user-identity"), HeaderValue::from_static(""));
        let info = ClientInfo::from_headers(&headers);
        // Distinct from `unknown`: the proxy sent the header with nothing in it.
        assert_eq!(info.user_identity, "invalid");
    }

    #[test]
    fn client_labels_slugifies_non_ascii_user_identity() {
        let mut headers = HeaderMap::new();
        // Bytes 0x80–0xFF are valid header bytes but fail `HeaderValue::to_str`. The label
        // must come from the raw bytes, or this client falls back to `unknown`.
        headers.insert(
            HeaderName::from_static("user-identity"),
            HeaderValue::from_bytes("Émile".as_bytes()).unwrap(),
        );
        let labels = ClientLabels::from_headers(&headers);
        assert_eq!(labels.user_identity, "--mile");
    }

    #[test]
    fn client_labels_truncates_oversized_user_identity() {
        let mut headers = HeaderMap::new();
        let oversized = "a".repeat(65);
        headers.insert(
            HeaderName::from_static("user-identity"),
            HeaderValue::from_str(&oversized).unwrap(),
        );
        let labels = ClientLabels::from_headers(&headers);
        assert_eq!(labels.user_identity, "a".repeat(64));
    }

    #[test]
    fn client_labels_marks_empty_user_identity_invalid() {
        let mut headers = HeaderMap::new();
        headers.insert(HeaderName::from_static("user-identity"), HeaderValue::from_static(""));
        let labels = ClientLabels::from_headers(&headers);
        // Distinct from the "unknown" sentinel used when the header is absent: the proxy sent
        // the header with nothing in it, which signals a misbehaving upstream.
        assert_eq!(labels.user_identity, "invalid");
    }

    #[test]
    fn client_labels_sanitizes_garbage_user_plan() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-user-plan"),
            HeaderValue::from_static("scale; DROP TABLE users"),
        );
        let labels = ClientLabels::from_headers(&headers);
        assert_eq!(labels.user_plan, "invalid");
    }

    #[test]
    fn record_request_emits_both_metrics() {
        use metrics_util::debugging::DebugValue;

        let recorder = metrics_util::debugging::DebuggingRecorder::new();
        let snapshotter = recorder.snapshotter();
        metrics::with_local_recorder(&recorder, || {
            record_request(
                "/v1/quote",
                "POST",
                200,
                std::time::Duration::from_millis(42),
                &ClientLabels {
                    user_identity: "alice".to_string(),
                    user_plan: "scale".to_string(),
                    client_version: "fynd-client/0.9.0".to_string(),
                },
            );
        });

        let recorded = snapshotter.snapshot().into_vec();

        match find_metric(
            &recorded,
            "http_request_duration_seconds",
            &[("endpoint", "/v1/quote"), ("method", "POST"), ("status", "200")],
        ) {
            DebugValue::Histogram(samples) => {
                assert_eq!(samples.len(), 1, "expected exactly one recorded duration sample");
                let sample = samples[0].into_inner();
                assert!(
                    (sample - 0.042).abs() < 1e-9,
                    "expected duration sample ~0.042, got {sample}"
                );
            }
            other => panic!("http_request_duration_seconds is not a histogram: {other:?}"),
        }

        match find_metric(
            &recorded,
            "http_requests_total",
            &[
                ("endpoint", "/v1/quote"),
                ("status", "200"),
                ("user_identity", "alice"),
                ("user_plan", "scale"),
                ("client_version", "fynd-client/0.9.0"),
            ],
        ) {
            DebugValue::Counter(value) => {
                assert_eq!(*value, 1, "expected counter == 1, got {value}");
            }
            other => panic!("http_requests_total is not a counter: {other:?}"),
        }
    }

    #[test]
    fn http_metrics_middleware_records_matched_and_unmatched_requests() {
        use actix_web::{web, App, HttpResponse};
        use metrics_util::debugging::DebugValue;

        let recorder = metrics_util::debugging::DebuggingRecorder::new();
        let snapshotter = recorder.snapshotter();
        // A plain current-thread runtime, not #[actix_web::test]: the local recorder is a
        // thread-local, and actix's own test executor does not guarantee the middleware runs
        // on the same OS thread that installed the recorder.
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime builds");

        metrics::with_local_recorder(&recorder, || {
            rt.block_on(async {
                let app = actix_web::test::init_service(
                    App::new()
                        .wrap(actix_web::middleware::from_fn(http_metrics_middleware))
                        .route("/v1/thing", web::get().to(HttpResponse::Ok)),
                )
                .await;

                let matched = actix_web::test::TestRequest::get()
                    .uri("/v1/thing")
                    .to_request();
                let matched_resp = actix_web::test::call_service(&app, matched).await;
                assert_eq!(matched_resp.status().as_u16(), 200);

                let unmatched = actix_web::test::TestRequest::get()
                    .uri("/does-not-exist")
                    .to_request();
                let unmatched_resp = actix_web::test::call_service(&app, unmatched).await;
                assert_eq!(unmatched_resp.status().as_u16(), 404);
            });
        });

        let recorded = snapshotter.snapshot().into_vec();

        match find_metric(
            &recorded,
            "http_requests_total",
            &[("endpoint", "/v1/thing"), ("status", "200")],
        ) {
            DebugValue::Counter(value) => {
                assert_eq!(*value, 1, "expected matched-route counter == 1, got {value}");
            }
            other => panic!("http_requests_total (matched) is not a counter: {other:?}"),
        }

        match find_metric(
            &recorded,
            "http_requests_total",
            &[("endpoint", "other"), ("status", "404")],
        ) {
            DebugValue::Counter(value) => {
                assert_eq!(*value, 1, "expected unmatched-route counter == 1, got {value}");
            }
            other => panic!("http_requests_total (unmatched) is not a counter: {other:?}"),
        }
    }
}