sdforge 0.5.0-rc.4

Multi-protocol SDK framework with unified macro configuration
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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT

use super::*;
use crate::config::ConfigError;
use crate::core::Registration;
use axum::Router;
use axum::body::Body;
use uuid::Uuid;

/// Construct a `RateLimitLayer` from any `HttpRequestRateLimiter`.
///
/// Convenience helper: wraps `RateLimitLayer::new` so users can write
/// `Router::new().layer(rate_limit_layer(limiter))` without importing both
/// `RateLimitLayer` and the `HttpRequestRateLimiter` trait.
///
/// Only available when the `ratelimit-http` feature is enabled.
#[cfg(feature = "ratelimit-http")]
pub fn rate_limit_layer(
    limiter: std::sync::Arc<dyn crate::security::HttpRequestRateLimiter>,
) -> RateLimitLayer {
    RateLimitLayer::new(limiter)
}

/// Generate or extract request ID from request.
///
/// A blank `x-request-id` header falls through to UUID generation, matching
/// the `context` middleware's handling of empty inbound ids.
#[cfg_attr(feature = "context", allow(dead_code))]
pub(crate) fn get_or_generate_request_id(req: &axum::http::Request<Body>) -> String {
    req.headers()
        .get(X_REQUEST_ID)
        .and_then(|v| v.to_str().ok())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .unwrap_or_else(|| Uuid::new_v4().to_string())
}

impl HttpRoute {
    #[allow(missing_docs)]
    pub fn new(
        path: String,
        handler: MethodRouter,
        metadata: ApiMetadata,
        module_prefix: Option<String>,
    ) -> Self {
        Self {
            path,
            handler,
            metadata,
            module_prefix,
        }
    }

    /// Get route path
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Get handler
    pub fn handler(&self) -> &MethodRouter {
        &self.handler
    }

    /// Get metadata
    pub fn metadata(&self) -> &ApiMetadata {
        &self.metadata
    }

    /// Get module prefix
    pub fn module_prefix(&self) -> Option<&str> {
        self.module_prefix.as_deref()
    }
}

/// Resolve module prefix for a route path
///
/// This function checks if there's a module prefix available for the given route.
/// In practice, the macro generates inline path resolution, but this provides
/// a runtime fallback for dynamic path construction.
pub(crate) fn resolve_route_path(base_path: &str, module_prefix: Option<&str>) -> String {
    match module_prefix {
        Some(prefix) if !prefix.is_empty() => {
            // Remove leading slash from prefix if present
            let clean_prefix = prefix.trim_start_matches('/');
            // HIGH 修复(#38):防御性切片——此前 `base_path[1..]` 假定首字符
            // 必为 '/',空串会越界 panic、多字节首字符会 panic(非 char
            // boundary)、无前导斜杠会静默丢首字符。改用 strip_prefix 语义。
            let path_without_slash = base_path.strip_prefix('/').unwrap_or(base_path);
            format!("/{}/{}", clean_prefix, path_without_slash)
        }
        _ => base_path.to_string(),
    }
}

pub(crate) fn apply_security_headers(router: Router) -> Router {
    SecurityHeaders::default().apply(router)
}

/// True when a route already occupies `path` (module-prefix resolved).
///
/// Built-in probe/metrics mounting skips paths already claimed by
/// user routes to avoid axum duplicate-route panics.
// 消费方:health 探针挂载、metrics 挂载、health 门控测试——
// 两 feature 皆关时无消费方,不参与编译。
#[cfg(any(feature = "health", feature = "metrics"))]
pub(crate) fn route_path_taken(path: &str) -> bool {
    use crate::core::Registration;
    let mut taken = false;
    for registration in inventory::iter::<RouteRegistration>() {
        let route = registration.create();
        let full = resolve_route_path(route.path(), route.module_prefix());
        if full == path {
            taken = true;
            break;
        }
    }
    if !taken {
        for route in inventory::iter::<HttpRoute>() {
            let full = resolve_route_path(route.path(), route.module_prefix());
            if full == path {
                taken = true;
                break;
            }
        }
    }
    taken
}

/// Prevent linker from optimizing away inventory registrations
/// Uses reference iteration to ensure symbols are preserved
#[cfg(feature = "mcp")]
#[inline(never)]
pub(crate) fn preserve_mcp_inventory() {
    // Iterate and count - this forces linker to keep symbols
    let _count = inventory::iter::<crate::mcp::McpToolRegistration>().count();
    let _ = _count; // Suppress unused variable warning
}

