ave-http 0.11.0

HTTP API server for the Ave runtime, auth system, and admin surface
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
// Ave HTTP Auth System - Middleware
//
// Authentication and authorization middleware for Axum

use crate::auth::middleware::uuid::Uuid;

use super::database::{AuthDatabase, DatabaseError};
use super::http_api::request_result_from_status;
use super::models::{AuthContext, ErrorResponse};
use super::request_meta;
use ave_bridge::ProxyConfig;
use axum::{
    Json,
    extract::{ConnectInfo, FromRequestParts, Request},
    http::{StatusCode, request::Parts},
    middleware::Next,
    response::Response,
};
use rand::RngExt;
use std::fmt::Display;
use std::time::Instant;
use std::{net::SocketAddr, sync::Arc};
use tracing::{error, warn};

const TARGET: &str = "ave::http::auth";

// =============================================================================
// API KEY AUTHENTICATION EXTRACTOR
// =============================================================================

/// New API key authentication extractor that uses the database
///
/// This extractor validates the API key and provides full auth context.
/// Use this instead of the legacy ApiKeyAuth.
pub struct ApiKeyAuthNew;

impl<S> FromRequestParts<S> for ApiKeyAuthNew
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, Json<ErrorResponse>);

    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        // Check if auth database is available
        let auth_db = parts.extensions.get::<Arc<AuthDatabase>>().cloned();

        // If no auth database, auth is disabled - allow request
        let Some(db) = auth_db else {
            return Ok(Self);
        };
        let request_started = Instant::now();

        // Auth is enabled - validate API key
        let api_key = parts
            .headers
            .get("X-API-Key")
            .and_then(|v| v.to_str().ok())
            .ok_or_else(|| {
                (
                    StatusCode::UNAUTHORIZED,
                    Json(ErrorResponse {
                        error: "Missing X-API-Key header".to_string(),
                    }),
                )
            })?;

        // SECURITY FIX: Extract IP from socket address, not client headers
        // X-Forwarded-For and X-Real-IP can be spoofed to bypass rate limiting
        let ip_address = match (
            parts.extensions.get::<ConnectInfo<SocketAddr>>(),
            parts.extensions.get::<Arc<ProxyConfig>>(),
        ) {
            (Some(conn), Some(proxy)) => request_meta::resolve_client_ip(
                &parts.headers,
                conn.0,
                proxy.as_ref(),
            )
            .map(|ip| ip.to_string()),
            (Some(conn), None) => Some(conn.0.ip().to_string()),
            _ => None,
        };

        // SECURITY FIX: Pre-authentication rate limiting by IP
        // Check rate limit BEFORE verifying credentials to prevent brute force attacks
        let pre_auth_ip = ip_address.clone();
        let pre_auth_result = db
            .run_blocking("pre_auth_rate_limit", move |db| {
                db.check_rate_limit(
                    None,
                    pre_auth_ip.as_deref(),
                    Some("/auth/*"),
                )
            })
            .await;
        pre_auth_result.map_err(|e| {
            db.record_request_metrics(
                "api_key_auth",
                "rate_limited",
                request_started.elapsed(),
            );
            {
                warn!(
                    target: TARGET,
                    ip = ?ip_address,
                    error = %e,
                    "pre-auth rate limit exceeded"
                );
                (
                    StatusCode::TOO_MANY_REQUESTS,
                    Json(ErrorResponse {
                        error: format!("Rate limit exceeded: {}", e),
                    }),
                )
            }
        })?;

        let request_path = parts.uri.path().to_string();
        let auth_api_key = api_key.to_string();
        let auth_ip = ip_address.clone();
        let auth_ctx = db
            .run_blocking("authenticate_api_key_request", move |db| {
                db.authenticate_api_key_request(
                    &auth_api_key,
                    auth_ip.as_deref(),
                    &request_path,
                )
            })
            .await
            .map_err(|e| match e {
                DatabaseError::RateLimitExceeded(message) => {
                    db.record_request_metrics(
                        "api_key_auth",
                        "rate_limited",
                        request_started.elapsed(),
                    );
                    warn!(
                        target: TARGET,
                        ip = ?ip_address,
                        error = %message,
                        "authenticated request rate limited"
                    );
                    (
                        StatusCode::TOO_MANY_REQUESTS,
                        Json(ErrorResponse { error: message }),
                    )
                }
                DatabaseError::PasswordChangeRequired(message) => {
                    db.record_request_metrics(
                        "api_key_auth",
                        request_result_from_status(StatusCode::FORBIDDEN),
                        request_started.elapsed(),
                    );
                    warn!(
                        target: TARGET,
                        ip = ?ip_address,
                        error = %message,
                        "api key blocked pending password change"
                    );
                    (
                        StatusCode::FORBIDDEN,
                        Json(ErrorResponse { error: message }),
                    )
                }
                DatabaseError::PermissionDenied(_)
                | DatabaseError::AccountLocked(_) => {
                    db.record_request_metrics(
                        "api_key_auth",
                        request_result_from_status(StatusCode::UNAUTHORIZED),
                        request_started.elapsed(),
                    );
                    warn!(
                        target: TARGET,
                        ip = ?ip_address,
                        error = %e,
                        "api key authentication failed"
                    );
                    (
                        StatusCode::UNAUTHORIZED,
                        Json(ErrorResponse {
                            error: format!("Authentication failed: {}", e),
                        }),
                    )
                }
                other => {
                    db.record_request_metrics(
                        "api_key_auth",
                        request_result_from_status(
                            StatusCode::INTERNAL_SERVER_ERROR,
                        ),
                        request_started.elapsed(),
                    );
                    error!(
                        target: TARGET,
                        ip = ?ip_address,
                        error = %other,
                        "authentication pipeline failed"
                    );
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(ErrorResponse {
                            error:
                                "Internal error while authenticating request"
                                    .to_string(),
                        }),
                    )
                }
            })?;
        db.record_request_metrics(
            "api_key_auth",
            "success",
            request_started.elapsed(),
        );

        // Store auth context in request extensions for later use
        parts.extensions.insert(Arc::new(auth_ctx));

        Ok(Self)
    }
}

