sonda-server 1.22.0

HTTP control plane for Sonda — synthetic telemetry generator
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
//! HTTP route definitions for sonda-server.

pub mod events;
pub mod health;
pub mod metrics;
pub mod ready;
pub mod scenarios;
pub mod sink_warnings;

use std::sync::Arc;
use std::time::Duration;

use axum::http::StatusCode;
use axum::middleware;
use axum::routing::{get, post};
use axum::Router;
use tokio::sync::Semaphore;
use tower::limit::GlobalConcurrencyLimitLayer;
use tower::ServiceBuilder;
use tower_http::limit::RequestBodyLimitLayer;
use tower_http::timeout::TimeoutLayer;

use crate::auth::require_api_key;
use crate::middleware::metrics::record_request_metrics;
use crate::state::AppState;

#[derive(Clone)]
pub struct RouterConfig {
    pub request_timeout: Duration,
    pub max_body_bytes: usize,
    pub inflight_semaphore: Arc<Semaphore>,
}

impl RouterConfig {
    #[allow(dead_code)]
    pub fn test_defaults() -> Self {
        Self {
            request_timeout: Duration::from_secs(30),
            max_body_bytes: 1_048_576,
            inflight_semaphore: Arc::new(Semaphore::new(Semaphore::MAX_PERMITS)),
        }
    }
}

#[allow(dead_code)]
pub fn router(state: AppState) -> Router {
    router_with_config(state, RouterConfig::test_defaults())
}

pub fn router_with_config(state: AppState, cfg: RouterConfig) -> Router {
    let public = Router::new()
        .route("/health", get(health::health))
        .route("/ready", get(ready::ready));

    let protected_observability = Router::new()
        .route("/scenarios/{id}/stats", get(scenarios::get_scenario_stats))
        .route(
            "/scenarios/{id}/metrics",
            get(scenarios::get_scenario_metrics),
        )
        .route("/scenarios/metrics", get(scenarios::get_aggregate_metrics))
        .route("/metrics", get(metrics::get_metrics))
        .route_layer(middleware::from_fn_with_state(
            state.clone(),
            record_request_metrics,
        ))
        .route_layer(middleware::from_fn_with_state(
            state.clone(),
            require_api_key,
        ));

    // RequestBodyLimit must wrap a service whose response body is
    // axum::body::Body; Timeout wraps the response into a type that
    // RequestBodyLimitLayer's downstream bound rejects, so timeout goes
    // inside the body limit at the layer-application level.
    let control_stack = ServiceBuilder::new()
        .layer(RequestBodyLimitLayer::new(cfg.max_body_bytes))
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            cfg.request_timeout,
        ))
        .layer(GlobalConcurrencyLimitLayer::with_semaphore(
            cfg.inflight_semaphore.clone(),
        ));

    let protected_control = Router::new()
        .route(
            "/scenarios",
            get(scenarios::list_scenarios).post(scenarios::post_scenario),
        )
        .route(
            "/scenarios/{id}",
            get(scenarios::get_scenario).delete(scenarios::delete_scenario),
        )
        .route("/events", post(events::post_events))
        .route_layer(middleware::from_fn_with_state(
            state.clone(),
            record_request_metrics,
        ))
        .route_layer(middleware::from_fn_with_state(
            state.clone(),
            require_api_key,
        ))
        .layer(control_stack);

    public
        .merge(protected_observability)
        .merge(protected_control)
        .with_state(state)
}

#[cfg(test)]
mod tests {
    use super::*;
    use http_body_util::BodyExt;
    use hyper::{Request, StatusCode};
    use tower::ServiceExt;

    /// Helper: build the router with empty state (no auth) for test use.
    fn test_router() -> Router {
        router(AppState::new())
    }

    /// Helper: build the router with API key authentication enabled.
    fn test_router_with_key(key: &str) -> Router {
        router(AppState::with_api_key(Some(key.to_string())))
    }

