minco-http 0.5.0

Axum and Tower HTTP conventions, principals, request IDs, limits, and RFC 9457 errors for Minco
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
use crate::middleware::{
    HttpConfigurationError, HttpHeaderPolicy, HttpRuntimeConfig, apply_standard_middleware,
};
use axum::Router;
use minco_core::{ApplicationGraph, FrozenContributions, PluginContext, PluginId};
use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};
use thiserror::Error;

/// One fully state-bound Axum router contributed by a statically linked plugin.
///
/// `minco-core` remains independent of Axum. HTTP-aware plugins contribute this
/// type through [`PluginContext::contributions`], and the application composition
/// root validates and merges all modules after plugin installation.
#[derive(Clone)]
pub struct HttpModule {
    pub plugin_id: PluginId,
    pub router: Router,
    /// OpenAPI/descriptor operation IDs implemented by this router fragment.
    ///
    /// Minco validates the union of these IDs against the operations declared by
    /// the plugin descriptor. The field does not attempt to introspect Axum's
    /// router internals; ownership remains explicit and machine-readable.
    pub operation_ids: BTreeSet<String>,
    /// Largest request body accepted by any route in this module.
    ///
    /// The application composition root uses this value to prevent a global
    /// Tower body limit from accidentally rejecting a route-specific upload
    /// limit. Individual routes must still configure their own smaller limits.
    pub max_request_body_bytes: Option<usize>,
    /// Exact header policy required only when this module is installed.
    pub header_policy: HttpHeaderPolicy,
}

impl HttpModule {
    pub const fn new(plugin_id: PluginId, router: Router) -> Self {
        Self {
            plugin_id,
            router,
            operation_ids: BTreeSet::new(),
            max_request_body_bytes: None,
            header_policy: HttpHeaderPolicy::empty(),
        }
    }

    /// Declares the contract operations implemented by this module.
    #[must_use]
    pub fn with_operations<I, S>(mut self, operation_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.operation_ids = operation_ids.into_iter().map(Into::into).collect();
        self
    }

    #[must_use]
    pub const fn with_max_request_body_bytes(mut self, maximum: usize) -> Self {
        self.max_request_body_bytes = Some(maximum);
        self
    }

    #[must_use]
    pub fn with_header_policy(mut self, policy: HttpHeaderPolicy) -> Self {
        self.header_policy = policy;
        self
    }

    /// Registers this module in deterministic plugin-installation order.
    pub fn contribute(self, context: &mut PluginContext<'_>) {
        context.contributions().push(Arc::new(self));
    }
}

impl std::fmt::Debug for HttpModule {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HttpModule")
            .field("plugin_id", &self.plugin_id)
            .field("operation_ids", &self.operation_ids)
            .field("max_request_body_bytes", &self.max_request_body_bytes)
            .field("header_policy", &self.header_policy)
            .finish_non_exhaustive()
    }
}

/// Verifies that HTTP contributions and plugin descriptors have an exact
/// operation-ID correspondence.
///
/// This closes the drift boundary between a plugin's contract/deployment graph
/// and its delivery module. Route method/path duplication is validated by
/// `minco-core`; this function proves that every declared operation is owned by
/// exactly one installed HTTP module and that no undeclared operation is exposed.
pub fn validate_plugin_http_modules(
    graph: &ApplicationGraph,
    contributions: &FrozenContributions,
) -> Result<(), HttpCompositionError> {
    let expected = graph
        .plugins
        .iter()
        .map(|plugin| {
            (
                plugin.id.clone(),
                plugin
                    .operations
                    .iter()
                    .map(|operation| operation.operation_id.clone())
                    .collect::<BTreeSet<_>>(),
            )
        })
        .collect::<BTreeMap<_, _>>();

    let mut actual = BTreeMap::<PluginId, BTreeSet<String>>::new();
    let mut owners = BTreeMap::<String, PluginId>::new();

    for module in contributions.get::<HttpModule>() {
        if !expected.contains_key(&module.plugin_id) {
            return Err(HttpCompositionError::UnknownPlugin(
                module.plugin_id.clone(),
            ));
        }
        let plugin_operations = actual.entry(module.plugin_id.clone()).or_default();
        for operation_id in &module.operation_ids {
            if !plugin_operations.insert(operation_id.clone()) {
                return Err(HttpCompositionError::DuplicateModuleOperation {
                    plugin: module.plugin_id.clone(),
                    operation_id: operation_id.clone(),
                });
            }
            if let Some(first) = owners.insert(operation_id.clone(), module.plugin_id.clone()) {
                return Err(HttpCompositionError::OperationOwnedByMultiplePlugins {
                    operation_id: operation_id.clone(),
                    first,
                    second: module.plugin_id.clone(),
                });
            }
        }
    }

    for (plugin, expected_operations) in expected {
        let actual_operations = actual.remove(&plugin).unwrap_or_default();
        if expected_operations != actual_operations {
            let missing = expected_operations
                .difference(&actual_operations)
                .cloned()
                .collect();
            let undeclared = actual_operations
                .difference(&expected_operations)
                .cloned()
                .collect();
            return Err(HttpCompositionError::OperationMismatch {
                plugin,
                missing,
                undeclared,
            });
        }
    }

    Ok(())
}

