harn-serve 0.8.92

Shared outbound workflow server core for Harn adapters
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
465
466
//! Transport completeness primitives for `harn-serve` HTTP routers.
//!
//! `harn-serve` adapters (API / A2A / MCP) build an `axum::Router` and
//! then call [`apply_transport_layers`] to wrap it with a stack of
//! tower middlewares that round out the HTTP surface beyond the
//! response-codec MVP (A.4 / #2501):
//!
//! * **Compression** — gzip / brotli / zstd negotiation via the
//!   request's `Accept-Encoding`, with the codec's response body
//!   transparently encoded when worthwhile.
//! * **ETag + conditional GET** — strong ETag attached to JSON `GET` /
//!   `HEAD` responses; matching `If-None-Match` short-circuits to
//!   `304 Not Modified`.
//! * **CORS** — declarative `cors { origin, methods, headers,
//!   credentials, max_age }` policy enforced at the layer boundary, so
//!   preflight requests answer without dispatching into a `.harn`
//!   handler.
//!
//! WebSocket upgrade lives in [`crate::ws`] because it needs to mount
//! per-route (axum can't middleware-upgrade); content negotiation,
//! ETag derivation, and multipart streaming are exposed to `.harn`
//! handlers via builtins in `harn_vm::stdlib::http_response` and
//! `harn_vm::stdlib::multipart`.

use axum::http::{Extensions, HeaderMap, HeaderValue, StatusCode, Version};
use axum::middleware::{self, Next};
use axum::Router;
use tower_http::compression::predicate::{And, DefaultPredicate};
use tower_http::compression::{CompressionLayer, Predicate};
use tower_http::cors::{AllowOrigin, CorsLayer};

mod etag;

pub use etag::compute_strong_etag;

/// Handler-set marker that opts the response out of compression. The
/// custom [`Predicate`] honours it; an outer middleware strips the
/// header before the response leaves the server so clients never see
/// the implementation detail.
///
/// `x-compress: never` is the only value that disables compression;
/// any other value (or absence of the header) leaves the default
/// predicate logic in effect.
pub const COMPRESSION_OPT_OUT_HEADER: &str = "x-compress";
pub const COMPRESSION_OPT_OUT_VALUE: &str = "never";

/// Bodies under this threshold skip compression entirely. Below ~512
/// bytes the encoder overhead (header framing + minimum CRC) usually
/// exceeds any savings. Tower-http's `DefaultPredicate` also filters
/// `Content-Type: text/event-stream` and a few other already-tiny or
/// pre-compressed types — see its source for the full list.
pub const COMPRESSION_MIN_SIZE_BYTES: u16 = 512;

/// Declarative CORS policy. `None` disables CORS entirely (no
/// `Access-Control-*` headers emitted, no preflight short-circuit).
#[derive(Clone, Debug, Default)]
pub struct CorsConfig {
    /// Explicit allowed origins. Matched as literal strings against
    /// `Origin`. Use `["*"]` (or set `allow_any_origin`) for the
    /// wildcard.
    pub allow_origins: Vec<String>,
    /// Send `Access-Control-Allow-Origin: *`. Per the CORS spec this
    /// is mutually exclusive with credentials, so `allow_credentials`
    /// is ignored when this is true.
    pub allow_any_origin: bool,
    /// Methods echoed in preflight responses. Defaults to the common
    /// safe verbs when empty.
    pub allow_methods: Vec<String>,
    /// Request headers allowed on cross-origin requests. Defaults to
    /// `Authorization`, `Content-Type`, `X-Request-Id` when empty.
    pub allow_headers: Vec<String>,
    /// Response headers exposed to JS beyond the CORS-safelist.
    pub expose_headers: Vec<String>,
    /// Permit cookies / `Authorization` on cross-origin requests.
    pub allow_credentials: bool,
    /// Max-age (seconds) for the preflight cache; defaults to 1 hour.
    pub max_age_seconds: Option<u32>,
}

impl CorsConfig {
    /// Permit any origin without credentials — the broad-open profile
    /// most public APIs use.
    pub fn allow_any() -> Self {
        Self {
            allow_any_origin: true,
            ..Self::default()
        }
    }
}

/// Configuration for the transport middleware stack. Adapters build
/// their router as usual, then wrap it via [`apply_transport_layers`].
#[derive(Clone, Debug, Default)]
pub struct TransportConfig {
    /// Enable `Accept-Encoding`-driven gzip / brotli / zstd
    /// compression.
    pub compression: bool,
    /// Attach a strong `ETag` to JSON `GET` / `HEAD` responses; honour
    /// `If-None-Match` with `304 Not Modified`.
    pub etag: bool,
    /// CORS policy. `None` disables CORS entirely.
    pub cors: Option<CorsConfig>,
}