// =============================================================================
// AUTH CONTEXT EXTRACTOR
// =============================================================================

/// Extractor for getting the AuthContext from request extensions
///
/// This should be used after ApiKeyAuthNew to access user information and permissions.
pub struct AuthContextExtractor(pub Arc<AuthContext>);

impl<S> FromRequestParts<S> for AuthContextExtractor
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, Json<ErrorResponse>);

    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        let auth_ctx = parts
            .extensions
            .get::<Arc<AuthContext>>()
            .cloned()
            .ok_or_else(|| {
                (
                    StatusCode::UNAUTHORIZED,
                    Json(ErrorResponse {
                        error: "No authentication context found".to_string(),
                    }),
                )
            })?;

        Ok(Self(auth_ctx))
    }
}

// =============================================================================
// PERMISSION CHECK FUNCTION
// =============================================================================

/// Helper function to check if user has permission
///
/// Returns 403 Forbidden if permission is denied
pub fn check_permission(
    auth_ctx: &AuthContext,
    resource: &str,
    action: &str,
) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
    if !auth_ctx.has_permission(resource, action) {
        return Err((
            StatusCode::FORBIDDEN,
            Json(ErrorResponse {
                error: format!("Permission denied: {} on {}", action, resource),
            }),
        ));
    }
    Ok(())
}

// =============================================================================
// AUDIT LOGGING MIDDLEWARE
// =============================================================================