/// Merges every plugin-contributed router in deterministic installation order.
///
/// Call [`validate_plugin_http_modules`] first, or use [`compose_plugin_http`],
/// when the modules expose contract operations.
pub fn merge_plugin_http_modules(
    mut router: Router,
    contributions: &FrozenContributions,
) -> Router {
    for module in contributions.get::<HttpModule>() {
        router = router.merge(module.router.clone());
    }
    router
}

/// Returns the global request-body ceiling required by all installed HTTP modules.
///
/// This is intentionally the maximum, not a replacement for route-level limits.
/// It keeps the global middleware compatible with upload-capable plugins while
/// allowing ordinary JSON routes to retain stricter extractor limits.
#[must_use]
pub fn required_request_body_bytes(baseline: usize, contributions: &FrozenContributions) -> usize {
    contributions
        .get::<HttpModule>()
        .into_iter()
        .filter_map(|module| module.max_request_body_bytes)
        .fold(baseline, usize::max)
}

/// Returns the application policy plus the exact requirements of installed HTTP modules.
pub fn required_header_policy(
    baseline: &HttpHeaderPolicy,
    contributions: &FrozenContributions,
) -> Result<HttpHeaderPolicy, HttpConfigurationError> {
    let mut policy = baseline.clone();
    for module in contributions.get::<HttpModule>() {
        policy.merge(&module.header_policy)?;
    }
    Ok(policy)
}

/// Validates and merges plugin routes, then applies Minco's standard middleware
/// with an automatically expanded global body ceiling.
pub fn compose_plugin_http(
    router: Router,
    configuration: &HttpRuntimeConfig,
    graph: &ApplicationGraph,
    contributions: &FrozenContributions,
) -> Result<Router, HttpCompositionError> {
    validate_plugin_http_modules(graph, contributions)?;
    let mut effective = configuration.clone();
    effective.max_request_body_bytes =
        required_request_body_bytes(configuration.max_request_body_bytes, contributions);
    effective.header_policy = required_header_policy(&configuration.header_policy, contributions)?;
    apply_standard_middleware(merge_plugin_http_modules(router, contributions), &effective)
        .map_err(HttpCompositionError::InvalidConfiguration)
}