/// Prevent linker from optimizing away WebSocket inventory registrations
#[cfg(feature = "websocket")]
#[inline(never)]
pub(crate) fn preserve_websocket_inventory() {
    let _count = inventory::iter::<crate::websocket::WebSocketRoute>().count();
    let _ = _count;
}

/// Prevent linker from optimizing away gRPC inventory registrations
#[cfg(feature = "grpc")]
#[inline(never)]
pub(crate) fn preserve_grpc_inventory() {
    let _count = inventory::iter::<crate::grpc::GrpcRouteRegistration>().count();
    let _ = _count;
}

/// Build HTTP router from registered routes
///
/// This function collects all routes registered via `inventory::submit!`
/// and builds a complete Axum router for serving HTTP requests.
/// Routes are automatically prefixed with their module prefix if available.
///
/// # Returns
/// A basic Axum router with all registered routes
///
/// # Note
/// This is the simplest router building function. For production use,
/// consider using `build_with_config()` for middleware support.
pub fn build() -> Router {
    // Force inventory collection to prevent linker optimization
    // Using inline(never) functions to ensure symbols are preserved
    #[cfg(feature = "mcp")]
    preserve_mcp_inventory();

    #[cfg(feature = "websocket")]
    preserve_websocket_inventory();

    #[cfg(feature = "grpc")]
    preserve_grpc_inventory();

    let mut router = Router::new();

    // First, collect registrations with function pointers
    let registrations: Vec<_> = inventory::iter::<RouteRegistration>().collect();

    // Map registrations to HttpRoute instances via their create functions
    let mut routes: Vec<_> = registrations
        .iter()
        .map(|registration| registration.create())
        .collect();

    // Also collect direct HttpRoute registrations
    for route in inventory::iter::<HttpRoute>() {
        routes.push(route.clone());
    }

    // Compute the full path (with module prefix) for each route, then
    // deduplicate by full path. Without this, registering the same path
    // via both RouteRegistration and a direct HttpRoute (or twice within
    // either source) would cause Axum to panic with "Cannot register
    // duplicate route" at runtime.
    //
    // Resolution order: later registrations win. Direct HttpRoute entries
    // are appended after RouteRegistration entries, so they take precedence
    // — which matches the expectation that explicit registrations override
    // macro-generated ones.
    //
    // CRITICAL: dedup must group by path but MERGE MethodRouters, never
    // discard entries. Keying by path alone silently dropped distinct
    // methods on the same path (e.g. GET list + POST create on
    // `/api/x/resources`), turning the dropped method into 405 responses.
    // `MethodRouter::merge` keeps per-method "later wins" semantics while
    // preserving coexisting methods on one path.
    let mut seen: std::collections::HashMap<String, MethodRouter> =
        std::collections::HashMap::with_capacity(routes.len());
    for route in routes {
        let prefix = route.module_prefix.as_deref();
        let full_path = resolve_route_path(&route.path, prefix);
        match seen.get_mut(&full_path) {
            Some(existing) => {
                *existing = std::mem::take(existing).merge(route.handler);
            }
            None => {
                seen.insert(full_path, route.handler);
            }
        }
    }

    // Sort by full path for deterministic router construction order.
    let mut deduped: Vec<_> = seen.into_iter().collect();
    deduped.sort_by(|a, b| a.0.cmp(&b.0));

    for (full_path, handler) in deduped {
        router = router.route(&full_path, handler);
    }

    router
}

/// Build HTTP router with version redirect middleware
///
/// This function builds a router with automatic version redirect support.
/// Requests to `/api/{path}` without a version are redirected to `/api/v1/{path}`.
///
/// # Returns
/// An Axum router with version redirect middleware applied
///
/// # Note
/// Use this when you want automatic version fallback for unversioned API requests.
///
/// # Security Warning(HIGH 修复 #147,补充文档警示)
///
/// 与 [`build`] 一样,此便捷函数**不挂载任何安全/配置中间件**(无 CORS、
/// security headers、body limit、timeout、auth)。仅版本重定向中间件会
/// 被叠加。生产用途请使用 [`build_with_config`]。
pub fn build_with_redirect() -> Router {
    let router = build();
    router.layer(axum::middleware::from_fn(version_redirect_middleware))
}