/// Middleware for audit logging
pub async fn audit_log_middleware(
    auth_ctx: Option<Arc<AuthContext>>,
    auth_db: Option<Arc<AuthDatabase>>,
    req: Request,
    next: Next,
) -> Response {
    let method = req.method().to_string();
    let path = req.uri().path().to_string();
    let request_id = uuid::Uuid::new_v4().to_string();

    // SECURITY FIX: Get IP from socket address only, ignore client headers
    // X-Forwarded-For and X-Real-IP can be spoofed
    let request_meta =
        match (
            req.extensions().get::<ConnectInfo<SocketAddr>>(),
            req.extensions().get::<Arc<ProxyConfig>>(),
        ) {
            (Some(conn), Some(proxy)) => request_meta::extract_request_meta(
                req.headers(),
                conn.0,
                proxy.as_ref(),
            ),
            (Some(conn), None) => request_meta::RequestMeta {
                ip_address: Some(conn.0.ip().to_string()),
                user_agent: req.headers().get("User-Agent").and_then(|value| {
                    value.to_str().ok().map(ToOwned::to_owned)
                }),
            },
            _ => request_meta::RequestMeta {
                ip_address: None,
                user_agent: req.headers().get("User-Agent").and_then(|value| {
                    value.to_str().ok().map(ToOwned::to_owned)
                }),
            },
        };
    let ip_address = request_meta.ip_address;
    let user_agent = request_meta.user_agent;

    // Process request
    let response = next.run(req).await;

    // Avoid double logging for login (explicitly logged elsewhere)
    if path == "/login" {
        return response;
    }

    // Log to audit if database is available
    if let Some(db) = auth_db {
        let success = response.status().is_success();
        let error_message = if !success {
            Some(format!("HTTP {}", response.status()))
        } else {
            None
        };

        // If we have auth_ctx, use normal logging
        if let Some(ctx) = auth_ctx {
            let ctx = (*ctx).clone();
            let path_for_log = path.clone();
            let method_for_log = method.clone();
            let ip_for_log = ip_address.clone();
            let user_agent_for_log = user_agent.clone();
            let request_id_for_log = request_id.clone();
            let error_for_log = error_message.clone();
            if let Err(e) = db
                .run_blocking("log_api_request", move |db| {
                    db.log_api_request(
                        &ctx,
                        crate::auth::database_audit::ApiRequestParams {
                            path: &path_for_log,
                            method: &method_for_log,
                            ip_address: ip_for_log.as_deref(),
                            user_agent: user_agent_for_log.as_deref(),
                            request_id: &request_id_for_log,
                            success,
                            error_message: error_for_log.as_deref(),
                        },
                    )
                })
                .await
            {
                error!(target: TARGET, error = %e, "failed to write request audit log");
            }
        } else {
            // No auth context - log as unauthenticated request
            let path_for_log = path.clone();
            let method_for_log = method.clone();
            let ip_for_log = ip_address.clone();
            let user_agent_for_log = user_agent.clone();
            let request_id_for_log = request_id.clone();
            let error_for_log = error_message.clone();
            let details = format!("{} {}", method, path);
            if let Err(e) = db
                .run_blocking("create_unauthenticated_audit_log", move |db| {
                    db.create_audit_log(
                        crate::auth::database_audit::AuditLogParams {
                            user_id: None,
                            api_key_id: None,
                            action_type: if success {
                                "unauthenticated_request_success"
                            } else {
                                "unauthenticated_request_failed"
                            },
                            endpoint: Some(&path_for_log),
                            http_method: Some(&method_for_log),
                            ip_address: ip_for_log.as_deref(),
                            user_agent: user_agent_for_log.as_deref(),
                            request_id: Some(&request_id_for_log),
                            details: Some(&details),
                            success,
                            error_message: error_for_log.as_deref(),
                        },
                    )
                })
                .await
            {
                error!(target: TARGET, error = %e, "failed to write audit log");
            }
        }
    }

    response
}

// Need to add uuid dependency
// For now, let's create a simple request ID generator
mod uuid {
    pub struct Uuid;

    impl Uuid {
        pub const fn new_v4() -> Self {
            Self
        }
    }
}

impl Display for Uuid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut rng = rand::rng();

        write!(
            f,
            "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
            rng.random::<u32>(),
            rng.random::<u16>(),
            rng.random::<u16>(),
            rng.random::<u16>(),
            rng.random::<u64>() & 0xFFFF_FFFF_FFFF,
        )
    }
}