#[derive(Debug, Error)]
pub enum HttpCompositionError {
    #[error("HTTP module references plugin that is not in the application graph: {0}")]
    UnknownPlugin(PluginId),
    #[error("plugin {plugin} contributes operation {operation_id} more than once")]
    DuplicateModuleOperation {
        plugin: PluginId,
        operation_id: String,
    },
    #[error("operation {operation_id} is contributed by both plugin {first} and plugin {second}")]
    OperationOwnedByMultiplePlugins {
        operation_id: String,
        first: PluginId,
        second: PluginId,
    },
    #[error(
        "HTTP operations for plugin {plugin} do not match its descriptor; missing={missing:?}, undeclared={undeclared:?}"
    )]
    OperationMismatch {
        plugin: PluginId,
        missing: BTreeSet<String>,
        undeclared: BTreeSet<String>,
    },
    #[error("invalid HTTP middleware configuration: {0}")]
    InvalidConfiguration(#[from] HttpConfigurationError),
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{body::Body, routing::get};
    use minco_core::{ContributionCollection, GraphBuilder, OperationDescriptor, PluginDescriptor};
    use semver::Version;
    use tower::ServiceExt;

    fn graph_with_operations(plugin_id: &str, operation_ids: &[&str]) -> ApplicationGraph {
        let id = PluginId::new(plugin_id).unwrap();
        let mut descriptor = PluginDescriptor::new(id, Version::new(1, 0, 0), "test HTTP plugin");
        descriptor
            .operations
            .extend(
                operation_ids
                    .iter()
                    .map(|operation_id| OperationDescriptor {
                        operation_id: (*operation_id).to_owned(),
                        method: "GET".to_owned(),
                        path: format!("/{operation_id}"),
                        public: true,
                        idempotent: false,
                    }),
            );
        let mut builder = GraphBuilder::default();
        builder.add_plugin(descriptor);
        builder.build().unwrap()
    }

    #[tokio::test]
    async fn plugin_routers_are_merged_from_ordered_contributions() {
        let mut contributions = ContributionCollection::default();
        contributions.push(Arc::new(
            HttpModule::new(
                PluginId::new("first").unwrap(),
                Router::new().route("/first", get(|| async { "first" })),
            )
            .with_operations(["firstOperation"]),
        ));
        contributions.push(Arc::new(
            HttpModule::new(
                PluginId::new("second").unwrap(),
                Router::new().route("/second", get(|| async { "second" })),
            )
            .with_operations(["secondOperation"]),
        ));
        let router = merge_plugin_http_modules(Router::new(), &contributions.freeze());

        for path in ["/first", "/second"] {
            let response = router
                .clone()
                .oneshot(http::Request::get(path).body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert!(response.status().is_success(), "{path}");
        }
    }

    #[test]
    fn operation_inventory_must_match_the_plugin_descriptor() {
        let graph = graph_with_operations("feedback", &["createFeedback", "getFeedback"]);
        let mut contributions = ContributionCollection::default();
        contributions.push(Arc::new(
            HttpModule::new(PluginId::new("feedback").unwrap(), Router::new())
                .with_operations(["createFeedback"]),
        ));
        let error = validate_plugin_http_modules(&graph, &contributions.freeze()).unwrap_err();
        assert!(matches!(
            error,
            HttpCompositionError::OperationMismatch { .. }
        ));
    }

    #[test]
    fn exact_operation_inventory_is_accepted() {
        let graph = graph_with_operations("feedback", &["createFeedback", "getFeedback"]);
        let mut contributions = ContributionCollection::default();
        contributions.push(Arc::new(
            HttpModule::new(PluginId::new("feedback").unwrap(), Router::new())
                .with_operations(["createFeedback", "getFeedback"]),
        ));
        assert!(validate_plugin_http_modules(&graph, &contributions.freeze()).is_ok());
    }

    #[test]
    fn upload_capable_modules_raise_only_the_global_ceiling() {
        let mut contributions = ContributionCollection::default();
        contributions.push(Arc::new(
            HttpModule::new(PluginId::new("uploads").unwrap(), Router::new())
                .with_max_request_body_bytes(8 * 1024 * 1024),
        ));
        let frozen = contributions.freeze();
        assert_eq!(
            required_request_body_bytes(1024 * 1024, &frozen),
            8 * 1024 * 1024
        );
        assert_eq!(
            required_request_body_bytes(16 * 1024 * 1024, &frozen),
            16 * 1024 * 1024
        );
    }

    #[test]
    fn plugin_header_requirements_merge_and_deduplicate_exact_names() {
        let mut first = HttpHeaderPolicy::empty();
        first.allow_request_header_name("x-example-token").unwrap();
        first
            .mark_request_header_name_sensitive("x-example-token")
            .unwrap();
        let mut second = HttpHeaderPolicy::empty();
        second.allow_request_header_name("X-Example-Token").unwrap();
        second
            .expose_response_header_name("x-example-result")
            .unwrap();
        let mut contributions = ContributionCollection::default();
        contributions.push(Arc::new(
            HttpModule::new(PluginId::new("first").unwrap(), Router::new())
                .with_header_policy(first),
        ));
        contributions.push(Arc::new(
            HttpModule::new(PluginId::new("second").unwrap(), Router::new())
                .with_header_policy(second),
        ));

        let policy =
            required_header_policy(&HttpHeaderPolicy::default(), &contributions.freeze()).unwrap();
        let allowed = policy
            .allowed_request_headers()
            .into_iter()
            .map(|name| name.as_str().to_owned())
            .collect::<Vec<_>>();
        assert_eq!(
            allowed
                .iter()
                .filter(|name| name.as_str() == "x-example-token")
                .count(),
            1
        );
        assert!(
            policy
                .exposed_response_headers()
                .iter()
                .any(|name| name == "x-example-result")
        );
    }

    #[tokio::test]
    async fn installed_plugin_header_is_allowed_by_preflight() {
        let mut policy = HttpHeaderPolicy::empty();
        policy
            .allow_request_header_name("x-minco-feedback-token")
            .unwrap();
        let mut contributions = ContributionCollection::default();
        contributions.push(Arc::new(
            HttpModule::new(PluginId::new("feedback").unwrap(), Router::new())
                .with_header_policy(policy),
        ));
        let frozen = contributions.freeze();
        let graph = graph_with_operations("feedback", &[]);
        let router = compose_plugin_http(
            Router::new(),
            &HttpRuntimeConfig::default(),
            &graph,
            &frozen,
        )
        .unwrap();
        let response = router
            .oneshot(
                http::Request::builder()
                    .method(http::Method::OPTIONS)
                    .uri("/")
                    .header(http::header::ORIGIN, "http://127.0.0.1:3000")
                    .header(http::header::ACCESS_CONTROL_REQUEST_METHOD, "GET")
                    .header(
                        http::header::ACCESS_CONTROL_REQUEST_HEADERS,
                        "x-minco-feedback-token",
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let allowed = response
            .headers()
            .get(http::header::ACCESS_CONTROL_ALLOW_HEADERS)
            .and_then(|value| value.to_str().ok())
            .unwrap_or_default();
        assert!(allowed.contains("x-minco-feedback-token"), "{allowed}");
    }
}