fynd-rpc 0.105.0

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
//! 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,
};
use metrics::{counter, histogram};

/// Per-client label values extracted from proxy-injected headers.
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();
    let client = ClientLabels::from_headers(req.headers());

    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);
    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 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:?}"),
        }
    }
}