impl TransportConfig {
    /// The standard transport stack: compression + ETag enabled, CORS
    /// off (adapters opt-in per-mount).
    pub fn default_enabled() -> Self {
        Self {
            compression: true,
            etag: true,
            cors: None,
        }
    }
}

/// Wrap an axum router with the configured transport layers.
///
/// Tower layers run outer-to-inner on the request and inner-to-outer
/// on the response. We want, on the response path: routes → ETag (sees
/// the uncompressed body, so the digest is stable across encodings) →
/// compression → CORS. `.layer()` registers each as a new outermost
/// layer, so the order below adds ETag innermost, then compression,
/// then CORS.
pub fn apply_transport_layers(mut router: Router, config: &TransportConfig) -> Router {
    if config.etag {
        router = etag::install_on(router);
    }
    if config.compression {
        router = router.layer(compression_layer());
        // The strip layer sits outside compression so the predicate sees
        // the marker on the response-path return; the strip runs after
        // and the client never observes the implementation header.
        router = router.layer(middleware::from_fn(strip_compression_marker));
    }
    if let Some(cors) = &config.cors {
        router = router.layer(build_cors_layer(cors));
    }
    router
}

fn compression_layer() -> CompressionLayer<And<HeaderOptOutPredicate, DefaultPredicate>> {
    CompressionLayer::new()
        .gzip(true)
        .br(true)
        .zstd(true)
        .compress_when(HeaderOptOutPredicate.and(DefaultPredicate::new()))
}

/// Returns `false` (i.e. don't compress) when the response carries
/// `x-compress: never`. Any other header value, or absence of the
/// header, defers to the next predicate in the chain. Implemented via
/// the closure-form [`Predicate`] blanket impl so the trait method
/// resolves through axum's re-exported `HeaderMap`/`StatusCode` types
/// without pulling in a direct `http-body` dependency.
#[derive(Clone, Copy, Debug, Default)]
pub struct HeaderOptOutPredicate;

impl Predicate for HeaderOptOutPredicate {
    fn should_compress<B>(&self, response: &axum::http::Response<B>) -> bool {
        opt_out_predicate(
            response.status(),
            response.version(),
            response.headers(),
            response.extensions(),
        )
    }
}

fn opt_out_predicate(
    _status: StatusCode,
    _version: Version,
    headers: &HeaderMap,
    _extensions: &Extensions,
) -> bool {
    !headers
        .get_all(COMPRESSION_OPT_OUT_HEADER)
        .iter()
        .any(|value| {
            value
                .to_str()
                .map(|s| s.eq_ignore_ascii_case(COMPRESSION_OPT_OUT_VALUE))
                .unwrap_or(false)
        })
}

async fn strip_compression_marker(
    req: axum::extract::Request,
    next: Next,
) -> axum::response::Response {
    let mut response = next.run(req).await;
    response.headers_mut().remove(COMPRESSION_OPT_OUT_HEADER);
    response
}