    /// GET /health returns HTTP 200.
    #[tokio::test]
    async fn get_health_returns_200() {
        let app = test_router();
        let request = Request::builder()
            .uri("/health")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::OK,
            "GET /health must return 200 OK"
        );
    }

    /// GET /health returns JSON body with {"status": "ok"}.
    #[tokio::test]
    async fn get_health_returns_status_ok_json() {
        let app = test_router();
        let request = Request::builder()
            .uri("/health")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        let body_bytes = response.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value =
            serde_json::from_slice(&body_bytes).expect("body must be valid JSON");

        assert_eq!(
            body,
            serde_json::json!({ "status": "ok" }),
            "GET /health must return {{\"status\": \"ok\"}}"
        );
    }

    /// GET /health sets Content-Type to application/json.
    #[tokio::test]
    async fn get_health_sets_json_content_type() {
        let app = test_router();
        let request = Request::builder()
            .uri("/health")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        let ct = response
            .headers()
            .get("content-type")
            .expect("response must have Content-Type header")
            .to_str()
            .unwrap();

        assert!(
            ct.contains("application/json"),
            "Content-Type must be application/json, got: {ct}"
        );
    }

    /// An unknown route returns HTTP 404.
    #[tokio::test]
    async fn unknown_route_returns_404() {
        let app = test_router();
        let request = Request::builder()
            .uri("/nonexistent")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::NOT_FOUND,
            "unknown route must return 404"
        );
    }

    /// POST /health returns 405 Method Not Allowed (only GET is registered).
    #[tokio::test]
    async fn post_health_returns_405() {
        let app = test_router();
        let request = Request::builder()
            .method("POST")
            .uri("/health")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::METHOD_NOT_ALLOWED,
            "POST /health must return 405 Method Not Allowed"
        );
    }

    /// A deeply nested unknown path returns 404.
    #[tokio::test]
    async fn deeply_nested_unknown_path_returns_404() {
        let app = test_router();
        let request = Request::builder()
            .uri("/a/b/c/d/e/f")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::NOT_FOUND,
            "deeply nested unknown path must return 404"
        );
    }

    // ---- Authentication integration tests -----------------------------------

    /// When auth is enabled, GET /scenarios without Authorization returns 401.
    #[tokio::test]
    async fn auth_enabled_no_header_returns_401() {
        let app = test_router_with_key("test-secret");
        let request = Request::builder()
            .uri("/scenarios")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "GET /scenarios without auth must return 401"
        );

        let body_bytes = response.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
        assert_eq!(body["error"], "unauthorized");
    }

    /// When auth is enabled, GET /scenarios with wrong key returns 401.
    #[tokio::test]
    async fn auth_enabled_wrong_key_returns_401() {
        let app = test_router_with_key("correct-key");
        let request = Request::builder()
            .uri("/scenarios")
            .header("authorization", "Bearer wrong-key")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "GET /scenarios with wrong key must return 401"
        );

        let body_bytes = response.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
        assert_eq!(body["detail"], "invalid API key");
    }

    /// When auth is enabled, GET /scenarios with correct key passes through.
    #[tokio::test]
    async fn auth_enabled_correct_key_returns_200() {
        let app = test_router_with_key("my-secret");
        let request = Request::builder()
            .uri("/scenarios")
            .header("authorization", "Bearer my-secret")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::OK,
            "GET /scenarios with correct key must return 200"
        );
    }

    /// When auth is enabled, GET /health is still public (no auth required).
    #[tokio::test]
    async fn auth_enabled_health_remains_public() {
        let app = test_router_with_key("secret");
        let request = Request::builder()
            .uri("/health")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::OK,
            "GET /health must return 200 even when auth is enabled"
        );
    }

    #[tokio::test]
    async fn auth_enabled_ready_remains_public() {
        let app = test_router_with_key("secret");
        let request = Request::builder()
            .uri("/ready")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::OK,
            "GET /ready must answer without a bearer token"
        );
    }

    /// When no API key is configured, GET /scenarios is publicly accessible.
    #[tokio::test]
    async fn no_auth_scenarios_accessible() {
        let app = test_router();
        let request = Request::builder()
            .uri("/scenarios")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::OK,
            "GET /scenarios must return 200 when no auth is configured"
        );
    }

    /// When auth is enabled, unknown routes still return 404, not 401.
    #[tokio::test]
    async fn auth_enabled_unknown_route_returns_404() {
        let app = test_router_with_key("secret");
        let request = Request::builder()
            .uri("/nonexistent")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::NOT_FOUND,
            "unknown route must return 404 even when auth is enabled"
        );
    }

    /// When auth is enabled, DELETE /scenarios/{id} without auth returns 401.
    #[tokio::test]
    async fn auth_enabled_delete_scenario_returns_401() {
        let app = test_router_with_key("secret");
        let request = Request::builder()
            .method("DELETE")
            .uri("/scenarios/some-id")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "DELETE /scenarios/{{id}} without auth must return 401"
        );
    }

    /// When auth is enabled, POST /scenarios without auth returns 401.
    #[tokio::test]
    async fn auth_enabled_post_scenario_returns_401() {
        let app = test_router_with_key("secret");
        let request = Request::builder()
            .method("POST")
            .uri("/scenarios")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "POST /scenarios without auth must return 401"
        );
    }
}