/// Build HTTP router with configuration
///
/// This function builds a router with configuration-driven middleware and settings.
/// Applies CORS, authentication, rate limiting, and logging based on the provided config.
///
/// # Arguments
/// * `config` - The application configuration
///
/// # Returns
/// A configured Axum router with all middleware applied
///
/// # Note
/// This is the recommended function for production use. It applies security headers,
/// CORS, rate limiting, compression, and timeout middleware based on the config.
pub fn build_with_config(config: &crate::config::AppConfig) -> Result<Router, ConfigError> {
    #[cfg(feature = "security")]
    use std::sync::Arc;

    // Fail fast on nonsensical server limits (e.g. max_body_size = 0 rejects
    // every request with a body; request_timeout_secs = 0 times out every
    // request) instead of wiring middleware that bricks the app.
    config.server.validate()?;

    let mut router = build();

    // request metrics middleware (count / latency / status per route
    // template). Installed early so every route from build() is measured;
    // the /metrics endpoint itself is mounted after the auth layer below and
    // therefore not self-recorded.
    #[cfg(feature = "metrics")]
    {
        router = router.layer(axum::middleware::from_fn(crate::metrics::record_middleware));
    }

    // request-span middleware (OTLP export via sdforge::otel).
    #[cfg(feature = "otel")]
    {
        router = router.layer(axum::middleware::from_fn(crate::otel::otel_span_middleware));
    }

    // ETag/If-None-Match conditional requests for GET responses.
    #[cfg(feature = "etag")]
    {
        router = router.layer(axum::middleware::from_fn(
            crate::http::etag::etag_middleware,
        ));
    }

    // processor pre/post hook pipeline (active when hooks installed).
    #[cfg(feature = "hooks")]
    {
        router = router.layer(axum::middleware::from_fn(crate::hooks::hooks_middleware));
    }

    // Request ID middleware (first to ensure all requests have an ID).
    // with the `context` feature the richer context middleware
    // (request_id + trace_id + task-local scope + response echo) subsumes it.
    #[cfg(not(feature = "context"))]
    {
        router = router.layer(axum::middleware::from_fn(
            |mut req: axum::http::Request<Body>, next: axum::middleware::Next| async move {
                let request_id = get_or_generate_request_id(&req);
                // Safely insert request ID header — fall back to a static placeholder
                // if the value contains non-ASCII characters (prevents panic on malformed client input)
                let header_value = axum::http::HeaderValue::from_str(&request_id)
                    .unwrap_or_else(|_| axum::http::HeaderValue::from_static("invalid-request-id"));
                req.headers_mut().insert(
                    axum::http::header::HeaderName::from_static(X_REQUEST_ID),
                    header_value.clone(),
                );
                let mut response = next.run(req).await;
                response.headers_mut().insert(
                    axum::http::header::HeaderName::from_static(X_REQUEST_ID),
                    header_value,
                );
                response
            },
        ));
    }
    #[cfg(feature = "context")]
    {
        router = router.layer(axum::middleware::from_fn(
            crate::context::context_middleware,
        ));
    }

    // Apply global body limit(HIGH 修复:来自 ServerConfig::max_body_size,
    // 此前硬编码 10MB 且配置结构无对应字段,运维无法调整)
    router = router.layer(tower_http::limit::RequestBodyLimitLayer::new(
        config.server.max_body_size,
    ));

    // Apply response compression
    router = router.layer(tower_http::compression::CompressionLayer::new());

    // Use configurable request timeout from server config
    let timeout_secs = config.server.request_timeout_secs;
    router = router.layer(tower_http::timeout::TimeoutLayer::with_status_code(
        axum::http::StatusCode::REQUEST_TIMEOUT,
        std::time::Duration::from_secs(timeout_secs),
    ));

    // Apply CORS
    if let Some(cors) = &config.server.cors {
        let cors_layer = crate::config::build_cors_layer(cors)?;
        router = router.layer(cors_layer);
    }

    // Apply security headers
    router = apply_security_headers(router);

    // Apply authentication middleware
    #[cfg(feature = "security")]
    {
        use crate::config::AuthConfig;
        use crate::security::{AppApiKeyAuth, AuthContext, AuthError, BearerAuth, auth_middleware};
        use axum::http::HeaderValue;

        let auth_config = &config.authentication;

        if let AuthConfig::ApiKey {
            header_name,
            prefix,
            keys,
        } = auth_config
        {
            // diting HIGH-003:播种配置声明的 key;为空时显式构建错误,
            // 不再静默创建空 key store 把整条 API 锁死在 401。
            if keys.is_empty() {
                return Err(ConfigError::ValidationError(
                    "ApiKey auth is configured but no keys are provided: add `keys` entries \
                     (AuthConfig::ApiKey { keys: vec![ApiKeySeed { key, permissions }], .. }) \
                     so the API is not silently locked out"
                        .to_string(),
                ));
            }
            let auth = Arc::new(AppApiKeyAuth::new());
            for seed in keys {
                auth.add_key(seed.key.clone(), seed.permissions.clone());
            }
            let auth_clone = auth.clone();
            let header_name = header_name.clone();
            let prefix = prefix.clone();
            let extract_auth =
                move |req: &axum::http::Request<Body>| -> Result<AuthContext, AuthError> {
                    // Get header value; if missing or malformed, return auth error immediately
                    let header_value = match req
                        .headers()
                        .get(&header_name)
                        .and_then(|v: &HeaderValue| v.to_str().ok())
                    {
                        Some(value) => value,
                        None => return Err(AuthError::MissingAuth),
                    };

                    // Use trusted-proxy-aware IP extraction (vuln-0001 fix):
                    // direct header reads allow IP spoofing; extract_client_ip_core
                    // only trusts X-Forwarded-For / X-Real-IP from trusted proxies.
                    let client_ip = crate::security::extract_client_ip_core(req)
                        .unwrap_or_else(|| "unknown".to_string());

                    // Security fix: Validate prefix is not empty before checking
                    // This prevents authentication bypass when prefix is empty
                    if prefix.is_empty() {
                        return Err(AuthError::MissingAuth);
                    }

                    if header_value.starts_with(&prefix) {
                        let key = &header_value[prefix.len()..];
                        if let Some(permissions) = auth.validate_key(key, &client_ip) {
                            Ok(AuthContext {
                                user_id: Some(AppApiKeyAuth::key_id(key)),
                                permissions,
                                metadata: crate::security::AuthMetadata::default(),
                            })
                        } else {
                            Err(AuthError::MissingAuth)
                        }
                    } else {
                        Err(AuthError::MissingAuth)
                    }
                };
            let middleware = auth_middleware(auth_clone, extract_auth);
            router = router.layer(axum::middleware::from_fn(middleware));
        } else if let AuthConfig::Jwt { secret, .. } = auth_config {
            // 使用 try_new 而非 new:AuthConfig::validate() 接受的 secret(仅长度+弱词校验)
            // 可能不满足 BearerAuth 的强复杂度要求,`new` 会在启动时 panic;
            // 改为返回构建错误,由调用方处理而非崩溃(diting HIGH-005)。
            let auth = Arc::new(
                BearerAuth::try_new(secret)
                    .map_err(|e| ConfigError::ValidationError(e.to_string()))?,
            );
            let auth_clone = auth.clone();
            let extract_auth =
                move |req: &axum::http::Request<Body>| -> Result<AuthContext, AuthError> {
                    // Validate authorization header is present and properly formatted
                    // Empty or malformed headers must be rejected to prevent authentication bypass
                    let header_value = match req
                        .headers()
                        .get("authorization")
                        .and_then(|v: &HeaderValue| v.to_str().ok())
                    {
                        Some(value) => value,
                        None => return Err(AuthError::MissingAuth),
                    };

                    // Validate Bearer token format and non-empty token
                    // Note: "".strip_prefix("Bearer ") returns Some("") - empty token must be rejected
                    let token = match header_value.strip_prefix("Bearer ") {
                        Some(token) if !token.is_empty() => token,
                        _ => return Err(AuthError::InvalidToken),
                    };

                    if let Some(context) = auth.validate_token(token) {
                        Ok(context)
                    } else {
                        Err(AuthError::InvalidToken)
                    }
                };
            let middleware = auth_middleware(auth_clone, extract_auth);
            router = router.layer(axum::middleware::from_fn(middleware));
        }
        // OAuth2 is already checked before this block
        // None is handled by doing nothing
    }

    // mount /healthz + /readyz AFTER the auth layer — axum layers only
    // apply to routes registered before them, so probes added here bypass
    // authentication/rate-limiting by construction. Paths already claimed by
    // user routes are skipped (prevents duplicate-route panics).
    #[cfg(feature = "health")]
    {
        router = crate::health::mount_probes(router);
    }

    // mount /metrics after the auth layer (bypasses authentication).
    #[cfg(feature = "metrics")]
    {
        router = crate::metrics::mount_metrics(router);
    }

    // Note: 日志初始化已移除,由使用方通过 sdforge::inklog 直接管理
    Ok(router)
}