fn build_cors_layer(config: &CorsConfig) -> CorsLayer {
    let mut layer = CorsLayer::new();

    if config.allow_any_origin || config.allow_origins.iter().any(|origin| origin == "*") {
        layer = layer.allow_origin(AllowOrigin::any());
    } else if !config.allow_origins.is_empty() {
        let origins: Vec<HeaderValue> = config
            .allow_origins
            .iter()
            .filter_map(|origin| HeaderValue::from_str(origin).ok())
            .collect();
        layer = layer.allow_origin(AllowOrigin::list(origins));
    }

    let methods: Vec<axum::http::Method> = if config.allow_methods.is_empty() {
        ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
            .into_iter()
            .filter_map(|m| m.parse().ok())
            .collect()
    } else {
        config
            .allow_methods
            .iter()
            .filter_map(|m| m.parse().ok())
            .collect()
    };
    layer = layer.allow_methods(methods);

    let header_names: Vec<axum::http::HeaderName> = if config.allow_headers.is_empty() {
        ["authorization", "content-type", "x-request-id"]
            .into_iter()
            .filter_map(|h| h.parse().ok())
            .collect()
    } else {
        config
            .allow_headers
            .iter()
            .filter_map(|h| h.parse().ok())
            .collect()
    };
    layer = layer.allow_headers(header_names);

    if !config.expose_headers.is_empty() {
        let exposed: Vec<axum::http::HeaderName> = config
            .expose_headers
            .iter()
            .filter_map(|h| h.parse().ok())
            .collect();
        layer = layer.expose_headers(exposed);
    }

    if config.allow_credentials && !config.allow_any_origin {
        layer = layer.allow_credentials(true);
    }

    let max_age = config.max_age_seconds.unwrap_or(3600);
    layer.max_age(std::time::Duration::from_secs(max_age as u64))
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::{to_bytes, Body};
    use axum::http::{header, Method, Request, StatusCode};
    use axum::response::IntoResponse;
    use axum::routing::get;
    use tower::ServiceExt;

    fn sample_router() -> Router {
        Router::new().route(
            "/json",
            get(|| async {
                axum::Json(serde_json::json!({
                    "data": "x".repeat(2048),
                }))
            }),
        )
    }

    #[tokio::test]
    async fn compression_layer_gzips_when_accepted() {
        let app = apply_transport_layers(sample_router(), &TransportConfig::default_enabled());
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/json")
                    .header(header::ACCEPT_ENCODING, "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(header::CONTENT_ENCODING)
                .map(HeaderValue::to_str)
                .transpose()
                .unwrap(),
            Some("gzip"),
        );
    }

    #[tokio::test]
    async fn compression_layer_skipped_without_accept_encoding() {
        let app = apply_transport_layers(sample_router(), &TransportConfig::default_enabled());
        let response = app
            .oneshot(Request::builder().uri("/json").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert!(!response.headers().contains_key(header::CONTENT_ENCODING));
    }

    #[tokio::test]
    async fn cors_preflight_returns_allow_headers() {
        let config = TransportConfig {
            compression: false,
            etag: false,
            cors: Some(CorsConfig {
                allow_origins: vec!["https://app.example.com".into()],
                ..Default::default()
            }),
        };
        let app = apply_transport_layers(sample_router(), &config);
        let response = app
            .oneshot(
                Request::builder()
                    .method(Method::OPTIONS)
                    .uri("/json")
                    .header(header::ORIGIN, "https://app.example.com")
                    .header("access-control-request-method", "GET")
                    .header("access-control-request-headers", "authorization")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(response.status().is_success());
        assert_eq!(
            response
                .headers()
                .get("access-control-allow-origin")
                .unwrap(),
            "https://app.example.com"
        );
        assert!(response
            .headers()
            .get("access-control-allow-methods")
            .unwrap()
            .to_str()
            .unwrap()
            .contains("GET"));
    }

    #[tokio::test]
    async fn cors_disabled_emits_no_headers() {
        let app = apply_transport_layers(sample_router(), &TransportConfig::default_enabled());
        let response = app
            .oneshot(
                Request::builder()
                    .method(Method::OPTIONS)
                    .uri("/json")
                    .header(header::ORIGIN, "https://app.example.com")
                    .header("access-control-request-method", "GET")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(!response
            .headers()
            .contains_key("access-control-allow-origin"));
    }

    #[tokio::test]
    async fn handler_x_compress_never_skips_compression_and_strips_marker() {
        let app = apply_transport_layers(
            Router::new().route(
                "/raw",
                get(|| async {
                    let mut response = axum::Json(serde_json::json!({
                        "data": "x".repeat(2048),
                    }))
                    .into_response();
                    response.headers_mut().insert(
                        COMPRESSION_OPT_OUT_HEADER,
                        HeaderValue::from_static(COMPRESSION_OPT_OUT_VALUE),
                    );
                    response
                }),
            ),
            &TransportConfig::default_enabled(),
        );
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/raw")
                    .header(header::ACCEPT_ENCODING, "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert!(
            !response.headers().contains_key(header::CONTENT_ENCODING),
            "x-compress: never must skip compression",
        );
        assert!(
            !response.headers().contains_key(COMPRESSION_OPT_OUT_HEADER),
            "marker header must be stripped before flushing to client",
        );
    }

    #[tokio::test]
    async fn handler_x_compress_other_value_still_compresses() {
        let app = apply_transport_layers(
            Router::new().route(
                "/maybe",
                get(|| async {
                    let mut response = axum::Json(serde_json::json!({
                        "data": "x".repeat(2048),
                    }))
                    .into_response();
                    // Anything other than the literal "never" leaves
                    // the default predicate in charge.
                    response
                        .headers_mut()
                        .insert(COMPRESSION_OPT_OUT_HEADER, HeaderValue::from_static("auto"));
                    response
                }),
            ),
            &TransportConfig::default_enabled(),
        );
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/maybe")
                    .header(header::ACCEPT_ENCODING, "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            response
                .headers()
                .get(header::CONTENT_ENCODING)
                .map(HeaderValue::to_str)
                .transpose()
                .unwrap(),
            Some("gzip"),
        );
        // Strip layer is unconditional — the marker is removed even
        // when the value didn't disable compression.
        assert!(!response.headers().contains_key(COMPRESSION_OPT_OUT_HEADER));
    }

    #[tokio::test]
    async fn pipeline_yields_uncompressed_body_when_no_accept_encoding() {
        let app = apply_transport_layers(sample_router(), &TransportConfig::default_enabled());
        let response = app
            .oneshot(Request::builder().uri("/json").body(Body::empty()).unwrap())
            .await
            .unwrap();
        let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(parsed["data"].as_str().unwrap().starts_with("xxxx"));
    }
}